feat(desktop): sync to a private Gitea repo, chosen by the URL

Same discriminant as the Android client - "/api/v1/repos/" in the URL - so one
address tells both ends which transport to speak, and nothing new appears in
Settings beyond a placeholder and a warning.

The bridge stays shared. Three things differ, and they are confined: the header
is "token <PAT>" rather than Basic (Gitea answers a silent 401 to the other),
a PUT carries a JSON envelope with the file base64-encoded inside it, and the
connection test uses GET because the contents API does not answer HEAD.

The sha does the ETag's whole job. It comes back from the pull, rides in the
PUT body instead of an If-Match, and a stale one earns a 409 - handled exactly
like WebDAV's 412, by re-running pull->merge->push so the other device's
changes are folded in rather than clobbered. On a first push `sha` is OMITTED
rather than sent empty: Gitea reads its presence as "replace that exact
version". `branch` is omitted too, so the repo's default is used instead of a
name we would be guessing.

A failing PUT now reads its response body: Gitea explains a 409 or a 422 there,
and without it the error was just a number.

The test button checks the SHAPE of what came back, not only the status. A URL
one path segment off answers 200 with valid JSON that is not a file - which
would otherwise surface much later as "wrong sync password" and send you
looking on the wrong side. Four tests cover that parsing, including the
line-wrapped base64 Gitea sends and the array an accidental directory URL
returns.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
r-zakarya
2026-08-17 14:37:39 +01:00
parent 6cab9b7c0a
commit c1d0eb3891
5 changed files with 206 additions and 20 deletions
+82 -8
View File
@@ -43,8 +43,34 @@ Bridge.onWebdavResult = function(reqId, status, payload, etag) {
delete _webdavResolvers[reqId];
r({ status: status | 0, payload: payload || '', etag: etag || '' });
};
// A Gitea repository, recognised by its contents-API path — the same
// discriminant the Android client uses, so one URL tells both ends which
// transport to speak. Everything below that differs is confined to the two
// call sites in runSyncNow(); the bridge itself is shared.
function syncIsGitea(url) {
return (url || '').toLowerCase().includes('/api/v1/repos/');
}
// Unwraps a Gitea contents response into { container, sha }. The API answers
// JSON whose `content` is the file in base64 — so the payload is base64 twice
// over: once by our bridge, once by Gitea. Returns null if the JSON is not
// the shape we expect, which is what a slightly-wrong URL produces: valid
// JSON, but not this.
function giteaUnwrap(bodyText) {
let obj;
try { obj = JSON.parse(bodyText); } catch (e) { return null; }
if (!obj || !obj.content || !obj.sha) return null;
if (obj.encoding && obj.encoding !== 'base64') return null;
try {
const raw = obj.content.replace(/[\r\n]/g, ''); // Gitea wraps its base64
return { container: new TextDecoder().decode(base64ToBytes(raw)), sha: obj.sha };
} catch (e) { return null; }
}
// method: 'get'|'put'|'test'. opts.ifMatch → sent as If-Match on a put so
// the server rejects (412) a write when the remote changed since our pull.
// On Gitea the sha travels inside the PUT body instead, and the bridge sends
// no If-Match.
function _webdavCall(method, url, user, pwd, dataB64, opts) {
opts = opts || {};
const reqId = 'dav_' + Date.now() + '_' + Math.random().toString(36).slice(2, 8);
@@ -188,6 +214,19 @@ async function syncTestConnection() {
if (!cfg || !cfg.url) return toast('Set the WebDAV URL first', 'warning');
toast('Testing connection…');
const r = await _webdavCall('test', cfg.url, cfg.user, cfg.pwd);
// A reachable Gitea with a valid token is not enough: a URL pointing one
// path segment off answers 200 with JSON that is not a file. Checking the
// shape here is what makes the test worth pressing.
if (syncIsGitea(cfg.url) && r.status >= 200 && r.status < 300) {
let un = null;
try {
un = giteaUnwrap(new TextDecoder().decode(base64ToBytes(r.payload || '')));
} catch (e) { /* traite comme une forme inattendue */ }
return un
? toast('Connection OK · file found in the repository')
: toast('Reached Gitea, but this URL does not return a file — ' +
'expected .../api/v1/repos/OWNER/REPO/contents/FILE', 'error');
}
if (r.status >= 200 && r.status < 400) {
toast('Connection OK (' + r.status + ')');
} else if (r.status === 404) {
@@ -526,14 +565,32 @@ async function runSyncNow(_attempt) {
// ETag of the version we just pulled — sent back as If-Match on the
// push so the server rejects our write if another device changed the
// file in between (optimistic concurrency, avoids lost updates).
const remoteEtag = pullResp.etag || '';
let remoteEtag = pullResp.etag || '';
// Decrypt + cross-account guard BEFORE touching local state, so a
// wrong sync password or a foreign account aborts cleanly.
let remoteSnap = null;
if (pullResp.status !== 404 && pullResp.payload) {
let jsonText;
try {
jsonText = new TextDecoder().decode(base64ToBytes(pullResp.payload));
} catch (e) {
syncStatus('');
return toast('Unreadable reply from the remote', 'error');
}
if (syncIsGitea(cfg.url)) {
const un = giteaUnwrap(jsonText);
if (!un) {
syncStatus('');
return toast('Gitea replied without content/sha — is the URL a ' +
'contents-API path to the file?', 'error');
}
jsonText = un.container;
// The blob sha takes the ETag's place, and plays exactly its role:
// it goes back on the push, and a stale one is refused.
remoteEtag = un.sha;
}
try {
const jsonText = new TextDecoder().decode(base64ToBytes(pullResp.payload));
const container = JSON.parse(jsonText);
remoteSnap = await decryptExportContainer(container, cfg.encPwd);
} catch (e) {
@@ -613,17 +670,34 @@ async function runSyncNow(_attempt) {
pushedCount = Array.isArray(snap.entries) ? snap.entries.length : 0;
syncStatus('Encrypting…');
const container = await encryptExportPayload(snap, cfg.encPwd);
const bodyBytes = new TextEncoder().encode(JSON.stringify(container, null, 2));
const containerBytes = new TextEncoder().encode(JSON.stringify(container, null, 2));
syncStatus('Pushing…');
const r = await _webdavCall('put', cfg.url, cfg.user, cfg.pwd,
bytesToBase64(bodyBytes),
{ ifMatch: remoteEtag });
let bodyB64, opts;
if (syncIsGitea(cfg.url)) {
// The file rides inside a JSON envelope, base64 again. `sha` is
// OMITTED rather than empty on a first push: Gitea reads its
// presence as "replace that exact version", and an empty one is
// not the same as none. `branch` is omitted too, so the repo's
// default branch is used instead of a name we would be guessing.
const env = {
message: 'sync from ' + (state.username || 'desktop'),
content: bytesToBase64(containerBytes)
};
if (remoteEtag) env.sha = remoteEtag;
bodyB64 = bytesToBase64(new TextEncoder().encode(JSON.stringify(env)));
opts = {};
} else {
bodyB64 = bytesToBase64(containerBytes);
opts = { ifMatch: remoteEtag };
}
const r = await _webdavCall('put', cfg.url, cfg.user, cfg.pwd, bodyB64, opts);
// 412 Precondition Failed = the remote changed since our pull
// (another device pushed). Re-run the whole pull→merge→push so we
// fold in their changes instead of clobbering them. Bounded to a
// few tries to avoid a livelock against a device syncing in a hot
// loop.
if (r.status === 412) {
// loop. Gitea says the same thing with 409: the sha we sent is no
// longer the file's.
if (r.status === 412 || r.status === 409) {
syncStatus('');
if (_attempt < 3) {
toast('Remote changed — re-syncing…');