@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.
- package/LICENSE +45 -0
- package/README.md +33 -2
- package/config.example.json +44 -0
- package/dist/acp/connection.js +175 -0
- package/dist/acp/types.js +23 -0
- package/dist/acp-session.js +212 -0
- package/dist/agents.js +111 -0
- package/dist/approvals.js +70 -0
- package/dist/auth.js +71 -0
- package/dist/bridge.js +103 -0
- package/dist/cli.js +612 -0
- package/dist/config.js +171 -0
- package/dist/daemon.js +191 -0
- package/dist/devices.js +82 -0
- package/dist/dirs.js +107 -0
- package/dist/errors.js +8 -0
- package/dist/events.js +38 -0
- package/dist/github.js +244 -0
- package/dist/http.js +63 -0
- package/dist/linear.js +105 -0
- package/dist/mock-agent.js +242 -0
- package/dist/notify.js +32 -0
- package/dist/pairing.js +166 -0
- package/dist/pending.js +108 -0
- package/dist/pki.js +94 -0
- package/dist/push.js +287 -0
- package/dist/qr.js +304 -0
- package/dist/questions.js +117 -0
- package/dist/relay.js +80 -0
- package/dist/server.js +256 -0
- package/dist/servers.js +92 -0
- package/dist/sessions.js +691 -0
- package/dist/summaries.js +70 -0
- package/dist/tailscale.js +51 -0
- package/dist/thread-store.js +74 -0
- package/dist/transcript.js +167 -0
- package/dist/version.js +4 -0
- package/dist/worktrees.js +157 -0
- package/dist/x509.js +144 -0
- package/package.json +63 -3
package/dist/notify.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional push via ntfy (https://ntfy.sh, or a self-hosted server). The ntfy
|
|
3
|
+
* iOS app's notifications mirror to the paired watch, so you get a buzz even
|
|
4
|
+
* when Agent Overwatch isn't running. Off unless `notify.ntfyUrl` is set.
|
|
5
|
+
*
|
|
6
|
+
* Only the agent name, thread title and a short summary are sent. Prefer a
|
|
7
|
+
* self-hosted server or a long random topic name: anyone who knows a public
|
|
8
|
+
* ntfy topic can read it.
|
|
9
|
+
*/
|
|
10
|
+
export function makeNotifier(config, log) {
|
|
11
|
+
const url = config.notify?.ntfyUrl;
|
|
12
|
+
if (!url)
|
|
13
|
+
return (_e) => { };
|
|
14
|
+
return (e) => {
|
|
15
|
+
const title = {
|
|
16
|
+
approval: `${e.agentName} needs approval`,
|
|
17
|
+
question: `${e.agentName} has a question`,
|
|
18
|
+
error: `${e.agentName} hit an error`,
|
|
19
|
+
reply: `${e.agentName} is waiting for you`,
|
|
20
|
+
}[e.kind];
|
|
21
|
+
const urgent = e.kind === "approval" || e.kind === "question";
|
|
22
|
+
const headers = {
|
|
23
|
+
Title: title,
|
|
24
|
+
Tags: urgent ? "warning" : e.kind === "error" ? "x" : "speech_balloon",
|
|
25
|
+
Priority: urgent ? "high" : "default",
|
|
26
|
+
};
|
|
27
|
+
if (config.notify?.ntfyToken)
|
|
28
|
+
headers.Authorization = `Bearer ${config.notify.ntfyToken}`;
|
|
29
|
+
const body = `${e.threadTitle}\n${e.message}`.slice(0, 400);
|
|
30
|
+
fetch(url, { method: "POST", headers, body }).catch((err) => log(`ntfy push failed: ${String(err)}`));
|
|
31
|
+
};
|
|
32
|
+
}
|
package/dist/pairing.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pairing protocol (v1), served on its own TLS listener that does NOT require a
|
|
3
|
+
* client certificate (the watch doesn't have one yet).
|
|
4
|
+
*
|
|
5
|
+
* watch → bridge POST /pair
|
|
6
|
+
* { deviceName, publicKey: b64(X9.63 P-256), nonce: b64(16–64 bytes),
|
|
7
|
+
* replaces?: <deviceId>,
|
|
8
|
+
* mac: b64(HMAC-SHA256(code, "ow-pair-v1|w|<fpS>|<publicKey>|<nonce>|<deviceName>|<replaces or empty>")) }
|
|
9
|
+
*
|
|
10
|
+
* bridge → watch 200
|
|
11
|
+
* { deviceId, hostName, token, clientCert: b64(DER), caCert: b64(DER), url,
|
|
12
|
+
* mac: b64(HMAC-SHA256(code, "ow-pair-v1|s|<fpS>|<nonce>|<sha256(clientCert)>|<sha256(caCert)>|<token>|<deviceId>")) }
|
|
13
|
+
*
|
|
14
|
+
* The code is made up by the watch and shown on its screen; you type it into
|
|
15
|
+
* `overwatch pair` on the host. Until you have, /pair answers 202 (waiting)
|
|
16
|
+
* without counting an attempt, so the watch just keeps asking.
|
|
17
|
+
*
|
|
18
|
+
* <fpS> is the hex SHA-256 of the TLS server certificate. The watch uses the
|
|
19
|
+
* certificate it saw in the handshake; the bridge uses its real one. If anyone
|
|
20
|
+
* sits in the middle with a different certificate, the MACs don't match and
|
|
21
|
+
* pairing fails — and since the code itself is never sent, they can't learn it
|
|
22
|
+
* except by brute force, which the 12-digit code, 5-attempt limit and 5-minute
|
|
23
|
+
* expiry make impractical.
|
|
24
|
+
*
|
|
25
|
+
* `replaces` is set when a watch re-pairs a host it was already paired with (its
|
|
26
|
+
* old certificate stopped working, or it re-scanned the QR code): the old device
|
|
27
|
+
* is revoked once the new one is issued, so stale certificates don't pile up.
|
|
28
|
+
* It's covered by the MAC, so only someone holding the code can ask for it, and
|
|
29
|
+
* it must be an exact device id.
|
|
30
|
+
*/
|
|
31
|
+
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
32
|
+
import { activePairingCode, consumePairingCode, MAX_PAIRING_ATTEMPTS } from "./auth.js";
|
|
33
|
+
import { fingerprint, p256PublicKeyFromX963 } from "./x509.js";
|
|
34
|
+
const PROTOCOL = "ow-pair-v1";
|
|
35
|
+
const MAX_BODY = 8 * 1024;
|
|
36
|
+
const hmac = (code, msg) => createHmac("sha256", code).update(msg, "utf8").digest();
|
|
37
|
+
const sha256hex = (b) => createHash("sha256").update(b).digest("hex");
|
|
38
|
+
export function watchMacMessage(fpS, publicKey, nonce, deviceName, replaces = "") {
|
|
39
|
+
return `${PROTOCOL}|w|${fpS}|${publicKey}|${nonce}|${deviceName}|${replaces}`;
|
|
40
|
+
}
|
|
41
|
+
const DEVICE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
42
|
+
/**
|
|
43
|
+
* The pairing address for the QR code / typing on the watch: just the host name when pairing is on
|
|
44
|
+
* the standard port 8443 (the watch assumes it), otherwise host:port (including :443, which a URL
|
|
45
|
+
* leaves implicit).
|
|
46
|
+
*/
|
|
47
|
+
export function pairingAddress(url) {
|
|
48
|
+
const u = new URL(url);
|
|
49
|
+
const port = u.port || "443";
|
|
50
|
+
return port === "8443" ? u.hostname : `${u.hostname}:${port}`;
|
|
51
|
+
}
|
|
52
|
+
export function bridgeMacMessage(o) {
|
|
53
|
+
return `${PROTOCOL}|s|${o.fpS}|${o.nonce}|${sha256hex(o.clientCert)}|${sha256hex(o.caCert)}|${o.token}|${o.deviceId}`;
|
|
54
|
+
}
|
|
55
|
+
export { hmac as pairingHmac };
|
|
56
|
+
function json(data, status = 200) {
|
|
57
|
+
return new Response(JSON.stringify(data), {
|
|
58
|
+
status,
|
|
59
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" },
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function b64(v, field, min, max) {
|
|
63
|
+
if (typeof v !== "string" || !/^[A-Za-z0-9+/]+={0,2}$/.test(v))
|
|
64
|
+
throw new Error(`${field} must be base64`);
|
|
65
|
+
const buf = Buffer.from(v, "base64");
|
|
66
|
+
if (buf.length < min || buf.length > max)
|
|
67
|
+
throw new Error(`${field} has the wrong length`);
|
|
68
|
+
return buf;
|
|
69
|
+
}
|
|
70
|
+
export function createPairingHandler(deps) {
|
|
71
|
+
const log = deps.log ?? (() => { });
|
|
72
|
+
let failures = 0;
|
|
73
|
+
let failuresForCode = "";
|
|
74
|
+
return async function handle(req) {
|
|
75
|
+
const url = new URL(req.url);
|
|
76
|
+
if (url.pathname === "/health" && req.method === "GET") {
|
|
77
|
+
return json({ ok: true, name: "agent-overwatch-pairing", protocol: PROTOCOL });
|
|
78
|
+
}
|
|
79
|
+
if (url.pathname !== "/pair" || req.method !== "POST")
|
|
80
|
+
return json({ error: "not found" }, 404);
|
|
81
|
+
const text = await req.text();
|
|
82
|
+
if (text.length > MAX_BODY)
|
|
83
|
+
return json({ error: "request body too large" }, 413);
|
|
84
|
+
let body;
|
|
85
|
+
try {
|
|
86
|
+
body = JSON.parse(text);
|
|
87
|
+
if (!body || typeof body !== "object" || Array.isArray(body))
|
|
88
|
+
throw new Error();
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return json({ error: "body must be a JSON object" }, 400);
|
|
92
|
+
}
|
|
93
|
+
const active = activePairingCode();
|
|
94
|
+
if (!active.ok) {
|
|
95
|
+
// Not typed in on the host yet (or it expired): the watch keeps polling. No attempt is counted.
|
|
96
|
+
return json({ waiting: true, error: "Waiting for you to type the code into `overwatch pair` on the host." }, 202);
|
|
97
|
+
}
|
|
98
|
+
if (failuresForCode !== active.code) {
|
|
99
|
+
failuresForCode = active.code;
|
|
100
|
+
failures = 0;
|
|
101
|
+
}
|
|
102
|
+
let deviceName;
|
|
103
|
+
let publicKeyB64;
|
|
104
|
+
let nonceB64;
|
|
105
|
+
let presentedMac;
|
|
106
|
+
let replaces = "";
|
|
107
|
+
let publicKey;
|
|
108
|
+
try {
|
|
109
|
+
const name = body.deviceName;
|
|
110
|
+
if (typeof name !== "string" || !/^[\p{L}\p{M}\p{N} '’._-]{1,64}$/u.test(name))
|
|
111
|
+
throw new Error("deviceName is invalid");
|
|
112
|
+
deviceName = name;
|
|
113
|
+
publicKeyB64 = body.publicKey;
|
|
114
|
+
nonceB64 = body.nonce;
|
|
115
|
+
publicKey = p256PublicKeyFromX963(b64(body.publicKey, "publicKey", 65, 65));
|
|
116
|
+
b64(body.nonce, "nonce", 16, 64);
|
|
117
|
+
presentedMac = b64(body.mac, "mac", 32, 32);
|
|
118
|
+
if (body.replaces !== undefined) {
|
|
119
|
+
if (typeof body.replaces !== "string" || !DEVICE_ID_RE.test(body.replaces))
|
|
120
|
+
throw new Error("replaces is invalid");
|
|
121
|
+
replaces = body.replaces;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
return json({ error: e.message }, 400);
|
|
126
|
+
}
|
|
127
|
+
const expected = hmac(active.code, watchMacMessage(deps.pki.serverFingerprint, publicKeyB64, nonceB64, deviceName, replaces));
|
|
128
|
+
if (!timingSafeEqual(expected, presentedMac)) {
|
|
129
|
+
failures++;
|
|
130
|
+
log(`pairing attempt failed (${failures}/${MAX_PAIRING_ATTEMPTS})`);
|
|
131
|
+
if (failures >= MAX_PAIRING_ATTEMPTS) {
|
|
132
|
+
consumePairingCode();
|
|
133
|
+
return json({ error: "Too many failed attempts; that code is now invalid. Run `overwatch pair` again." }, 410);
|
|
134
|
+
}
|
|
135
|
+
// Wrong code, or someone in the middle presented a different certificate.
|
|
136
|
+
return json({ error: "Pairing failed: wrong code, or the connection isn't reaching this bridge directly." }, 401);
|
|
137
|
+
}
|
|
138
|
+
consumePairingCode();
|
|
139
|
+
const clientCert = deps.pki.issueClientCertificate(publicKey, deviceName);
|
|
140
|
+
const { device, token } = deps.devices.add(deviceName, fingerprint(clientCert));
|
|
141
|
+
const mac = hmac(active.code, bridgeMacMessage({
|
|
142
|
+
fpS: deps.pki.serverFingerprint,
|
|
143
|
+
nonce: nonceB64,
|
|
144
|
+
clientCert,
|
|
145
|
+
caCert: deps.pki.caDer,
|
|
146
|
+
token,
|
|
147
|
+
deviceId: device.id,
|
|
148
|
+
}));
|
|
149
|
+
log(`paired device "${deviceName}" (${device.id.slice(0, 8)})`);
|
|
150
|
+
// Exact id only: revoke() also takes prefixes, which a re-pair must never use.
|
|
151
|
+
if (replaces && replaces !== device.id && deps.devices.list().some((d) => d.id === replaces)) {
|
|
152
|
+
const old = deps.devices.revoke(replaces);
|
|
153
|
+
if (old)
|
|
154
|
+
log(`revoked "${old.name}" (${old.id.slice(0, 8)}), which it replaces`);
|
|
155
|
+
}
|
|
156
|
+
return json({
|
|
157
|
+
deviceId: device.id,
|
|
158
|
+
hostName: deps.config.hostName,
|
|
159
|
+
token,
|
|
160
|
+
clientCert: clientCert.toString("base64"),
|
|
161
|
+
caCert: deps.pki.caDer.toString("base64"),
|
|
162
|
+
url: deps.config.secure?.publicURL ?? null,
|
|
163
|
+
mac: mac.toString("base64"),
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
}
|
package/dist/pending.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What agents are waiting on you for: tool approvals ("Run `pnpm test`?") and
|
|
3
|
+
* questions ("Which cache should I use?"). Each holds the agent's request open
|
|
4
|
+
* until you answer, and checks your answer against what was asked.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { HttpError } from "./errors.js";
|
|
8
|
+
import { AnswerError, answerFor } from "./questions.js";
|
|
9
|
+
export class PendingInputs {
|
|
10
|
+
entries = new Map();
|
|
11
|
+
/** Wait for you to approve or reject a tool call. Resolves with the option, or null if it's cancelled. */
|
|
12
|
+
approval(fields) {
|
|
13
|
+
const input = { ...fields, options: fields.options ?? [], id: randomUUID(), kind: "approval", createdAt: Date.now() };
|
|
14
|
+
const done = new Promise((resolve) => this.entries.set(input.id, { kind: "approval", input, resolve }));
|
|
15
|
+
return { input, done };
|
|
16
|
+
}
|
|
17
|
+
/** Wait for you to answer the agent's questions. A cancel (turn stopped, agent gone) aborts them. */
|
|
18
|
+
question(fields, required) {
|
|
19
|
+
const input = { ...fields, options: [], id: randomUUID(), kind: "question", createdAt: Date.now() };
|
|
20
|
+
const done = new Promise((resolve) => this.entries.set(input.id, { kind: "question", input, resolve, required }));
|
|
21
|
+
return { input, done };
|
|
22
|
+
}
|
|
23
|
+
list() {
|
|
24
|
+
return [...this.entries.values()].map((e) => e.input).sort((a, b) => a.createdAt - b.createdAt);
|
|
25
|
+
}
|
|
26
|
+
forThread(threadId) {
|
|
27
|
+
for (const e of this.entries.values())
|
|
28
|
+
if (e.input.threadId === threadId)
|
|
29
|
+
return e.input;
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
/** The turn was cancelled or the agent went away: everything it was waiting for is cancelled (per the ACP spec). */
|
|
33
|
+
cancelThread(threadId) {
|
|
34
|
+
for (const [id, e] of this.entries) {
|
|
35
|
+
if (e.input.threadId !== threadId)
|
|
36
|
+
continue;
|
|
37
|
+
this.entries.delete(id);
|
|
38
|
+
if (e.kind === "approval")
|
|
39
|
+
e.resolve(null);
|
|
40
|
+
else
|
|
41
|
+
e.resolve({ action: "cancel" });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Approve with one of the request's options, or null to dismiss it. With `remember`, an
|
|
46
|
+
* allow also asks for its exact command to be added to the rules. For a question, null skips it.
|
|
47
|
+
*/
|
|
48
|
+
approve(id, optionId, remember = false) {
|
|
49
|
+
const e = this.mustGet(id);
|
|
50
|
+
if (e.kind === "question") {
|
|
51
|
+
if (optionId !== null)
|
|
52
|
+
throw new HttpError(400, "this is a question: send answers instead");
|
|
53
|
+
this.entries.delete(id);
|
|
54
|
+
e.resolve({ action: "decline" });
|
|
55
|
+
return { input: e.input, said: "You skipped the question" };
|
|
56
|
+
}
|
|
57
|
+
const chosen = e.input.options.find((o) => o.optionId === optionId);
|
|
58
|
+
if (optionId !== null && !chosen)
|
|
59
|
+
throw new HttpError(400, "unknown optionId for this request");
|
|
60
|
+
const command = e.input.alwaysAllowCommand;
|
|
61
|
+
if (remember && (!command || !chosen?.kind.startsWith("allow")))
|
|
62
|
+
throw new HttpError(400, "this request can't be remembered");
|
|
63
|
+
this.entries.delete(id);
|
|
64
|
+
e.resolve(optionId);
|
|
65
|
+
if (!chosen)
|
|
66
|
+
return { input: e.input, said: "Approval dismissed" };
|
|
67
|
+
return remember
|
|
68
|
+
? { input: e.input, said: `Always allowed: ${command}`, remember: command }
|
|
69
|
+
: { input: e.input, said: `You chose: ${chosen.name}` };
|
|
70
|
+
}
|
|
71
|
+
/** Answer a question: `{ [questionId or its textField]: value | value[] }`, checked against the form. */
|
|
72
|
+
answer(id, answers) {
|
|
73
|
+
const e = this.mustGet(id);
|
|
74
|
+
if (e.kind !== "question")
|
|
75
|
+
throw new HttpError(400, "this is a tool approval: send an optionId instead");
|
|
76
|
+
const questions = e.input.questions ?? [];
|
|
77
|
+
let result;
|
|
78
|
+
try {
|
|
79
|
+
result = answerFor(questions, answers, e.required);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
if (err instanceof AnswerError)
|
|
83
|
+
throw new HttpError(400, err.message);
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
this.entries.delete(id);
|
|
87
|
+
e.resolve(result);
|
|
88
|
+
const said = describeAnswers(questions, result.action === "accept" ? result.content : {});
|
|
89
|
+
return { input: e.input, said: said ? `You answered: ${said}` : "You skipped the question" };
|
|
90
|
+
}
|
|
91
|
+
mustGet(id) {
|
|
92
|
+
const e = this.entries.get(id);
|
|
93
|
+
if (!e)
|
|
94
|
+
throw new HttpError(404, "nothing is waiting for that (already answered?)");
|
|
95
|
+
return e;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** "SQLite, in memory · Yes": the answers as you'd say them, option labels rather than values. */
|
|
99
|
+
function describeAnswers(questions, content) {
|
|
100
|
+
return questions
|
|
101
|
+
.map((q) => [...new Set([q.id, q.textField ?? q.id])]
|
|
102
|
+
.flatMap((field) => [content[field]].flat())
|
|
103
|
+
.filter((v) => v !== undefined)
|
|
104
|
+
.map((v) => q.options.find((o) => o.value === String(v))?.label ?? String(v))
|
|
105
|
+
.join(", "))
|
|
106
|
+
.filter(Boolean)
|
|
107
|
+
.join(" · ");
|
|
108
|
+
}
|
package/dist/pki.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createPrivateKey, createPublicKey, generateKeyPairSync, X509Certificate } from "node:crypto";
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { hostname } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { fingerprint, issueCertificate, toPem } from "./x509.js";
|
|
6
|
+
const CA_DAYS = 3650;
|
|
7
|
+
const LEAF_DAYS = 730;
|
|
8
|
+
const RENEW_BEFORE_DAYS = 30;
|
|
9
|
+
function writeSecret(path, data) {
|
|
10
|
+
writeFileSync(path, data, { mode: 0o600 });
|
|
11
|
+
chmodSync(path, 0o600);
|
|
12
|
+
}
|
|
13
|
+
export function loadOrCreatePki(home, bridgeName, extraHostnames = []) {
|
|
14
|
+
const dir = join(home, "pki");
|
|
15
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
16
|
+
chmodSync(dir, 0o700);
|
|
17
|
+
const p = (n) => join(dir, n);
|
|
18
|
+
const caName = `${bridgeName} Overwatch CA`;
|
|
19
|
+
// ---- CA (created once; rotating it un-pairs every device) ----
|
|
20
|
+
let caKey;
|
|
21
|
+
let caDer;
|
|
22
|
+
if (existsSync(p("ca.key")) && existsSync(p("ca.crt"))) {
|
|
23
|
+
caKey = createPrivateKey(readFileSync(p("ca.key")));
|
|
24
|
+
caDer = new X509Certificate(readFileSync(p("ca.crt"))).raw;
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
const kp = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
|
|
28
|
+
caKey = kp.privateKey;
|
|
29
|
+
caDer = issueCertificate({
|
|
30
|
+
role: "ca",
|
|
31
|
+
commonName: caName,
|
|
32
|
+
subjectPublicKey: kp.publicKey,
|
|
33
|
+
issuerName: caName,
|
|
34
|
+
issuerPublicKey: kp.publicKey,
|
|
35
|
+
issuerPrivateKey: kp.privateKey,
|
|
36
|
+
validDays: CA_DAYS,
|
|
37
|
+
});
|
|
38
|
+
writeSecret(p("ca.key"), caKey.export({ format: "pem", type: "pkcs8" }));
|
|
39
|
+
writeFileSync(p("ca.crt"), toPem(caDer));
|
|
40
|
+
}
|
|
41
|
+
const caCert = new X509Certificate(caDer);
|
|
42
|
+
const caPub = createPublicKey(caKey);
|
|
43
|
+
const issuerName = caCert.subject
|
|
44
|
+
.split("\n")
|
|
45
|
+
.find((l) => l.startsWith("CN="))
|
|
46
|
+
?.slice(3) ?? caName;
|
|
47
|
+
// ---- Server certificate (re-issued when names change or it nears expiry) ----
|
|
48
|
+
const altNames = [...new Set(["localhost", "127.0.0.1", hostname(), ...extraHostnames].filter(Boolean))];
|
|
49
|
+
const wantSan = altNames.map((n) => (/^\d+\.\d+\.\d+\.\d+$/.test(n) ? `IP Address:${n}` : `DNS:${n}`)).join(", ");
|
|
50
|
+
let serverDer = null;
|
|
51
|
+
let serverKeyPem = "";
|
|
52
|
+
if (existsSync(p("server.key")) && existsSync(p("server.crt"))) {
|
|
53
|
+
const cert = new X509Certificate(readFileSync(p("server.crt")));
|
|
54
|
+
const fresh = cert.validToDate.getTime() - Date.now() > RENEW_BEFORE_DAYS * 864e5;
|
|
55
|
+
if (fresh && cert.subjectAltName === wantSan && cert.verify(caPub)) {
|
|
56
|
+
serverDer = cert.raw;
|
|
57
|
+
serverKeyPem = readFileSync(p("server.key"), "utf8");
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (!serverDer) {
|
|
61
|
+
const kp = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
|
|
62
|
+
serverDer = issueCertificate({
|
|
63
|
+
role: "server",
|
|
64
|
+
commonName: bridgeName,
|
|
65
|
+
subjectPublicKey: kp.publicKey,
|
|
66
|
+
issuerName,
|
|
67
|
+
issuerPublicKey: caPub,
|
|
68
|
+
issuerPrivateKey: caKey,
|
|
69
|
+
validDays: LEAF_DAYS,
|
|
70
|
+
altNames,
|
|
71
|
+
});
|
|
72
|
+
serverKeyPem = kp.privateKey.export({ format: "pem", type: "pkcs8" });
|
|
73
|
+
writeSecret(p("server.key"), serverKeyPem);
|
|
74
|
+
writeFileSync(p("server.crt"), toPem(serverDer));
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
caDer,
|
|
78
|
+
caPem: toPem(caDer),
|
|
79
|
+
serverPem: toPem(serverDer),
|
|
80
|
+
serverKeyPem,
|
|
81
|
+
serverFingerprint: fingerprint(serverDer),
|
|
82
|
+
issueClientCertificate(publicKey, deviceName) {
|
|
83
|
+
return issueCertificate({
|
|
84
|
+
role: "client",
|
|
85
|
+
commonName: deviceName,
|
|
86
|
+
subjectPublicKey: publicKey,
|
|
87
|
+
issuerName,
|
|
88
|
+
issuerPublicKey: caPub,
|
|
89
|
+
issuerPrivateKey: caKey,
|
|
90
|
+
validDays: LEAF_DAYS,
|
|
91
|
+
});
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|