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:
+82
-8
@@ -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…');
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// Le transport Gitea : reconnaissance de l'URL, et lecture de la reponse de
|
||||
// l'API des contenus.
|
||||
//
|
||||
// POURQUOI CES DEUX-LA. `giteaUnwrap` est le seul endroit du chemin de sync qui
|
||||
// interprete du JSON venu du reseau, et il decide de ce qui sera ensuite
|
||||
// dechiffre. Une URL a un segment pres rend du JSON valide qui n'est PAS un
|
||||
// fichier ; s'il passait, l'erreur ne se verrait qu'au message
|
||||
// « mot de passe de sync incorrect », qui envoie chercher la cause ailleurs.
|
||||
//
|
||||
// Le `sha` compte autant que le contenu : il repart en `sha` au push, et c'est
|
||||
// lui qui fait refuser une ecriture concurrente. Le rendre vide plutot
|
||||
// qu'absent ferait ecraser la version d'un autre appareil.
|
||||
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert');
|
||||
const { loadApp } = require('./harness');
|
||||
|
||||
function b64(text) {
|
||||
return Buffer.from(text, 'utf8').toString('base64');
|
||||
}
|
||||
|
||||
test('syncIsGitea: recognises a contents-API URL, ignores WebDAV', async () => {
|
||||
const { __test: t } = await loadApp();
|
||||
assert.equal(t.syncIsGitea(
|
||||
'https://git.example.com/api/v1/repos/Zaki/pm_sync/contents/vault-sync.json'), true);
|
||||
// Casse indifferente : l'URL est saisie a la main.
|
||||
assert.equal(t.syncIsGitea(
|
||||
'https://git.example.com/API/V1/REPOS/Zaki/pm_sync/contents/v.json'), true);
|
||||
// Une URL de depot n'est pas une URL d'API, et elle ne rendrait pas de sha.
|
||||
assert.equal(t.syncIsGitea('https://git.example.com/Zaki/pm_sync'), false);
|
||||
assert.equal(t.syncIsGitea('https://dav.example.com/remote.php/vault.json'), false);
|
||||
assert.equal(t.syncIsGitea(''), false);
|
||||
assert.equal(t.syncIsGitea(undefined), false);
|
||||
});
|
||||
|
||||
test('giteaUnwrap: returns the file and its sha', async () => {
|
||||
const { __test: t } = await loadApp();
|
||||
const container = '{"version":1,"cipher":"AAAA"}';
|
||||
const un = t.giteaUnwrap(JSON.stringify({
|
||||
content: b64(container), encoding: 'base64', sha: 'abc123', name: 'vault-sync.json'
|
||||
}));
|
||||
assert.ok(un, 'devrait accepter une reponse bien formee');
|
||||
assert.equal(un.container, container);
|
||||
assert.equal(un.sha, 'abc123');
|
||||
});
|
||||
|
||||
test('giteaUnwrap: accepts the line-wrapped base64 Gitea sends', async () => {
|
||||
const { __test: t } = await loadApp();
|
||||
const container = '{"version":1}';
|
||||
// Gitea coupe son base64 en lignes ; un decodeur strict s'y casse.
|
||||
const wrapped = b64(container).replace(/(.{4})/, '$1\r\n');
|
||||
const un = t.giteaUnwrap(JSON.stringify({
|
||||
content: wrapped, encoding: 'base64', sha: 'deadbeef'
|
||||
}));
|
||||
assert.ok(un, 'les retours a la ligne ne doivent pas faire echouer le decodage');
|
||||
assert.equal(un.container, container);
|
||||
});
|
||||
|
||||
test('giteaUnwrap: refuses anything that is not a file', async () => {
|
||||
const { __test: t } = await loadApp();
|
||||
// Ce que rend une URL a un segment pres : du JSON valide, sans fichier.
|
||||
assert.equal(t.giteaUnwrap('{"message":"Not found"}'), null);
|
||||
// Un repertoire : l'API rend un TABLEAU, pas un objet.
|
||||
assert.equal(t.giteaUnwrap('[{"name":"vault-sync.json","sha":"x"}]'), null);
|
||||
// Un sha sans contenu ne permet rien de dechiffrer.
|
||||
assert.equal(t.giteaUnwrap('{"sha":"abc"}'), null);
|
||||
// Un contenu sans sha interdirait l'ecriture concurrente : refuse aussi.
|
||||
assert.equal(t.giteaUnwrap(JSON.stringify({ content: b64('{}') })), null);
|
||||
// Un encodage que nous ne savons pas lire.
|
||||
assert.equal(t.giteaUnwrap(JSON.stringify({
|
||||
content: 'x', encoding: 'utf-8', sha: 'abc' })), null);
|
||||
// Pas du JSON du tout - une page d'erreur HTML, par exemple.
|
||||
assert.equal(t.giteaUnwrap('<html>502</html>'), null);
|
||||
assert.equal(t.giteaUnwrap(''), null);
|
||||
});
|
||||
@@ -152,6 +152,8 @@ function loadApp(overrides = {}) {
|
||||
computeStrength: (typeof computeStrength !== 'undefined' ? computeStrength : undefined),
|
||||
// merge (async, coupled — tests stub the io seams below)
|
||||
applyRemoteSnapshot, buildSyncSnapshot,
|
||||
// gitea transport
|
||||
syncIsGitea, giteaUnwrap,
|
||||
// metadata-at-rest
|
||||
withEncryptedMeta, decryptEntryMeta, ENCRYPTED_META_FIELDS,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user