@jacoblee93/agent-overwatch 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ const MAX_QUESTIONS = 8;
2
+ const MAX_OPTIONS = 12;
3
+ const MAX_TEXT = 2_000;
4
+ const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
5
+ function options(list) {
6
+ return (list ?? [])
7
+ .filter((o) => typeof o === "string" || (o && typeof o.const === "string"))
8
+ .slice(0, MAX_OPTIONS)
9
+ .map((o) => typeof o === "string"
10
+ ? { value: o, label: clip(o, 120) }
11
+ : { value: o.const, label: clip(o.title ?? o.const, 120), ...(o.description ? { description: clip(o.description, 300) } : {}) });
12
+ }
13
+ /** The questions in a form elicitation, or [] if it isn't one we can show. */
14
+ export function questionsFrom(params) {
15
+ if (params.mode !== "form")
16
+ return [];
17
+ const props = params.requestedSchema?.properties ?? {};
18
+ const entries = Object.entries(props).filter(([, p]) => p && typeof p === "object");
19
+ const single = entries.filter(([k]) => !k.endsWith("_custom") || !props[k.slice(0, -"_custom".length)]).length === 1;
20
+ const out = [];
21
+ for (const [id, p] of entries) {
22
+ const base = id.endsWith("_custom") ? id.slice(0, -"_custom".length) : undefined;
23
+ if (base && props[base]) {
24
+ const q = out.find((x) => x.id === base);
25
+ if (q && q.options.length && p.type === "string")
26
+ q.textField = id;
27
+ continue;
28
+ }
29
+ const header = typeof p.title === "string" ? clip(p.title, 40) : undefined;
30
+ const text = clip((typeof p.description === "string" && p.description) || (single ? params.message : "") || header || id, 500);
31
+ if (p.type === "array") {
32
+ const opts = options(p.items?.anyOf ?? p.items?.enum);
33
+ if (opts.length)
34
+ out.push({ id, header, text, options: opts, multiSelect: true, kind: "array" });
35
+ }
36
+ else if (p.type === "boolean") {
37
+ out.push({
38
+ id,
39
+ header,
40
+ text,
41
+ options: [
42
+ { value: "true", label: "Yes" },
43
+ { value: "false", label: "No" },
44
+ ],
45
+ multiSelect: false,
46
+ kind: "boolean",
47
+ });
48
+ }
49
+ else if (p.type === "number" || p.type === "integer") {
50
+ out.push({ id, header, text, options: [], multiSelect: false, textField: id, kind: p.type });
51
+ }
52
+ else if (p.type === "string" || p.type === undefined) {
53
+ const opts = options(p.oneOf ?? p.enum);
54
+ out.push({ id, header, text, options: opts, multiSelect: false, kind: "string", ...(opts.length ? {} : { textField: id }) });
55
+ }
56
+ if (out.length >= MAX_QUESTIONS)
57
+ break;
58
+ }
59
+ return out;
60
+ }
61
+ export class AnswerError extends Error {
62
+ }
63
+ /**
64
+ * The response to send back for the watch's answers: `{ [field]: value | value[] }`,
65
+ * where a select takes option values and `textField`s take text. Unknown fields,
66
+ * unknown options and missing required fields are refused.
67
+ */
68
+ export function answerFor(questions, answers, required = []) {
69
+ const content = {};
70
+ const fields = new Map();
71
+ for (const q of questions) {
72
+ if (q.options.length)
73
+ fields.set(q.id, { q, text: false });
74
+ if (q.textField)
75
+ fields.set(q.textField, { q, text: true });
76
+ }
77
+ for (const [key, raw] of Object.entries(answers)) {
78
+ const f = fields.get(key);
79
+ if (!f)
80
+ throw new AnswerError(`"${key}" isn't a question here`);
81
+ if (raw === null || raw === undefined || raw === "")
82
+ continue;
83
+ const { q } = f;
84
+ if (f.text) {
85
+ if (typeof raw !== "string")
86
+ throw new AnswerError(`answer to "${key}" must be text`);
87
+ const text = raw.trim().slice(0, MAX_TEXT);
88
+ if (!text)
89
+ continue;
90
+ if (q.kind === "number" || q.kind === "integer") {
91
+ const n = Number(text);
92
+ if (!Number.isFinite(n) || (q.kind === "integer" && !Number.isInteger(n)))
93
+ throw new AnswerError(`"${text}" isn't a number`);
94
+ content[key] = n;
95
+ }
96
+ else
97
+ content[key] = text;
98
+ continue;
99
+ }
100
+ const picks = q.multiSelect ? raw : [raw];
101
+ if (!Array.isArray(picks) || !picks.every((v) => typeof v === "string" && q.options.some((o) => o.value === v)))
102
+ throw new AnswerError(`that isn't one of the options for "${q.header ?? q.text}"`);
103
+ if (q.kind === "boolean")
104
+ content[key] = picks[0] === "true";
105
+ else
106
+ content[key] = q.multiSelect ? [...new Set(picks)] : picks[0];
107
+ }
108
+ for (const r of required) {
109
+ if (fields.has(r) && content[r] === undefined)
110
+ throw new AnswerError("answer every question first");
111
+ }
112
+ return { action: "accept", content };
113
+ }
114
+ /** One line per question for a notification: "Which approach? Redis / Postgres / Skip". */
115
+ export function describeQuestions(questions) {
116
+ return questions.map((q) => (q.options.length ? `${q.text}\n${q.options.map((o) => o.label).join(" / ")}` : q.text)).join("\n");
117
+ }
package/dist/relay.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The Agent Overwatch relay (relay/ in this repo, a Cloudflare Worker): Apple push
3
+ * for bridges without an APNs key of their own (only the app's publisher can have one).
4
+ *
5
+ * The bridge has its own Ed25519 identity (relay-key.pem in the overwatch home, 0600);
6
+ * its relay ID is derived from the public key, and every request it makes is signed.
7
+ * The watch registers its push token with the relay for this bridge's ID and hands the
8
+ * bridge an opaque handle; the bridge can only push to handles registered for it.
9
+ *
10
+ * Off with `"relay": false` in the config (e.g. if you run it all yourself over Tailscale
11
+ * with your own APNs key, which takes precedence anyway).
12
+ */
13
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign } from "node:crypto";
14
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ /** The relay the published app uses (the watch only registers with this one). */
17
+ export const DEFAULT_RELAY_URL = "https://relay.agent-overwatch.workers.dev";
18
+ export const HANDLE_RE = /^[A-Za-z0-9_-]{22}$/;
19
+ export function relayURL(config) {
20
+ if (config.relay === false)
21
+ return undefined;
22
+ return (config.relay?.url ?? DEFAULT_RELAY_URL).replace(/\/+$/, "");
23
+ }
24
+ /** This bridge's relay identity, created on first use. */
25
+ export function loadRelayIdentity(home) {
26
+ const path = join(home, "relay-key.pem");
27
+ if (!existsSync(path)) {
28
+ const { privateKey } = generateKeyPairSync("ed25519");
29
+ writeFileSync(path, privateKey.export({ format: "pem", type: "pkcs8" }), { mode: 0o600 });
30
+ chmodSync(path, 0o600);
31
+ }
32
+ const privateKey = createPrivateKey(readFileSync(path));
33
+ const publicKey = createPublicKey(privateKey).export({ format: "der", type: "spki" }).subarray(-32);
34
+ const bridgeId = createHash("sha256").update(publicKey).digest().subarray(0, 16).toString("base64url");
35
+ return { privateKey, publicKey: Buffer.from(publicKey), bridgeId };
36
+ }
37
+ export class RelayClient {
38
+ url;
39
+ identity;
40
+ fetchImpl;
41
+ constructor(url, identity, fetchImpl = fetch) {
42
+ this.url = url;
43
+ this.identity = identity;
44
+ this.fetchImpl = fetchImpl;
45
+ }
46
+ /** A request signed with the bridge's key: `${method}\n${path}\n${time}\n${hex(sha256(body))}`. */
47
+ async signed(method, path, body) {
48
+ const time = String(Date.now());
49
+ const digest = createHash("sha256").update(body).digest("hex");
50
+ const sig = sign(null, Buffer.from(`${method}\n${path}\n${time}\n${digest}`), this.identity.privateKey);
51
+ try {
52
+ const res = await this.fetchImpl(`${this.url}${path}`, {
53
+ method,
54
+ body: body || undefined,
55
+ headers: {
56
+ "content-type": "application/json",
57
+ "x-ow-key": this.identity.publicKey.toString("base64url"),
58
+ "x-ow-time": time,
59
+ "x-ow-sig": sig.toString("base64url"),
60
+ },
61
+ signal: AbortSignal.timeout(15_000),
62
+ });
63
+ const data = (await res.json().catch(() => ({})));
64
+ return { status: res.status, reason: data.reason ?? data.error };
65
+ }
66
+ catch (e) {
67
+ return { status: 0, reason: e.message };
68
+ }
69
+ }
70
+ /** Confirm a handle this bridge's own watch gave it (pushes only go to claimed handles). */
71
+ claim(handle) {
72
+ return this.signed("POST", `/v1/push/handles/${handle}/claim`, "");
73
+ }
74
+ push(handle, payload, collapseId) {
75
+ return this.signed("POST", "/v1/push", JSON.stringify({ handle, payload, collapseId }));
76
+ }
77
+ removeHandle(handle) {
78
+ return this.signed("DELETE", `/v1/push/handles/${handle}`, "");
79
+ }
80
+ }
package/dist/server.js ADDED
@@ -0,0 +1,256 @@
1
+ import { bearerFrom, tokenMatches } from "./auth.js";
2
+ import { agentKind } from "./config.js";
3
+ import { GitHubError, GitHubInputError } from "./github.js";
4
+ import { HANDLE_RE } from "./relay.js";
5
+ import { LinearError } from "./linear.js";
6
+ import { HOST_ID_RE, TOKEN_RE } from "./push.js";
7
+ import { HttpError } from "./errors.js";
8
+ import { isInGitRepo } from "./worktrees.js";
9
+ const MAX_BODY_BYTES = 64 * 1024;
10
+ const MAX_TEXT_CHARS = 20_000;
11
+ const MAX_WAIT_SECONDS = 25;
12
+ function json(data, status = 200) {
13
+ return new Response(JSON.stringify(data), {
14
+ status,
15
+ headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
16
+ });
17
+ }
18
+ async function readBody(req) {
19
+ const len = Number(req.headers.get("content-length") ?? "0");
20
+ if (len > MAX_BODY_BYTES)
21
+ throw new HttpError(413, "request body too large");
22
+ const text = await req.text();
23
+ if (text.length > MAX_BODY_BYTES)
24
+ throw new HttpError(413, "request body too large");
25
+ if (!text)
26
+ return {};
27
+ try {
28
+ const v = JSON.parse(text);
29
+ if (!v || typeof v !== "object" || Array.isArray(v))
30
+ throw new Error();
31
+ return v;
32
+ }
33
+ catch {
34
+ throw new HttpError(400, "body must be a JSON object");
35
+ }
36
+ }
37
+ function str(body, key, opts = {}) {
38
+ const v = body[key];
39
+ if (v === undefined || v === null) {
40
+ if (opts.required)
41
+ throw new HttpError(400, `${key} is required`);
42
+ return undefined;
43
+ }
44
+ if (typeof v !== "string")
45
+ throw new HttpError(400, `${key} must be a string`);
46
+ if (v.length > (opts.max ?? 256))
47
+ throw new HttpError(400, `${key} is too long`);
48
+ return v;
49
+ }
50
+ /** Optional `settings: {settingId: value}` for a new thread (model, effort, mode). */
51
+ function settingsFrom(body) {
52
+ const v = body.settings;
53
+ if (v === undefined || v === null)
54
+ return {};
55
+ if (typeof v !== "object" || Array.isArray(v))
56
+ throw new HttpError(400, "settings must be an object");
57
+ const out = {};
58
+ for (const [k, val] of Object.entries(v).slice(0, 16)) {
59
+ if (typeof val !== "string" || k.length > 128 || val.length > 256)
60
+ throw new HttpError(400, "settings values must be short strings");
61
+ out[k] = val;
62
+ }
63
+ return out;
64
+ }
65
+ export function createHandler(deps) {
66
+ const { config, feed, sessions } = deps;
67
+ const log = deps.log ?? (() => { });
68
+ function overview(ctx) {
69
+ const deviceId = deps.deviceIdFor?.(ctx);
70
+ return {
71
+ version: feed.current,
72
+ // The paired device asking: lets it name itself when it re-pairs (see pairing.ts, `replaces`).
73
+ ...(deviceId ? { deviceId } : {}),
74
+ host: { name: config.hostName },
75
+ agents: config.agents.map((a) => ({ id: a.id, name: a.name, kind: agentKind(a) })),
76
+ directories: config.directories.map((w) => ({ id: w.id, name: w.name, git: isInGitRepo(w.path) })),
77
+ threads: sessions.listThreads(),
78
+ // Approvals and questions agents are waiting on you for.
79
+ pending: sessions.listPending(),
80
+ integrations: { linear: deps.linear?.enabled ?? false, github: deps.github?.enabled ?? false },
81
+ ...(deps.relay ? { relay: deps.relay } : {}),
82
+ };
83
+ }
84
+ async function route(req, url, ctx) {
85
+ const { pathname } = url;
86
+ const method = req.method;
87
+ if (pathname === "/api/health" && method === "GET") {
88
+ return json({ ok: true, name: "agent-overwatch", host: config.hostName });
89
+ }
90
+ // Everything below requires the bearer token.
91
+ const presented = bearerFrom(req);
92
+ if (!tokenMatches(presented, config.token) && !(deps.authorize?.(presented, ctx) ?? false))
93
+ return json({ error: "Not authorized. Pair this device again.", code: "unauthorized" }, 401);
94
+ if (pathname === "/api/overview" && method === "GET") {
95
+ const since = Number(url.searchParams.get("since") ?? "0");
96
+ const wait = Math.min(MAX_WAIT_SECONDS, Math.max(0, Number(url.searchParams.get("wait") ?? "0") || 0));
97
+ if (Number.isFinite(since) && since > 0 && wait > 0) {
98
+ await feed.waitForChange(since, wait * 1000);
99
+ }
100
+ return json(overview(ctx));
101
+ }
102
+ if (pathname === "/api/threads" && method === "POST") {
103
+ const body = await readBody(req);
104
+ const thread = await sessions.startThread(str(body, "agentId", { required: true }), str(body, "directoryId", { required: true }), str(body, "prompt", { required: true, max: MAX_TEXT_CHARS }), settingsFrom(body), { worktree: body.worktree === true, title: str(body, "title", { max: 200 }), branch: str(body, "branch", { max: 100 }) });
105
+ return json(thread, 201);
106
+ }
107
+ if (pathname === "/api/linear/issues" && method === "GET") {
108
+ if (!deps.linear)
109
+ throw new HttpError(404, "Linear isn't available on this bridge");
110
+ try {
111
+ return json({ issues: await deps.linear.issues() });
112
+ }
113
+ catch (e) {
114
+ if (e instanceof LinearError)
115
+ throw new HttpError(502, e.message);
116
+ throw e;
117
+ }
118
+ }
119
+ if (pathname === "/api/github/prs" && method === "GET") {
120
+ if (!deps.github)
121
+ throw new HttpError(404, "GitHub isn't available on this bridge");
122
+ try {
123
+ const prs = await deps.github.pullRequests(url.searchParams.get("directory") ?? undefined);
124
+ return json({ pullRequests: prs.map((p) => ({ ...p, threadIds: sessions.threadsLinkedTo("github_pr", p.id, p) })) });
125
+ }
126
+ catch (e) {
127
+ if (e instanceof GitHubInputError)
128
+ throw new HttpError(400, e.message);
129
+ if (e instanceof GitHubError)
130
+ throw new HttpError(502, e.message);
131
+ throw e;
132
+ }
133
+ }
134
+ const prDetail = /^\/api\/github\/prs\/([A-Za-z0-9-]{1,39})\/([A-Za-z0-9_.-]{1,100})\/(\d{1,9})$/.exec(pathname);
135
+ if (prDetail && method === "GET") {
136
+ if (!deps.github)
137
+ throw new HttpError(404, "GitHub isn't available on this bridge");
138
+ const [owner, repo, number] = [prDetail[1], prDetail[2], Number(prDetail[3])];
139
+ try {
140
+ const [checks, comments] = await Promise.all([deps.github.checks(owner, repo, number), deps.github.comments(owner, repo, number)]);
141
+ return json({ checks, comments, threadIds: sessions.threadsLinkedTo("github_pr", `${owner}/${repo}#${number}`) });
142
+ }
143
+ catch (e) {
144
+ if (e instanceof GitHubError)
145
+ throw new HttpError(502, e.message);
146
+ throw e;
147
+ }
148
+ }
149
+ if (pathname === "/api/push/register" && method === "POST") {
150
+ if (!deps.push)
151
+ throw new HttpError(404, "push isn't available on this bridge");
152
+ const body = await readBody(req);
153
+ const token = str(body, "token", { required: true });
154
+ const environment = str(body, "environment", { required: true });
155
+ const hostId = str(body, "hostId", { required: true });
156
+ if (!TOKEN_RE.test(token))
157
+ throw new HttpError(400, "token must be the APNs device token in hex");
158
+ if (environment !== "development" && environment !== "production")
159
+ throw new HttpError(400, "environment must be development or production");
160
+ if (!HOST_ID_RE.test(hostId))
161
+ throw new HttpError(400, "hostId must be a UUID");
162
+ const relayHandle = str(body, "relayHandle");
163
+ if (relayHandle !== undefined && !HANDLE_RE.test(relayHandle))
164
+ throw new HttpError(400, "relayHandle isn't a relay handle");
165
+ // Through the relay: claim the handle first, so the relay only pushes to watches we vouch for.
166
+ let pushEnabled = deps.push.enabled;
167
+ if (relayHandle && deps.claimRelayHandle) {
168
+ const claimed = await deps.claimRelayHandle(relayHandle);
169
+ if (claimed.status !== 200) {
170
+ log(`push: the relay didn't accept this watch's registration (${claimed.status} ${claimed.reason ?? ""})`.trim());
171
+ pushEnabled = false;
172
+ }
173
+ }
174
+ deps.push.registry.register({
175
+ token,
176
+ environment,
177
+ hostId,
178
+ deviceId: deps.deviceIdFor?.(ctx),
179
+ ...(relayHandle && pushEnabled ? { relayHandle } : {}),
180
+ });
181
+ log(`push: registered a watch${pushEnabled ? "" : " (push isn't available, so nothing will be sent)"}`);
182
+ return json({ ok: true, pushEnabled });
183
+ }
184
+ if (pathname === "/api/push/unregister" && method === "POST") {
185
+ const body = await readBody(req);
186
+ deps.push?.registry.remove(str(body, "token", { required: true }));
187
+ return json({ ok: true });
188
+ }
189
+ const agentSettings = /^\/api\/agents\/([A-Za-z0-9_.-]{1,64})\/settings$/.exec(pathname);
190
+ if (agentSettings && method === "GET") {
191
+ return json({ settings: await sessions.agentSettings(agentSettings[1]) });
192
+ }
193
+ const threadMatch = /^\/api\/threads\/([0-9a-f-]{36})(?:\/(prompt|cancel|close|settings|done))?$/.exec(pathname);
194
+ if (threadMatch) {
195
+ const [, id, action] = threadMatch;
196
+ if (!action && method === "GET") {
197
+ const limit = Number(url.searchParams.get("limit") ?? "120") || 120;
198
+ const detail = sessions.getThread(id, limit);
199
+ // Linked PRs with their latest known CI/review status (from the PR list cache; no extra GitHub calls).
200
+ const prs = deps.github?.cachedPullRequests() ?? [];
201
+ const pullRequests = prs.filter((p) => detail.links.some((l) => l.kind === "github_pr" && l.id === p.id) || (detail.branch && p.branch === detail.branch));
202
+ return json({ ...detail, pullRequests });
203
+ }
204
+ if (method === "POST" && action === "prompt") {
205
+ const body = await readBody(req);
206
+ await sessions.sendPrompt(id, str(body, "text", { required: true, max: MAX_TEXT_CHARS }));
207
+ return json(sessions.getThread(id));
208
+ }
209
+ if (method === "POST" && action === "settings") {
210
+ const body = await readBody(req);
211
+ await sessions.setSetting(id, str(body, "id", { required: true }), str(body, "value", { required: true }));
212
+ return json(sessions.getThread(id));
213
+ }
214
+ if (method === "POST" && action === "cancel") {
215
+ sessions.cancel(id);
216
+ return json(sessions.getThread(id));
217
+ }
218
+ if (method === "POST" && action === "done") {
219
+ sessions.markDone(id);
220
+ return json(sessions.getThread(id));
221
+ }
222
+ if (method === "POST" && action === "close") {
223
+ const { keptWorktree } = await sessions.close(id);
224
+ return json({ ok: true, keptWorktree });
225
+ }
226
+ }
227
+ // Answer what an agent is waiting on: an approval ({optionId, remember?}), a question
228
+ // ({answers: {field: value | [values]}}), or dismiss / skip it ({cancel: true}).
229
+ const inputMatch = /^\/api\/inputs\/([0-9a-f-]{36})$/.exec(pathname);
230
+ if (inputMatch && method === "POST") {
231
+ const body = await readBody(req);
232
+ if (body.answers !== undefined) {
233
+ if (!body.answers || typeof body.answers !== "object" || Array.isArray(body.answers))
234
+ throw new HttpError(400, "answers must be an object");
235
+ sessions.answer(inputMatch[1], body.answers);
236
+ return json({ ok: true });
237
+ }
238
+ const optionId = body.cancel === true ? null : str(body, "optionId", { required: true });
239
+ sessions.approve(inputMatch[1], optionId ?? null, body.remember === true);
240
+ return json({ ok: true });
241
+ }
242
+ return json({ error: "not found" }, 404);
243
+ }
244
+ return async function handle(req, ctx = {}) {
245
+ const url = new URL(req.url);
246
+ try {
247
+ return await route(req, url, ctx);
248
+ }
249
+ catch (e) {
250
+ if (e instanceof HttpError)
251
+ return json({ error: e.message }, e.status);
252
+ log(`unhandled error on ${req.method} ${url.pathname}: ${String(e?.stack ?? e)}`);
253
+ return json({ error: "internal error" }, 500);
254
+ }
255
+ };
256
+ }
@@ -0,0 +1,92 @@
1
+ import http from "node:http";
2
+ import https from "node:https";
3
+ import { clientCertFingerprint, nodeListener } from "./http.js";
4
+ import { createPairingHandler } from "./pairing.js";
5
+ import { createHandler } from "./server.js";
6
+ function listen(server, port, host) {
7
+ return new Promise((resolve, reject) => {
8
+ server.once("error", reject);
9
+ server.listen(port, host, () => {
10
+ server.off("error", reject);
11
+ resolve(server.address().port);
12
+ });
13
+ });
14
+ }
15
+ /**
16
+ * The bridge's three listeners:
17
+ * - local: plain HTTP for localhost tools / simulator / `tailscale serve` (admin token)
18
+ * - secure: mutual TLS for paired devices (bridge-CA client cert + that device's token)
19
+ * - pairing: TLS (server auth only) exposing just /health and /pair
20
+ */
21
+ export async function startServers(o) {
22
+ const { config, pki, devices, log } = o;
23
+ const local = http.createServer(nodeListener(createHandler(o.api), log));
24
+ const secureApi = nodeListener(createHandler({
25
+ ...o.api,
26
+ // A device token only works with that device's own certificate.
27
+ authorize: (token, ctx) => {
28
+ const device = devices.findByToken(token);
29
+ return !!device && !!ctx.clientCertFingerprint && device.certFingerprint === ctx.clientCertFingerprint;
30
+ },
31
+ deviceIdFor: (ctx) => devices.list().find((d) => d.certFingerprint === ctx.clientCertFingerprint)?.id,
32
+ }), log);
33
+ const isPaired = (fp) => !!fp && devices.list().some((d) => d.certFingerprint === fp);
34
+ const secure = https.createServer({
35
+ cert: pki.serverPem,
36
+ key: pki.serverKeyPem,
37
+ ca: pki.caPem,
38
+ requestCert: true,
39
+ rejectUnauthorized: true, // no client cert from our CA → handshake fails
40
+ minVersion: "TLSv1.2",
41
+ }, (req, res) => {
42
+ // OVERWATCH_LOG_REQUESTS=1: one line per request (device, path, status, time) to debug a watch's connection.
43
+ if (process.env.OVERWATCH_LOG_REQUESTS === "1") {
44
+ const started = Date.now();
45
+ const fp = clientCertFingerprint(req.socket);
46
+ const who = devices.list().find((d) => d.certFingerprint === fp);
47
+ res.on("finish", () => log(`mTLS ${who ? `${who.name} (${who.id.slice(0, 8)})` : "unknown device"} ${req.method} ${req.url?.split("?")[0]} → ${res.statusCode} in ${Date.now() - started}ms`));
48
+ res.on("close", () => {
49
+ if (!res.writableFinished)
50
+ log(`mTLS ${who?.id.slice(0, 8) ?? "?"} ${req.method} ${req.url?.split("?")[0]} → connection closed before responding (${Date.now() - started}ms)`);
51
+ });
52
+ }
53
+ // Certificates of revoked devices get a fixed answer (so the watch can tell
54
+ // the user to re-pair) and never reach the API handlers.
55
+ if (!isPaired(clientCertFingerprint(req.socket))) {
56
+ res.writeHead(403, { "content-type": "application/json", connection: "close" });
57
+ res.end(JSON.stringify({ error: "This device was revoked or the bridge was reset. Pair it again.", code: "device_revoked" }));
58
+ return;
59
+ }
60
+ secureApi(req, res);
61
+ });
62
+ // Revocation takes effect immediately: the certificate is checked against the
63
+ // paired devices on every request, including on already-open connections.
64
+ secure.on("secureConnection", (socket) => {
65
+ if (!clientCertFingerprint(socket))
66
+ socket.destroy(); // belt and braces; the handshake already required a cert
67
+ });
68
+ // Rejected handshakes (no client certificate, or one from another CA). Logged,
69
+ // rate-limited, so `overwatch start` output shows why a device can't connect.
70
+ let lastTlsLog = 0;
71
+ secure.on("tlsClientError", (err, socket) => {
72
+ if (Date.now() - lastTlsLog < 10_000)
73
+ return;
74
+ lastTlsLog = Date.now();
75
+ log(`mTLS handshake rejected from ${socket.remoteAddress ?? "?"}: ${err.code ?? ""} ${err.message}`.trim());
76
+ });
77
+ const pairing = https.createServer({ cert: pki.serverPem, key: pki.serverKeyPem, minVersion: "TLSv1.2" }, nodeListener(createPairingHandler({ config, pki, devices, log }), log));
78
+ const ports = {
79
+ local: await listen(local, config.listen.port, config.listen.hostname),
80
+ secure: await listen(secure, config.secure.port, config.secure.hostname),
81
+ pairing: await listen(pairing, config.secure.pairPort, config.secure.hostname),
82
+ };
83
+ return {
84
+ ports,
85
+ async close() {
86
+ for (const s of [local, secure, pairing]) {
87
+ s.closeAllConnections();
88
+ await new Promise((r) => s.close(() => r(undefined)));
89
+ }
90
+ },
91
+ };
92
+ }