the skill told an agent how to hand-write a .ics: escape the commas, fold at 75 octets, CRLF, DTSTAMP is required, and DTEND is the day after. all true, all silent when wrong, and the browser had learned the same lesson separately in its own copy of the code. this makes the sidecar the only thing that knows the format, and gives everyone else fields. WHAT WAS MISSING BEFORE THE SKILL COULD CHANGE. reading was already JSON, and create-event landed this morning. this adds PATCH /_officer/item — change some fields of an event or a card — and POST /_officer/contact. delete already worked. with those the skill has no reason left to mention iCalendar, so it does not. PATCH IS READ-PATCH-PUT, SERVER SIDE. it reads the stored text, replaces only the lines it owns, and puts the whole thing back, so alarms, attendees, RRULEs and every X- property a phone invented survive an edit made from a form that cannot show them. that logic came out of the browser, where it had needed a duplicate of the escaping and folding rules to live; the agent would have been a third copy in bash. the web bundle now contains no iCalendar literals at all. AND LIVE TESTING FOUND THE BUG THAT MATTERS. an event with a TZID is stored with a VTIMEZONE block beside it, and that block has DTSTART lines of its own — the rule for when summer time starts. taking the first DTSTART in the file rewrote the TIMEZONE DEFINITION, left the event where it was, and answered ok. the calendar showed the old time and the file was quietly corrupt. every write is now confined to the first VEVENT or VCARD, and the file that caught it is a test. three more traps handled rather than documented: a patch that reuses an all-day event's stored DTEND must subtract the exclusive day first or the holiday drifts every time the title is edited; moving a timed event must DROP a stale TZID rather than preserve it, because a TZID and a Z together are a contradiction clients resolve by moving the event; and a move bumps SEQUENCE, which is how a phone tells an update from a duplicate. contacts got the create form the calendar had, so both screens now do all four. editing a card sends the other emails and phones back untouched — the form shows the first of each, and sending only that would delete the rest. 47 tests across the writer and the patcher. verified live against a real event carrying an alarm, an attendee, an RRULE and an X- property: all four intact after a rename, a relocation and a move to a different day. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Officer-Session: 656f5c85-e49a-4f1f-b9f3-042a04b4d043
427 lines
19 KiB
TypeScript
427 lines
19 KiB
TypeScript
import type { SidecarCommand, SidecarEvent } from '@@/sidecar/protocol';
|
|
import { createSidecarConnector } from '@@/sidecar/connect';
|
|
import { startRadicale, davPaths } from './radicale';
|
|
import { listCollections, listEvents, listContacts, createEvent, createContact } from './collections';
|
|
import { patchFor, summarise } from './patch';
|
|
import { DATA_PATH } from '@@/data-path';
|
|
import { API_URL } from '@@/officer-url.mjs';
|
|
|
|
// The officer-caldav sidecar. Owns the whole CalDAV/CardDAV contract: it supervises Radicale, owns the
|
|
// collection storage under DATA_PATH/dav, and exposes two very different doors.
|
|
//
|
|
// ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
// HTTP CONTRACT — the platform strips its mount prefix before forwarding.
|
|
//
|
|
// ANY /dav/* the DAV door. Forwarded verbatim to Radicale, including PROPFIND, REPORT,
|
|
// MKCOL, MKCALENDAR, COPY, MOVE, LOCK and UNLOCK, and every DAV header.
|
|
// Reached from the platform's TOP-LEVEL /dav mount, which authenticates a DAV
|
|
// app password over HTTP Basic. This is the door phones use.
|
|
// GET /_health is Radicale up, and does it answer.
|
|
// * /_officer/* the JSON door. Reads, and field-level writes: POST /_officer/event and
|
|
// /_officer/contact create, PATCH /_officer/item changes fields, DELETE removes.
|
|
// Built for the web UI; the agent skill speaks it too, which is why the writes
|
|
// take FIELDS rather than iCalendar text (see patch.ts).
|
|
//
|
|
// WHY TWO DOORS. A browser should not speak DAV — rendering a month view out of multistatus XML is a
|
|
// lot of machinery, and it would make the web UI as fragile as the protocol. The collections are on
|
|
// local disk here, so this sidecar can serve the UI plain JSON over the same data while DAV stays the
|
|
// machine-facing interface. Same split officer-email already uses.
|
|
// ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
|
|
/** Grab an ephemeral free port by briefly binding one and releasing it. */
|
|
function getFreePort(): number {
|
|
const probeServer = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: () => new Response('') });
|
|
const p = probeServer.port;
|
|
probeServer.stop(true);
|
|
if (p == null) throw new Error('failed to acquire a free port');
|
|
return p;
|
|
}
|
|
|
|
// Where the platform exposes the DAV door publicly. It is a fixed contract between hono.ts's top-level
|
|
// mount and this sidecar, not configuration — Radicale has to be told it so the hrefs it generates are
|
|
// the ones the client can actually fetch.
|
|
const DAV_MOUNT = '/dav';
|
|
|
|
const paths = davPaths(DATA_PATH);
|
|
const radicale = startRadicale({ ...paths, port: getFreePort() });
|
|
const port = getFreePort();
|
|
|
|
// Headers a DAV exchange cannot survive without. `Depth` alone decides whether a PROPFIND returns the
|
|
// collection, its children, or the whole tree — drop it and every client sees an empty calendar. The
|
|
// rest carry conditional writes (If-Match is how a client avoids clobbering a concurrent edit),
|
|
// COPY/MOVE targets, and lock tokens.
|
|
const DAV_REQUEST_HEADERS = [
|
|
'depth',
|
|
'content-type',
|
|
'content-length',
|
|
'if',
|
|
'if-match',
|
|
'if-none-match',
|
|
'destination',
|
|
'overwrite',
|
|
'lock-token',
|
|
'timeout',
|
|
'prefer',
|
|
'user-agent',
|
|
] as const;
|
|
|
|
// Sent back untouched. `DAV` and `Allow` are how a client discovers what the server supports; getting
|
|
// them wrong makes iOS decide the account is not a calendar at all.
|
|
const DAV_RESPONSE_HEADERS = [
|
|
'content-type',
|
|
'dav',
|
|
'allow',
|
|
'etag',
|
|
'last-modified',
|
|
'location',
|
|
'lock-token',
|
|
'preference-applied',
|
|
'vary',
|
|
] as const;
|
|
|
|
async function forwardToRadicale(req: Request, subpath: string, userId: string): Promise<Response> {
|
|
const url = new URL(req.url);
|
|
const target = `${radicale.url}${subpath}${url.search}`;
|
|
|
|
const headers: Record<string, string> = {};
|
|
for (const name of DAV_REQUEST_HEADERS) {
|
|
const value = req.headers.get(name);
|
|
if (value) headers[name] = value;
|
|
}
|
|
// Radicale is configured with `type = http_x_remote_user` and does no authentication of its own. It
|
|
// binds loopback, so this header is only settable from inside this process.
|
|
headers['X-Remote-User'] = userId;
|
|
// Radicale generates ABSOLUTE hrefs in its multistatus bodies, and it builds them from where it
|
|
// thinks it is mounted. Without this it answers a PROPFIND on /dav/ with
|
|
// `<current-user-principal><href>/1/</href>`, the client dutifully requests /1/, and the platform
|
|
// serves it the SPA — an HTML page where a calendar was expected. The client does not report a
|
|
// useful error for that; the account just appears to have no calendars in it.
|
|
headers['X-Script-Name'] = DAV_MOUNT;
|
|
|
|
const hasBody = req.method !== 'GET' && req.method !== 'HEAD';
|
|
|
|
let upstream: Response;
|
|
try {
|
|
upstream = await fetch(target, {
|
|
method: req.method,
|
|
headers,
|
|
body: hasBody ? await req.arrayBuffer() : undefined,
|
|
});
|
|
} catch (err) {
|
|
// Path only — a DAV body is the owner's calendar and address book content.
|
|
console.error('[caldav] radicale unreachable', { path: subpath, error: String(err) });
|
|
return new Response('caldav upstream unreachable', { status: 502 });
|
|
}
|
|
|
|
const out = new Headers();
|
|
for (const name of DAV_RESPONSE_HEADERS) {
|
|
const value = upstream.headers.get(name);
|
|
if (value) out.set(name, value);
|
|
}
|
|
return new Response(upstream.body, { status: upstream.status, headers: out });
|
|
}
|
|
|
|
const server = Bun.serve({
|
|
port,
|
|
hostname: '127.0.0.1',
|
|
// A contact photo or a calendar with years of history arrives as one PUT.
|
|
maxRequestBodySize: 32 * 1024 * 1024,
|
|
async fetch(req) {
|
|
const url = new URL(req.url);
|
|
|
|
const officerUser = req.headers.get('X-Officer-User');
|
|
const userId = Number(officerUser);
|
|
if (!officerUser || !Number.isInteger(userId) || userId <= 0) {
|
|
return new Response('missing or invalid X-Officer-User', { status: 401 });
|
|
}
|
|
|
|
if (url.pathname === '/_health') {
|
|
if (!radicale.isRunning()) {
|
|
// `startupError` distinguishes "not installed" from "crashed and backing off". Both are 503, but
|
|
// only one of them is fixed by waiting, and the logs alone did not say which.
|
|
return Response.json(
|
|
{
|
|
ok: false,
|
|
running: false,
|
|
error: radicale.startupError ?? 'radicale not running',
|
|
installed: radicale.startupError === null,
|
|
},
|
|
{ status: 503 },
|
|
);
|
|
}
|
|
try {
|
|
const probe = await fetch(`${radicale.url}/`, {
|
|
method: 'PROPFIND',
|
|
headers: { 'X-Remote-User': String(userId), Depth: '0' },
|
|
signal: AbortSignal.timeout(5000),
|
|
});
|
|
// Anything that answers the DAV handshake is healthy; 207 Multi-Status is the expected reply.
|
|
return Response.json({ ok: probe.status < 500, running: true, status: probe.status });
|
|
} catch (err) {
|
|
return Response.json({ ok: false, running: true, error: String(err) }, { status: 502 });
|
|
}
|
|
}
|
|
|
|
if (url.pathname === '/dav' || url.pathname.startsWith('/dav/')) {
|
|
const subpath = url.pathname.slice('/dav'.length) || '/';
|
|
return forwardToRadicale(req, subpath, String(userId));
|
|
}
|
|
|
|
// The JSON door. Same data, no XML: a month view built out of multistatus responses would make the
|
|
// web UI as fragile as the protocol.
|
|
if (url.pathname.startsWith('/_officer/')) {
|
|
// Radicale generates hrefs prefixed with /dav (X-Script-Name), and the UI hands those back
|
|
// verbatim as collection ids — so strip the prefix again on the way in.
|
|
const fetcher = (path: string, init: RequestInit) =>
|
|
fetch(`${radicale.url}${path.replace(/^\/dav/, '')}`, {
|
|
...init,
|
|
headers: {
|
|
...(init.headers as Record<string, string>),
|
|
'X-Remote-User': String(userId),
|
|
// Same prefix the phone-facing door sends, so the collection ids the UI receives here are
|
|
// the same strings a DAV client would see. Without it the UI gets /1/work/ and the phone
|
|
// gets /dav/1/work/ for the same collection, and nothing downstream can match them up.
|
|
'X-Script-Name': DAV_MOUNT,
|
|
},
|
|
});
|
|
|
|
if (url.pathname === '/_officer/collections') {
|
|
return Response.json({ collections: await listCollections(fetcher, String(userId)) });
|
|
}
|
|
|
|
/*
|
|
One item's ORIGINAL text, for an editor that must not lose what it does not understand.
|
|
|
|
Rebuilding an .ics from the parsed fields would silently drop alarms, attendees, recurrence rules
|
|
and every X- property the file came with — an edit that quietly deletes half an event is worse
|
|
than no editing at all. So the editor reads the real thing, changes the lines it owns, and puts
|
|
the whole file back.
|
|
*/
|
|
if (url.pathname === '/_officer/item' && req.method === 'GET') {
|
|
const href = url.searchParams.get('href') ?? '';
|
|
if (!href.startsWith(`/dav/${userId}/`)) {
|
|
return Response.json({ error: 'href is required and must be your own' }, { status: 400 });
|
|
}
|
|
const res = await fetcher(href, { method: 'GET' });
|
|
if (!res.ok) return Response.json({ error: `radicale answered ${res.status}` }, { status: 502 });
|
|
return Response.json({ href, data: await res.text() });
|
|
}
|
|
|
|
/*
|
|
Change some FIELDS of an item, rather than replacing its text.
|
|
|
|
This is the route anything sane should use. PUT is still here because the raw text is sometimes
|
|
genuinely what a caller has, but a caller that only wants to move an event or fix a phone number
|
|
should not have to learn iCalendar escaping to do it — and every caller that did learn it learned
|
|
it slightly differently. The read, the patch and the write happen here, in one round trip, over
|
|
the ORIGINAL text, so nothing the patcher does not recognise is disturbed.
|
|
*/
|
|
if (url.pathname === '/_officer/item' && req.method === 'PATCH') {
|
|
const body = (await req.json().catch(() => ({}))) as { href?: string; [field: string]: unknown };
|
|
const href = String(body.href ?? '');
|
|
if (!href.startsWith(`/dav/${userId}/`)) {
|
|
return Response.json({ error: 'href is required and must be your own' }, { status: 400 });
|
|
}
|
|
|
|
const read = await fetcher(href, { method: 'GET' });
|
|
if (!read.ok) return Response.json({ error: `radicale answered ${read.status}` }, { status: 502 });
|
|
|
|
let patched: string;
|
|
try {
|
|
const { href: _ignored, ...fields } = body;
|
|
patched = patchFor(href, fields, await read.text());
|
|
} catch (err) {
|
|
return Response.json({ error: String(err) }, { status: 400 });
|
|
}
|
|
|
|
const isCard = href.endsWith('.vcf');
|
|
const written = await fetcher(href, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': isCard ? 'text/vcard; charset=utf-8' : 'text/calendar; charset=utf-8' },
|
|
body: patched,
|
|
});
|
|
if (!written.ok) return Response.json({ error: `radicale answered ${written.status}` }, { status: 502 });
|
|
// The item as it now reads, so a caller can confirm what it did without a second call.
|
|
return Response.json({ ok: true, item: summarise(href, patched) });
|
|
}
|
|
|
|
if (url.pathname === '/_officer/item' && (req.method === 'PUT' || req.method === 'DELETE')) {
|
|
const body = (await req.json().catch(() => ({}))) as { href?: string; data?: string };
|
|
const href = String(body.href ?? '');
|
|
if (!href.startsWith(`/dav/${userId}/`)) {
|
|
return Response.json({ error: 'href is required and must be your own' }, { status: 400 });
|
|
}
|
|
|
|
if (req.method === 'DELETE') {
|
|
const res = await fetcher(href, { method: 'DELETE' });
|
|
// 404 is success from the caller's point of view: the thing they asked to be gone is gone.
|
|
if (!res.ok && res.status !== 404) {
|
|
return Response.json({ error: `radicale answered ${res.status}` }, { status: 502 });
|
|
}
|
|
return Response.json({ ok: true });
|
|
}
|
|
|
|
if (!body.data) return Response.json({ error: 'data is required' }, { status: 400 });
|
|
const isCard = href.endsWith('.vcf');
|
|
const res = await fetcher(href, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': isCard ? 'text/vcard; charset=utf-8' : 'text/calendar; charset=utf-8',
|
|
},
|
|
body: body.data,
|
|
});
|
|
if (!res.ok) return Response.json({ error: `radicale answered ${res.status}` }, { status: 502 });
|
|
return Response.json({ ok: true, status: res.status });
|
|
}
|
|
|
|
/*
|
|
Create an event. POST rather than PUT, because the caller does not choose the address — the
|
|
sidecar mints the filename, so this is "add one to that collection", not "put this here".
|
|
|
|
The BODY carries the collection, which is why this sits above the guard below: that one reads a
|
|
collection out of the query string, and a create has none there.
|
|
*/
|
|
if (url.pathname === '/_officer/event' && req.method === 'POST') {
|
|
const body = (await req.json().catch(() => ({}))) as {
|
|
collection?: string;
|
|
summary?: string;
|
|
location?: string;
|
|
start?: string;
|
|
end?: string;
|
|
allDay?: boolean;
|
|
};
|
|
const collection = String(body.collection ?? '');
|
|
if (!collection.startsWith(`/dav/${userId}/`)) {
|
|
return Response.json({ error: 'collection is required and must be your own' }, { status: 400 });
|
|
}
|
|
const summary = (body.summary ?? '').trim();
|
|
if (!summary) return Response.json({ error: 'summary is required' }, { status: 400 });
|
|
if (!body.start) return Response.json({ error: 'start is required' }, { status: 400 });
|
|
|
|
try {
|
|
const created = await createEvent(fetcher, collection, {
|
|
summary,
|
|
location: (body.location ?? '').trim() || undefined,
|
|
start: body.start,
|
|
end: body.end,
|
|
allDay: Boolean(body.allDay),
|
|
});
|
|
return Response.json(created, { status: 201 });
|
|
} catch (err) {
|
|
return Response.json({ error: String(err) }, { status: 502 });
|
|
}
|
|
}
|
|
|
|
/* Same contract as the event route above, for an address book. */
|
|
if (url.pathname === '/_officer/contact' && req.method === 'POST') {
|
|
const body = (await req.json().catch(() => ({}))) as {
|
|
collection?: string;
|
|
fullName?: string;
|
|
emails?: string[];
|
|
phones?: string[];
|
|
org?: string;
|
|
title?: string;
|
|
};
|
|
const collection = String(body.collection ?? '');
|
|
if (!collection.startsWith(`/dav/${userId}/`)) {
|
|
return Response.json({ error: 'collection is required and must be your own' }, { status: 400 });
|
|
}
|
|
const fullName = (body.fullName ?? '').trim();
|
|
// FN is what a phone displays and vCard requires it. A card without one shows as a blank row.
|
|
if (!fullName) return Response.json({ error: 'fullName is required' }, { status: 400 });
|
|
|
|
try {
|
|
const created = await createContact(fetcher, collection, {
|
|
fullName,
|
|
emails: (body.emails ?? []).filter(Boolean),
|
|
phones: (body.phones ?? []).filter(Boolean),
|
|
org: (body.org ?? '').trim() || undefined,
|
|
title: (body.title ?? '').trim() || undefined,
|
|
});
|
|
return Response.json(created, { status: 201 });
|
|
} catch (err) {
|
|
return Response.json({ error: String(err) }, { status: 502 });
|
|
}
|
|
}
|
|
|
|
const path = url.searchParams.get('collection');
|
|
// Confine reads to this user's own tree. The header already scopes Radicale, but a path from a
|
|
// query string is attacker-shaped input and should not be handed on unchecked.
|
|
if (!path || !path.startsWith(`/dav/${userId}/`)) {
|
|
return Response.json({ error: 'collection is required' }, { status: 400 });
|
|
}
|
|
|
|
if (url.pathname === '/_officer/events') {
|
|
return Response.json({ events: await listEvents(fetcher, path) });
|
|
}
|
|
if (url.pathname === '/_officer/contacts') {
|
|
return Response.json({ contacts: await listContacts(fetcher, path) });
|
|
}
|
|
|
|
/*
|
|
On the writing routes above.
|
|
|
|
── Why the href is required and never derived ──
|
|
|
|
A `.ics` filename only conventionally matches the UID. Radicale stores whatever the client that
|
|
wrote it chose, so `<uid>.ics` finds everything Officer wrote and misses everything a phone did.
|
|
The listing hands back the real href; these take it back unchanged.
|
|
|
|
── Why it is checked against this user's tree ──
|
|
|
|
`X-Remote-User` already scopes Radicale, and an href arriving in a request body is
|
|
attacker-shaped input either way. Two gates rather than one, for the same reason the reads above
|
|
check `collection`.
|
|
*/
|
|
}
|
|
|
|
return new Response('not found', { status: 404 });
|
|
},
|
|
});
|
|
|
|
console.log(`[caldav] listening on 127.0.0.1:${port}; radicale on ${radicale.url}; storage ${paths.storagePath}`);
|
|
|
|
type ReplyFn = (msg: SidecarEvent) => void;
|
|
|
|
function handleCommand(cmd: SidecarCommand, reply: ReplyFn) {
|
|
switch (cmd.type) {
|
|
case 'ping':
|
|
reply({ type: 'pong', id: cmd.id });
|
|
break;
|
|
default:
|
|
reply({
|
|
type: 'error',
|
|
id: (cmd as SidecarCommand).id,
|
|
error: `Unknown command type: ${(cmd as Record<string, unknown>).type}`,
|
|
});
|
|
}
|
|
}
|
|
|
|
const connection = createSidecarConnector({
|
|
apiUrl: `${API_URL}/api/sidecar/register`,
|
|
name: 'caldav',
|
|
handles: ['caldav'],
|
|
onCommand(cmd, reply) {
|
|
handleCommand(cmd as SidecarCommand, reply as ReplyFn);
|
|
},
|
|
onConnected() {
|
|
connection.send({ type: 'caldav:server', port });
|
|
console.log(`[caldav] reported server port ${port} to API`);
|
|
},
|
|
});
|
|
|
|
function shutdown(signal: string) {
|
|
console.log(`[caldav] ${signal} received, shutting down...`);
|
|
radicale.stop();
|
|
try {
|
|
server.stop(true);
|
|
} catch {
|
|
/* already stopped */
|
|
}
|
|
connection.destroy();
|
|
process.exit(0);
|
|
}
|
|
|
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
process.on('SIGINT', () => shutdown('SIGINT'));
|