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 };