Refractoring Stage 5 DAV functions EDIT/DEL tied to creators account

This commit is contained in:
2026-10-16 17:15:20 +03:00
parent 0b52949f23
commit 88a8729f4f
6 changed files with 190 additions and 15 deletions
+11 -2
View File
@@ -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 };
+63
View File
@@ -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 };
+39 -11
View File
@@ -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() {