From 88a8729f4fa2f6f10e31ecf8412584338d04a88c Mon Sep 17 00:00:00 2001 From: Tero Date: Fri, 16 Oct 2026 17:15:20 +0300 Subject: [PATCH] Refractoring Stage 5 DAV functions EDIT/DEL tied to creators account --- REFACTOR_PLAN.md | 7 ++- desktop/dav-codecs.cjs | 13 +++++- desktop/dav/remote-reference.cjs | 63 +++++++++++++++++++++++++++ desktop/main.cjs | 50 +++++++++++++++++----- tests/dav-codecs.test.cjs | 6 +++ tests/dav-remote-reference.test.cjs | 66 +++++++++++++++++++++++++++++ 6 files changed, 190 insertions(+), 15 deletions(-) create mode 100644 desktop/dav/remote-reference.cjs create mode 100644 tests/dav-remote-reference.test.cjs diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md index d7532bf..5362596 100644 --- a/REFACTOR_PLAN.md +++ b/REFACTOR_PLAN.md @@ -87,7 +87,8 @@ This is a gradual destination, not a requirement to move everything at once. IPC - [x] Verify the IPC sender is the expected top-level application document (`desktop/security/ipc-sender.cjs`). - [x] Restrict navigation to the exact app document URL; reject arbitrary `file:` navigation. - [x] Validate channel names, argument counts/types, and nested payload complexity (`desktop/security/ipc-arguments.cjs`). -- [ ] Validate channel-specific field limits and authority-sensitive values, including DAV remote object references. +- [x] Bind DAV object updates/deletes to the selected account, server collection, server-returned resource, and current ETag (`desktop/dav/remote-reference.cjs`). +- [ ] Finish channel-specific validation for remaining nested fields and sensitive values. - [ ] Register handlers by feature and keep `preload.cjs` as the narrow renderer API. - [ ] Return deliberate DTOs rather than internal store objects. @@ -127,5 +128,7 @@ This is a gradual destination, not a requirement to move everything at once. IPC - Step 4 completed with extracted IDLE and snooze services; the full suite passed 92 tests. - Step 5 added a trusted top-level sender check to all 54 registered IPC handlers; sender boundary tests pass. - Step 5 also aligned `will-navigate` with the same exact-document policy; `npm test` passes 96 tests. -- Step 5 added request schemas for all 54 registered channels, plus depth/collection/string bounds. Base64 attachment payloads remain uncapped to preserve the existing no-total-size-cap behavior; `npm test` passes 100 tests. +- Step 5 added request schemas for all 54 registered channels, plus depth/collection/string bounds. Base64 attachment payloads remain uncapped to preserve the existing no-total-size-cap behavior. +- Step 5 also binds DAV updates/deletes to the configured account, same-origin collection, a server-listed resource, and a current ETag; DAV IDs are constrained against line injection and path traversal. +- The current IPC/DAV validation changes pass the full suite: 106 tests. - While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved. diff --git a/desktop/dav-codecs.cjs b/desktop/dav-codecs.cjs index d2923f5..445829c 100644 --- a/desktop/dav-codecs.cjs +++ b/desktop/dav-codecs.cjs @@ -8,8 +8,16 @@ function escapeVcard(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); } +function safeDavUid(value, createId) { + const uid = String(value || createId()); + if (!uid || uid.length > 255 || /[\\/\\?#\u0000-\u001f\u007f]/.test(uid)) { + throw new Error('The DAV item identifier is invalid.'); + } + return uid; +} + function makeCalendarData(event, { createId = randomUUID, now = () => new Date() } = {}) { - const uid = event._dav?.uid || createId(); + const uid = safeDavUid(event._dav?.uid, createId); const stamp = now().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, ''); const start = event.time ? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') @@ -25,7 +33,8 @@ function makeVcard(contact, { createId = randomUUID } = {}) { const name = String(contact.name || '').trim().split(/\s+/); const first = name.shift() || ''; const last = name.join(' '); - return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${contact._dav?.uid || createId()}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`; + const uid = safeDavUid(contact._dav?.uid, createId); + return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${uid}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`; } module.exports = { escapeIcal, escapeVcard, makeCalendarData, makeVcard }; diff --git a/desktop/dav/remote-reference.cjs b/desktop/dav/remote-reference.cjs new file mode 100644 index 0000000..24deb57 --- /dev/null +++ b/desktop/dav/remote-reference.cjs @@ -0,0 +1,63 @@ +function asSafeDavUrl(value, baseUrl, serverOrigin) { + if (typeof value !== 'string' || !value.trim()) return null; + try { + const url = new URL(value, baseUrl); + if (url.origin !== serverOrigin || url.username || url.password || url.search || url.hash) return null; + return url; + } catch { + return null; + } +} + +function assertDavObjectReference({ config, remote, collections, objects }) { + if (!config || typeof config.id !== 'string' || typeof config.serverUrl !== 'string') { + throw new Error('The DAV account reference is invalid.'); + } + if (!remote || typeof remote !== 'object' || Array.isArray(remote) || remote.accountId !== config.id) { + throw new Error('This DAV item does not belong to the selected account.'); + } + if (!Array.isArray(collections) || !Array.isArray(objects)) { + throw new Error('The DAV collection could not be verified.'); + } + + let serverUrl; + try { + serverUrl = new URL(config.serverUrl); + } catch { + throw new Error('The DAV server address is invalid.'); + } + if (!['https:', 'http:'].includes(serverUrl.protocol) || serverUrl.username || serverUrl.password) { + throw new Error('The DAV server address is invalid.'); + } + + const requestedCollection = asSafeDavUrl(remote.collectionUrl, serverUrl.href, serverUrl.origin); + const collection = collections.find(candidate => { + const url = asSafeDavUrl(candidate?.url, serverUrl.href, serverUrl.origin); + return url && requestedCollection && url.href === requestedCollection.href; + }); + if (!collection || !requestedCollection) throw new Error('This DAV collection is not available on the selected server.'); + + const collectionUrl = asSafeDavUrl(collection.url, serverUrl.href, serverUrl.origin); + const objectUrl = asSafeDavUrl(remote.objectUrl, collectionUrl.href, serverUrl.origin); + if (!objectUrl) throw new Error('This DAV object address is not valid for the selected server.'); + const collectionPath = collectionUrl.pathname.endsWith('/') ? collectionUrl.pathname : `${collectionUrl.pathname}/`; + if (objectUrl.pathname === collectionPath || !objectUrl.pathname.startsWith(collectionPath)) { + throw new Error('This DAV object is outside the selected collection.'); + } + + const object = objects.find(candidate => { + const url = asSafeDavUrl(candidate?.url, collectionUrl.href, serverUrl.origin); + return url && url.href === objectUrl.href; + }); + if (!object) throw new Error('This DAV object is no longer available in the selected collection.'); + if (object.etag != null && remote.etag !== object.etag) { + throw new Error('This DAV item has changed on the server. Sync again before editing it.'); + } + if (remote.etag != null && typeof remote.etag !== 'string') { + throw new Error('The DAV object version is invalid.'); + } + + return { collection, object, collectionUrl: collectionUrl.href, objectUrl: objectUrl.href }; +} + +module.exports = { assertDavObjectReference }; diff --git a/desktop/main.cjs b/desktop/main.cjs index e7e231b..fa0ec52 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -35,6 +35,7 @@ const { createIdleWatcherManager } = require('./mail/idle-watcher-manager.cjs'); const { createSnoozeReminderService } = require('./mail/snooze-reminder-service.cjs'); const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs'); const { validateIpcArguments } = require('./security/ipc-arguments.cjs'); +const { assertDavObjectReference } = require('./dav/remote-reference.cjs'); const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); @@ -1072,7 +1073,10 @@ registerIpcHandler('dav:connect', async (_event, input) => { const password = String(input?.password || ''); let parsedUrl; try { parsedUrl = new URL(serverUrl); } catch { throw new Error('Enter a valid CalDAV or CardDAV server URL.'); } - if (!['https:', 'http:'].includes(parsedUrl.protocol) || (parsedUrl.protocol === 'http:' && !['localhost','127.0.0.1','::1'].includes(parsedUrl.hostname))) throw new Error('DAV server URLs must use HTTPS.'); + if (!['https:', 'http:'].includes(parsedUrl.protocol) || parsedUrl.username || parsedUrl.password || + (parsedUrl.protocol === 'http:' && !['localhost','127.0.0.1','::1'].includes(parsedUrl.hostname))) { + throw new Error('DAV server URLs must use HTTPS and must not contain embedded credentials.'); + } if (!username || !password) throw new Error('Enter the DAV username and password.'); const config = { id: randomUUID(), type, serverUrl: parsedUrl.href, username, password }; const client = await openDavClient(config, type); @@ -1162,15 +1166,22 @@ registerIpcHandler('dav:save-event', async (_event, input) => { if (!config) return null; const client = await openDavClient(config, 'caldav'); const calendars = await client.fetchCalendars(); - const calendar = calendars.find(item => item.url === remote?.collectionUrl) || calendars[0]; + const calendar = remote?.collectionUrl + ? calendars.find(item => item.url === remote.collectionUrl) + : calendars[0]; if (!calendar) throw new Error('No writable calendar was found.'); + let trustedObject = null; + if (remote?.objectUrl) { + const objects = await client.fetchCalendarObjects({ calendar }); + trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects }); + } const uid = remote?.uid || randomUUID(); const data = makeCalendarData({ ...input, _dav: { ...remote, uid } }); if (remote?.objectUrl) { - const response = await client.updateCalendarObject({ calendarObject: { url: remote.objectUrl, data, etag: remote.etag } }); - return { accountId: config.id, collectionUrl: calendar.url, objectUrl: remote.objectUrl, etag: response.headers.get('etag') || remote.etag, uid }; + const response = await client.updateCalendarObject({ calendarObject: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag } }); + return { accountId: config.id, collectionUrl: calendar.url, objectUrl: trustedObject.objectUrl, etag: response.headers.get('etag') || remote.etag, uid }; } - const filename = `${uid}.ics`; + const filename = `${encodeURIComponent(uid)}.ics`; const response = await client.createCalendarObject({ calendar, iCalString: data.replace(`UID:${uid}`, `UID:${uid}`), filename }); return { accountId: config.id, collectionUrl: calendar.url, objectUrl: new URL(filename, calendar.url.endsWith('/')?calendar.url:`${calendar.url}/`).href, etag: response.headers.get('etag'), uid }; }); @@ -1180,7 +1191,12 @@ registerIpcHandler('dav:delete-event', async (_event, remote) => { const config = activeDavConfig(store, 'caldav', remote?.accountId); if (!config || !remote?.objectUrl) return; const client = await openDavClient(config, 'caldav'); - await client.deleteCalendarObject({ calendarObject: { url: remote.objectUrl, etag: remote.etag } }); + const calendars = await client.fetchCalendars(); + const calendar = calendars.find(item => item.url === remote.collectionUrl); + if (!calendar) throw new Error('This DAV collection is not available on the selected server.'); + const objects = await client.fetchCalendarObjects({ calendar }); + const trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects }); + await client.deleteCalendarObject({ calendarObject: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag } }); }); registerIpcHandler('dav:save-contact', async (_event, input) => { @@ -1190,15 +1206,22 @@ registerIpcHandler('dav:save-contact', async (_event, input) => { if (!config) return null; const client = await openDavClient(config, 'carddav'); const books = await client.fetchAddressBooks(); - const book = books.find(item => item.url === remote?.collectionUrl) || books[0]; + const book = remote?.collectionUrl + ? books.find(item => item.url === remote.collectionUrl) + : books[0]; if (!book) throw new Error('No writable address book was found.'); + let trustedObject = null; + if (remote?.objectUrl) { + const cards = await client.fetchVCards({ addressBook: book }); + trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards }); + } const uid = remote?.uid || randomUUID(); const data = makeVcard({ ...input, _dav: { ...remote, uid } }); if (remote?.objectUrl) { - const response = await client.updateVCard({ vCard: { url: remote.objectUrl, data, etag: remote.etag } }); - return { accountId: config.id, collectionUrl: book.url, objectUrl: remote.objectUrl, etag: response.headers.get('etag') || remote.etag, uid }; + const response = await client.updateVCard({ vCard: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag } }); + return { accountId: config.id, collectionUrl: book.url, objectUrl: trustedObject.objectUrl, etag: response.headers.get('etag') || remote.etag, uid }; } - const filename = `${uid}.vcf`; + const filename = `${encodeURIComponent(uid)}.vcf`; const response = await client.createVCard({ addressBook: book, vCardString: data, filename }); return { accountId: config.id, collectionUrl: book.url, objectUrl: new URL(filename, book.url.endsWith('/')?book.url:`${book.url}/`).href, etag: response.headers.get('etag'), uid }; }); @@ -1208,7 +1231,12 @@ registerIpcHandler('dav:delete-contact', async (_event, remote) => { const config = activeDavConfig(store, 'carddav', remote?.accountId); if (!config || !remote?.objectUrl) return; const client = await openDavClient(config, 'carddav'); - await client.deleteVCard({ vCard: { url: remote.objectUrl, etag: remote.etag } }); + const books = await client.fetchAddressBooks(); + const book = books.find(item => item.url === remote.collectionUrl); + if (!book) throw new Error('This DAV collection is not available on the selected server.'); + const cards = await client.fetchVCards({ addressBook: book }); + const trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards }); + await client.deleteVCard({ vCard: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag } }); }); function createWindow() { diff --git a/tests/dav-codecs.test.cjs b/tests/dav-codecs.test.cjs index 7274a33..6a70fe6 100644 --- a/tests/dav-codecs.test.cjs +++ b/tests/dav-codecs.test.cjs @@ -32,3 +32,9 @@ test('serializes contacts with escaped fields and an injected identifier', () => 'N:Example Lovelace;Ada;;;\r\nEMAIL:ada@example.com\r\n' + 'NOTE:Research\\, analysis\\; mathematics\r\nEND:VCARD\r\n'); }); + +test('rejects DAV identifiers that can inject fields or escape resource paths', () => { + assert.throws(() => makeCalendarData({ date: '2026-10-16', title: 'Bad', _dav: { uid: 'good\r\nX-Evil: yes' } }), /identifier is invalid/); + assert.throws(() => makeCalendarData({ date: '2026-10-16', title: 'Bad', _dav: { uid: '../other' } }), /identifier is invalid/); + assert.throws(() => makeVcard({ name: 'Bad', email: 'x@example.test', _dav: { uid: 'x'.repeat(256) } }), /identifier is invalid/); +}); diff --git a/tests/dav-remote-reference.test.cjs b/tests/dav-remote-reference.test.cjs new file mode 100644 index 0000000..0a82e6b --- /dev/null +++ b/tests/dav-remote-reference.test.cjs @@ -0,0 +1,66 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { assertDavObjectReference } = require('../desktop/dav/remote-reference.cjs'); + +const config = { id: 'dav-1', serverUrl: 'https://dav.example.test/' }; +const collection = { url: 'https://dav.example.test/calendars/user/main/', displayName: 'Main' }; +const object = { url: 'https://dav.example.test/calendars/user/main/event-1.ics', etag: '"v4"' }; +const remote = { + accountId: 'dav-1', + collectionUrl: collection.url, + objectUrl: object.url, + etag: object.etag +}; + +test('accepts a resource verified against the configured server, collection, and current ETag', () => { + const result = assertDavObjectReference({ config, remote, collections: [collection], objects: [object] }); + assert.equal(result.collection, collection); + assert.equal(result.object, object); + assert.equal(result.objectUrl, object.url); +}); + +test('accepts a relative server-returned object URL within its verified collection', () => { + const result = assertDavObjectReference({ + config, + remote: { ...remote, objectUrl: 'event-1.ics' }, + collections: [collection], + objects: [{ url: 'event-1.ics', etag: '"v4"' }] + }); + assert.equal(result.objectUrl, object.url); +}); + +test('rejects account, collection, and resource references not returned by the server', () => { + assert.throws(() => assertDavObjectReference({ + config, remote: { ...remote, accountId: 'other-account' }, collections: [collection], objects: [object] + }), /does not belong/); + assert.throws(() => assertDavObjectReference({ + config, remote: { ...remote, collectionUrl: 'https://dav.example.test/other/' }, collections: [collection], objects: [object] + }), /collection is not available/); + assert.throws(() => assertDavObjectReference({ + config, remote: { ...remote, objectUrl: 'https://dav.example.test/calendars/user/main/unknown.ics' }, collections: [collection], objects: [object] + }), /no longer available/); +}); + +test('rejects cross-origin, credential-bearing, query, traversal, and out-of-collection URLs', () => { + for (const objectUrl of [ + 'https://attacker.example/event.ics', + 'https://user:pass@dav.example.test/calendars/user/main/event-1.ics', + 'https://dav.example.test/calendars/user/main/event-1.ics?redirect=1', + '../other/event.ics', + 'https://dav.example.test/calendars/user/main/', + 'https://dav.example.test/calendars/user/other/event.ics' + ]) { + assert.throws(() => assertDavObjectReference({ + config, remote: { ...remote, objectUrl }, collections: [collection], objects: [object] + })); + } +}); + +test('rejects stale ETags and ETags with unexpected types', () => { + assert.throws(() => assertDavObjectReference({ + config, remote: { ...remote, etag: '"v3"' }, collections: [collection], objects: [object] + }), /changed on the server/); + assert.throws(() => assertDavObjectReference({ + config, remote: { ...remote, etag: 4 }, collections: [collection], objects: [{ ...object, etag: undefined }] + }), /version is invalid/); +});