@verax-ai/body 0.5.1 → 0.6.1
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/README.md +4 -3
- package/dist/approval-signature.d.ts +19 -0
- package/dist/approval-signature.js +70 -5
- package/dist/approve-cli.js +20 -24
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +146 -14
- package/dist/config.d.ts +27 -0
- package/dist/config.js +72 -1
- package/dist/control-signature.d.ts +4 -0
- package/dist/control-signature.js +20 -5
- package/dist/definitions.d.ts +9 -0
- package/dist/definitions.js +53 -0
- package/dist/demo.js +11 -11
- package/dist/doctor.js +72 -0
- package/dist/downstream-pin.d.ts +9 -0
- package/dist/downstream-pin.js +273 -0
- package/dist/downstream.d.ts +22 -2
- package/dist/downstream.js +312 -44
- package/dist/heartbeat.d.ts +26 -2
- package/dist/heartbeat.js +90 -7
- package/dist/held-spend.d.ts +16 -0
- package/dist/held-spend.js +20 -0
- package/dist/http-io.d.ts +14 -0
- package/dist/http-io.js +46 -0
- package/dist/init-local.d.ts +11 -0
- package/dist/init-local.js +32 -3
- package/dist/install.d.ts +5 -0
- package/dist/install.js +37 -5
- package/dist/main.d.ts +1 -0
- package/dist/main.js +40 -6
- package/dist/operator-cli.d.ts +49 -1
- package/dist/operator-cli.js +136 -8
- package/dist/operator-credentials.d.ts +40 -1
- package/dist/operator-credentials.js +97 -7
- package/dist/operator-door-page.d.ts +3 -0
- package/dist/operator-door-page.js +819 -0
- package/dist/operator-door.d.ts +22 -0
- package/dist/operator-door.js +487 -0
- package/dist/operator-handlers.d.ts +28 -0
- package/dist/operator-handlers.js +221 -0
- package/dist/operator-pairing.d.ts +2 -0
- package/dist/operator-pairing.js +11 -0
- package/dist/reconcile-cli.js +3 -1
- package/dist/server.d.ts +2 -0
- package/dist/server.js +133 -256
- package/dist/verify-cli.js +30 -10
- package/dist/webauthn-verify.d.ts +48 -4
- package/dist/webauthn-verify.js +183 -25
- package/dist/wiring.js +14 -1
- package/package.json +4 -4
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Server } from "node:http";
|
|
2
|
+
import type { OperatorDoorConfig } from "./config.ts";
|
|
3
|
+
import { checkPairing } from "./operator-pairing.ts";
|
|
4
|
+
import type { createBodyServices } from "./wiring.ts";
|
|
5
|
+
export declare const DOOR_SESSION_TTL_MS: number;
|
|
6
|
+
export declare const DOOR_CHALLENGE_TTL_MS: number;
|
|
7
|
+
/**
|
|
8
|
+
* The door answers for its own name, and for its own loopback address so the
|
|
9
|
+
* operator's proxy may forward either. A page on another name that resolves
|
|
10
|
+
* to this machine carries that other name here and is refused.
|
|
11
|
+
*/
|
|
12
|
+
export declare function doorHostAllowed(hostHeader: string | undefined, door: OperatorDoorConfig, listenPort: number): boolean;
|
|
13
|
+
export declare function openOperatorDoor(opts: {
|
|
14
|
+
door: OperatorDoorConfig;
|
|
15
|
+
stateDir: string;
|
|
16
|
+
services: ReturnType<typeof createBodyServices>;
|
|
17
|
+
now?: () => number;
|
|
18
|
+
/** How long an unauthenticated sign-in body may take to arrive. */
|
|
19
|
+
signinBodyMs?: number;
|
|
20
|
+
/** Test hook. Stands in for the pairing check, to make its write fail. */
|
|
21
|
+
checkPairing?: typeof checkPairing;
|
|
22
|
+
}): Promise<Server>;
|
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The operator door: a second listener that serves only what an operator
|
|
3
|
+
* needs away from the machine. Sign in with a passkey, see what is waiting,
|
|
4
|
+
* approve one request, stop and resume the body. It never serves `/mcp`, the
|
|
5
|
+
* ledger or the inventory, and it takes no token the main listener takes.
|
|
6
|
+
*
|
|
7
|
+
* It also serves the one page that does those things from a browser. The
|
|
8
|
+
* page is handed to anyone who asks; everything it shows comes from the
|
|
9
|
+
* routes below it, under the same checks as before.
|
|
10
|
+
*
|
|
11
|
+
* A passkey is enrolled through the door only with a pairing code that
|
|
12
|
+
* `verax operator enroll` printed at the machine. Enrolling opens no session
|
|
13
|
+
* and approves nothing.
|
|
14
|
+
*
|
|
15
|
+
* A session is a random value this process remembers and nothing else: there
|
|
16
|
+
* is no key on disk that could sign one, and a restart ends them all. The
|
|
17
|
+
* session lets the operator look. An approval still needs a passkey
|
|
18
|
+
* assertion made for that one request.
|
|
19
|
+
*/
|
|
20
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
21
|
+
import { rmSync } from "node:fs";
|
|
22
|
+
import { createServer } from "node:http";
|
|
23
|
+
import { loadApprovalsFromDir, terminalText } from "@verax-ai/proxy";
|
|
24
|
+
import { asAssertion } from "./approval-signature.js";
|
|
25
|
+
import { readBearer } from "./auth.js";
|
|
26
|
+
import { heldSpend } from "./held-spend.js";
|
|
27
|
+
import { contentLengthOverLimit, readJsonBody, send } from "./http-io.js";
|
|
28
|
+
import { DEFAULT_OPERATOR_SUB, everEnrolled, findCredential, hasRegisteredOperator, readCredentials, saveCredential, updateCounter, } from "./operator-credentials.js";
|
|
29
|
+
import { DOOR_CSS, DOOR_HTML, DOOR_JS } from "./operator-door-page.js";
|
|
30
|
+
import { handleApprove, handleApproveChallenge, handleControl } from "./operator-handlers.js";
|
|
31
|
+
import { checkPairing, consumePairing, pairingPath, readPairing } from "./operator-pairing.js";
|
|
32
|
+
import { COSE_ALGORITHMS, verifyAssertion, verifyRegistration } from "./webauthn-verify.js";
|
|
33
|
+
export const DOOR_SESSION_TTL_MS = 10 * 60_000;
|
|
34
|
+
export const DOOR_CHALLENGE_TTL_MS = 2 * 60_000;
|
|
35
|
+
const MAX_SESSIONS = 8;
|
|
36
|
+
const SIGNIN_BODY_BYTES = 16 * 1024;
|
|
37
|
+
const SIGNIN_BODY_MS = 5_000;
|
|
38
|
+
const MAX_SIGNINS_IN_FLIGHT = 32;
|
|
39
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
40
|
+
const HEADERS_TIMEOUT_MS = 20_000;
|
|
41
|
+
const SESSION_SCOPES = new Set(["verax:approve", "verax:audit"]);
|
|
42
|
+
/**
|
|
43
|
+
* The page loads its own script and stylesheet and talks to its own origin.
|
|
44
|
+
* Nothing else loads, nothing frames it, and the browsers that enforce
|
|
45
|
+
* Trusted Types refuse markup written from a string.
|
|
46
|
+
*/
|
|
47
|
+
const PAGE_HEADERS = {
|
|
48
|
+
"content-security-policy": "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; require-trusted-types-for 'script'; trusted-types 'none'",
|
|
49
|
+
"x-frame-options": "DENY",
|
|
50
|
+
"referrer-policy": "no-referrer",
|
|
51
|
+
"cross-origin-opener-policy": "same-origin",
|
|
52
|
+
"cross-origin-resource-policy": "same-origin",
|
|
53
|
+
};
|
|
54
|
+
/** The page is three files. They hold no secret and name nothing about this body, so they need no session. */
|
|
55
|
+
const PAGE = new Map([
|
|
56
|
+
["/", { type: "text/html; charset=utf-8", text: DOOR_HTML }],
|
|
57
|
+
["/door.js", { type: "text/javascript; charset=utf-8", text: DOOR_JS }],
|
|
58
|
+
["/door.css", { type: "text/css; charset=utf-8", text: DOOR_CSS }],
|
|
59
|
+
]);
|
|
60
|
+
/** Method and path, exactly. Anything else on the door is not found. */
|
|
61
|
+
const ROUTES = new Set([
|
|
62
|
+
"GET /",
|
|
63
|
+
"GET /door.js",
|
|
64
|
+
"GET /door.css",
|
|
65
|
+
"POST /api/enroll/options",
|
|
66
|
+
"POST /api/enroll",
|
|
67
|
+
"POST /api/signin/options",
|
|
68
|
+
"POST /api/signin",
|
|
69
|
+
"POST /api/signout",
|
|
70
|
+
"GET /api/waiting",
|
|
71
|
+
"GET /api/approve/challenge",
|
|
72
|
+
"POST /api/approve",
|
|
73
|
+
"GET /api/halt",
|
|
74
|
+
"POST /api/halt",
|
|
75
|
+
"GET /api/halt/challenge",
|
|
76
|
+
"POST /api/resume",
|
|
77
|
+
"GET /api/resume/challenge",
|
|
78
|
+
]);
|
|
79
|
+
function first(value) {
|
|
80
|
+
return Array.isArray(value) ? value[0] : value;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The door answers for its own name, and for its own loopback address so the
|
|
84
|
+
* operator's proxy may forward either. A page on another name that resolves
|
|
85
|
+
* to this machine carries that other name here and is refused.
|
|
86
|
+
*/
|
|
87
|
+
export function doorHostAllowed(hostHeader, door, listenPort) {
|
|
88
|
+
const raw = (hostHeader ?? "").trim().toLowerCase();
|
|
89
|
+
if (raw === "")
|
|
90
|
+
return false;
|
|
91
|
+
if (raw === new URL(door.origin).host)
|
|
92
|
+
return true;
|
|
93
|
+
return raw === `127.0.0.1:${listenPort}` || raw === `localhost:${listenPort}` || raw === `[::1]:${listenPort}`;
|
|
94
|
+
}
|
|
95
|
+
/** One operator, one name on the device, however many times it enrolls. */
|
|
96
|
+
function operatorUserId(sub) {
|
|
97
|
+
return createHash("sha256").update(`verax-operator:${sub}`, "utf8").digest("base64url");
|
|
98
|
+
}
|
|
99
|
+
function sessionKey(token) {
|
|
100
|
+
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
101
|
+
}
|
|
102
|
+
function challengeInClientData(clientDataJSON) {
|
|
103
|
+
try {
|
|
104
|
+
const parsed = JSON.parse(Buffer.from(clientDataJSON, "base64url").toString("utf8"));
|
|
105
|
+
if (!parsed || typeof parsed !== "object")
|
|
106
|
+
return null;
|
|
107
|
+
const challenge = parsed.challenge;
|
|
108
|
+
return typeof challenge === "string" && challenge !== "" ? challenge : null;
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Oldest out first: a Map keeps insertion order. */
|
|
115
|
+
function capped(map, max) {
|
|
116
|
+
while (map.size > max) {
|
|
117
|
+
const oldest = map.keys().next();
|
|
118
|
+
if (oldest.done)
|
|
119
|
+
return;
|
|
120
|
+
map.delete(oldest.value);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export async function openOperatorDoor(opts) {
|
|
124
|
+
const { door, stateDir, services } = opts;
|
|
125
|
+
const now = opts.now ?? (() => Date.now());
|
|
126
|
+
const pairingCheck = opts.checkPairing ?? checkPairing;
|
|
127
|
+
const sessions = new Map();
|
|
128
|
+
const signinBodyMs = opts.signinBodyMs ?? SIGNIN_BODY_MS;
|
|
129
|
+
let signinsInFlight = 0;
|
|
130
|
+
// A challenge is its own expiry and a random part under a MAC this process
|
|
131
|
+
// keys. Nothing is stored when one is handed out, so a caller who asks for
|
|
132
|
+
// a thousand takes nothing from the operator who asked for one. Sign-in and
|
|
133
|
+
// enrolment have a key each: a challenge made for one is not one for the other.
|
|
134
|
+
const signinKey = randomBytes(32);
|
|
135
|
+
const enrollKey = randomBytes(32);
|
|
136
|
+
const spent = new Map();
|
|
137
|
+
const mintChallenge = (key) => {
|
|
138
|
+
const head = Buffer.alloc(24);
|
|
139
|
+
head.writeBigUInt64BE(BigInt(now() + DOOR_CHALLENGE_TTL_MS), 0);
|
|
140
|
+
randomBytes(16).copy(head, 8);
|
|
141
|
+
return Buffer.concat([head, createHmac("sha256", key).update(head).digest()]).toString("base64url");
|
|
142
|
+
};
|
|
143
|
+
/** When a challenge this door made runs out, or null for one it did not make, one that ran out, or one already used. */
|
|
144
|
+
const challengeExpiry = (key, challenge) => {
|
|
145
|
+
const bytes = Buffer.from(challenge, "base64url");
|
|
146
|
+
if (bytes.length !== 56 || bytes.toString("base64url") !== challenge)
|
|
147
|
+
return null;
|
|
148
|
+
const head = bytes.subarray(0, 24);
|
|
149
|
+
const mac = createHmac("sha256", key).update(head).digest();
|
|
150
|
+
if (!timingSafeEqual(mac, bytes.subarray(24)))
|
|
151
|
+
return null;
|
|
152
|
+
const expiresAtMs = Number(head.readBigUInt64BE(0));
|
|
153
|
+
if (now() >= expiresAtMs || spent.has(challenge))
|
|
154
|
+
return null;
|
|
155
|
+
return expiresAtMs;
|
|
156
|
+
};
|
|
157
|
+
/** Good once. Only a verified answer gets a challenge onto this list, so a stranger cannot fill it. */
|
|
158
|
+
const spend = (challenge, expiresAtMs) => {
|
|
159
|
+
for (const [known, until] of spent)
|
|
160
|
+
if (now() >= until)
|
|
161
|
+
spent.delete(known);
|
|
162
|
+
spent.set(challenge, expiresAtMs);
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
165
|
+
* A body from a caller who has proved nothing yet: small, few are read at
|
|
166
|
+
* once, and one that dawdles is dropped. Null when the answer has gone out.
|
|
167
|
+
*/
|
|
168
|
+
const readUnvouched = async (req, res) => {
|
|
169
|
+
const declared = Number(first(req.headers["content-length"]) ?? "0");
|
|
170
|
+
if (Number.isFinite(declared) && declared > SIGNIN_BODY_BYTES) {
|
|
171
|
+
send(res, 413, { error: "payload-too-large" });
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
if (signinsInFlight >= MAX_SIGNINS_IN_FLIGHT) {
|
|
175
|
+
send(res, 503, { error: "busy" }, { "retry-after": "5" });
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
signinsInFlight += 1;
|
|
179
|
+
const dawdling = setTimeout(() => req.destroy(), signinBodyMs);
|
|
180
|
+
let parsed;
|
|
181
|
+
try {
|
|
182
|
+
parsed = await readJsonBody(req, SIGNIN_BODY_BYTES);
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
clearTimeout(dawdling);
|
|
186
|
+
signinsInFlight -= 1;
|
|
187
|
+
}
|
|
188
|
+
if (!parsed.ok) {
|
|
189
|
+
if ("tooLarge" in parsed) {
|
|
190
|
+
send(res, 413, { error: "payload-too-large" });
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
send(res, 400, { error: "bad-body" });
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
return { value: parsed.value };
|
|
197
|
+
};
|
|
198
|
+
// Wrong codes are counted in the pairing file, and that count is the only
|
|
199
|
+
// one. A wrong try that cannot be counted, as on a full disk, ends the code
|
|
200
|
+
// instead: the file is removed, which needs no room, and this body refuses
|
|
201
|
+
// the code for as long as it runs in case the file could not be removed either.
|
|
202
|
+
const uncountable = new Set();
|
|
203
|
+
const codeHolds = (code) => {
|
|
204
|
+
const open = readPairing(stateDir);
|
|
205
|
+
if (open && uncountable.has(open.hash))
|
|
206
|
+
return false;
|
|
207
|
+
try {
|
|
208
|
+
return pairingCheck(stateDir, code, now()).ok;
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
process.stderr.write(`verax-door: pairing check: ${terminalText(err instanceof Error ? err.message : "fault")}\n`);
|
|
212
|
+
if (open)
|
|
213
|
+
uncountable.add(open.hash);
|
|
214
|
+
try {
|
|
215
|
+
rmSync(pairingPath(stateDir), { force: true });
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
// The refusal above still stands while this body runs.
|
|
219
|
+
}
|
|
220
|
+
return false;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
// The handlers read the relying party from an environment. The door's is
|
|
224
|
+
// its own origin, whatever the process environment says.
|
|
225
|
+
const rpEnv = { VERAX_RP_ID: door.rpID, VERAX_RP_ORIGINS: door.origin };
|
|
226
|
+
const liveSession = (token) => {
|
|
227
|
+
if (!token)
|
|
228
|
+
return null;
|
|
229
|
+
const key = sessionKey(token);
|
|
230
|
+
const row = sessions.get(key);
|
|
231
|
+
if (!row)
|
|
232
|
+
return null;
|
|
233
|
+
// A credential taken off the machine ends the sessions it opened.
|
|
234
|
+
if (now() >= row.expiresAtMs || !findCredential(stateDir, row.credentialId)) {
|
|
235
|
+
sessions.delete(key);
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
return row;
|
|
239
|
+
};
|
|
240
|
+
const server = createServer(async (req, res) => {
|
|
241
|
+
try {
|
|
242
|
+
// What the door says names payees and amounts; no cache keeps a copy.
|
|
243
|
+
res.setHeader("cache-control", "no-store");
|
|
244
|
+
// One request to a connection. Many of the door's answers go out before
|
|
245
|
+
// a body is read, or without one being wanted, and a caller who goes on
|
|
246
|
+
// sending after such an answer must not hold the line: Node closes the
|
|
247
|
+
// socket once an answer marked like this has gone out.
|
|
248
|
+
res.setHeader("connection", "close");
|
|
249
|
+
const listenPort = server.address().port;
|
|
250
|
+
if (!doorHostAllowed(first(req.headers.host), door, listenPort)) {
|
|
251
|
+
send(res, 400, { error: "host-not-allowed" });
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const origin = first(req.headers.origin);
|
|
255
|
+
if (origin !== undefined && origin !== door.origin) {
|
|
256
|
+
send(res, 403, { error: "origin-not-allowed" });
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const url = new URL(req.url ?? "/", door.origin);
|
|
260
|
+
if (!ROUTES.has(`${req.method} ${url.pathname}`)) {
|
|
261
|
+
send(res, 404, { error: "not-found" });
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
// A browser names the origin on every POST. One that does not is not the door's page.
|
|
265
|
+
if (req.method === "POST" && origin === undefined) {
|
|
266
|
+
send(res, 403, { error: "origin-required" });
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (req.method === "POST" && contentLengthOverLimit(req)) {
|
|
270
|
+
send(res, 413, { error: "payload-too-large" });
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
// Before the operator check: the screen that takes a pairing code is this page.
|
|
274
|
+
const asset = PAGE.get(url.pathname);
|
|
275
|
+
if (asset) {
|
|
276
|
+
send(res, 200, asset.text, { "content-type": asset.type, ...PAGE_HEADERS });
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (url.pathname === "/api/enroll/options" || url.pathname === "/api/enroll") {
|
|
280
|
+
const read = await readUnvouched(req, res);
|
|
281
|
+
if (!read)
|
|
282
|
+
return;
|
|
283
|
+
const posted = read.value && typeof read.value === "object" ? read.value : {};
|
|
284
|
+
// Nothing is awaited from here to the answer. The count of wrong codes
|
|
285
|
+
// is read and written in one turn, so callers who arrive together
|
|
286
|
+
// still have five tries between them.
|
|
287
|
+
// One answer for no code asked for, a wrong one, one that ran out and
|
|
288
|
+
// one used up: a caller without the code is not told which.
|
|
289
|
+
if (!codeHolds(typeof posted.code === "string" ? posted.code : "")) {
|
|
290
|
+
send(res, 403, { error: "pairing-refused" });
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (url.pathname === "/api/enroll/options") {
|
|
294
|
+
send(res, 200, {
|
|
295
|
+
challenge: mintChallenge(enrollKey),
|
|
296
|
+
rp: { id: door.rpID, name: "Verax" },
|
|
297
|
+
user: {
|
|
298
|
+
id: operatorUserId(DEFAULT_OPERATOR_SUB),
|
|
299
|
+
name: DEFAULT_OPERATOR_SUB,
|
|
300
|
+
displayName: DEFAULT_OPERATOR_SUB,
|
|
301
|
+
},
|
|
302
|
+
pubKeyCredParams: COSE_ALGORITHMS.map((alg) => ({ type: "public-key", alg })),
|
|
303
|
+
authenticatorSelection: { userVerification: "required", residentKey: "preferred" },
|
|
304
|
+
attestation: "none",
|
|
305
|
+
excludeCredentials: readCredentials(stateDir).map((row) => ({ id: row.id, type: "public-key" })),
|
|
306
|
+
timeout: DOOR_CHALLENGE_TTL_MS,
|
|
307
|
+
});
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
// The caller holds the code, so the reason is theirs to read.
|
|
311
|
+
const refuse = (reason) => send(res, 403, { error: "enroll-refused", reason });
|
|
312
|
+
const registration = posted.response && typeof posted.response === "object" ? posted.response : null;
|
|
313
|
+
const clientData = registration?.response?.clientDataJSON;
|
|
314
|
+
const made = typeof clientData === "string" ? challengeInClientData(clientData) : null;
|
|
315
|
+
const madeUntilMs = made ? challengeExpiry(enrollKey, made) : null;
|
|
316
|
+
if (!registration || !made || madeUntilMs === null) {
|
|
317
|
+
refuse("challenge");
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const enrolled = verifyRegistration({
|
|
321
|
+
response: registration,
|
|
322
|
+
expectedChallenge: made,
|
|
323
|
+
expectedOrigins: [door.origin],
|
|
324
|
+
rpId: door.rpID,
|
|
325
|
+
});
|
|
326
|
+
if (!enrolled.ok) {
|
|
327
|
+
refuse(enrolled.reason);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
// A removed passkey is refused here too: enrolling it again would put
|
|
331
|
+
// another key under an id that approvals in the ledger were signed by.
|
|
332
|
+
if (everEnrolled(stateDir, enrolled.credentialId)) {
|
|
333
|
+
refuse("already-enrolled");
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
spend(made, madeUntilMs);
|
|
337
|
+
// The code goes first: if the write after it fails, the operator asks
|
|
338
|
+
// for another code, and no code outlives an enrolment it paid for.
|
|
339
|
+
consumePairing(stateDir);
|
|
340
|
+
saveCredential(stateDir, {
|
|
341
|
+
id: enrolled.credentialId,
|
|
342
|
+
publicKey: enrolled.publicKeyCose,
|
|
343
|
+
counter: enrolled.counter,
|
|
344
|
+
sub: DEFAULT_OPERATOR_SUB,
|
|
345
|
+
});
|
|
346
|
+
send(res, 200, { enrolled: true, sub: DEFAULT_OPERATOR_SUB });
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
// With no operator enrolled an approval over HTTP needs no signature.
|
|
350
|
+
// That path must not be reachable from here, so past enrolment the door stays shut.
|
|
351
|
+
if (!hasRegisteredOperator(stateDir)) {
|
|
352
|
+
send(res, 403, { error: "no-operator" });
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (url.pathname === "/api/signin/options") {
|
|
356
|
+
send(res, 200, {
|
|
357
|
+
challenge: mintChallenge(signinKey),
|
|
358
|
+
rpId: door.rpID,
|
|
359
|
+
allowCredentials: readCredentials(stateDir).map((row) => ({ id: row.id, type: "public-key" })),
|
|
360
|
+
userVerification: "required",
|
|
361
|
+
timeout: DOOR_CHALLENGE_TTL_MS,
|
|
362
|
+
});
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
if (url.pathname === "/api/signin") {
|
|
366
|
+
const read = await readUnvouched(req, res);
|
|
367
|
+
if (!read)
|
|
368
|
+
return;
|
|
369
|
+
const assertion = asAssertion(read.value?.assertion);
|
|
370
|
+
const challenge = assertion ? challengeInClientData(assertion.response.clientDataJSON) : null;
|
|
371
|
+
const expiresAtMs = challenge ? challengeExpiry(signinKey, challenge) : null;
|
|
372
|
+
const stored = assertion ? findCredential(stateDir, assertion.id) : null;
|
|
373
|
+
if (!assertion || !challenge || expiresAtMs === null || !stored) {
|
|
374
|
+
send(res, 403, { error: "signin-refused" });
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const verified = verifyAssertion({
|
|
378
|
+
response: assertion,
|
|
379
|
+
expectedChallenge: challenge,
|
|
380
|
+
expectedOrigins: [door.origin],
|
|
381
|
+
rpId: door.rpID,
|
|
382
|
+
publicKeyCose: stored.publicKey,
|
|
383
|
+
});
|
|
384
|
+
if (!verified.ok) {
|
|
385
|
+
send(res, 403, { error: "signin-refused" });
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
spend(challenge, expiresAtMs);
|
|
389
|
+
if (!updateCounter(stateDir, stored.id, verified.counter)) {
|
|
390
|
+
send(res, 403, { error: "cloned-authenticator" });
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const token = randomBytes(32).toString("base64url");
|
|
394
|
+
const session = { sub: stored.sub, credentialId: stored.id, expiresAtMs: now() + DOOR_SESSION_TTL_MS };
|
|
395
|
+
sessions.set(sessionKey(token), session);
|
|
396
|
+
capped(sessions, MAX_SESSIONS);
|
|
397
|
+
send(res, 200, { token, sub: session.sub, expiresAtMs: session.expiresAtMs });
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const token = readBearer(req.headers.authorization);
|
|
401
|
+
const session = liveSession(token);
|
|
402
|
+
if (!session) {
|
|
403
|
+
send(res, 401, { error: "unauthorized" });
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
if (url.pathname === "/api/signout") {
|
|
407
|
+
sessions.delete(sessionKey(token));
|
|
408
|
+
send(res, 200, { ok: true });
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (url.pathname === "/api/waiting") {
|
|
412
|
+
const at = now();
|
|
413
|
+
const waiting = loadApprovalsFromDir(stateDir)
|
|
414
|
+
.filter((row) => row.status === "pending" && row.expiresAtMs > at)
|
|
415
|
+
.map((row) => {
|
|
416
|
+
const spend = heldSpend(row);
|
|
417
|
+
return {
|
|
418
|
+
ref: row.ref,
|
|
419
|
+
requestHash: row.requestHash,
|
|
420
|
+
tool: row.subject,
|
|
421
|
+
args: row.args,
|
|
422
|
+
agent: row.brain,
|
|
423
|
+
rule: row.ruleText,
|
|
424
|
+
...(row.createdAtMs !== undefined ? { createdAtMs: row.createdAtMs } : {}),
|
|
425
|
+
expiresAtMs: row.expiresAtMs,
|
|
426
|
+
// The payee and the amount as `verax approve` prints them at the machine.
|
|
427
|
+
...(spend ? { spend } : {}),
|
|
428
|
+
};
|
|
429
|
+
});
|
|
430
|
+
send(res, 200, { waiting });
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
const operatorRequest = {
|
|
434
|
+
req,
|
|
435
|
+
res,
|
|
436
|
+
url,
|
|
437
|
+
stateDir,
|
|
438
|
+
services,
|
|
439
|
+
subject: session.sub,
|
|
440
|
+
scopes: SESSION_SCOPES,
|
|
441
|
+
refuseStale: async () => {
|
|
442
|
+
if (liveSession(token))
|
|
443
|
+
return false;
|
|
444
|
+
send(res, 401, { error: "unauthorized" });
|
|
445
|
+
return true;
|
|
446
|
+
},
|
|
447
|
+
env: rpEnv,
|
|
448
|
+
};
|
|
449
|
+
if (url.pathname === "/api/approve/challenge") {
|
|
450
|
+
await handleApproveChallenge(operatorRequest);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (url.pathname === "/api/approve") {
|
|
454
|
+
await handleApprove(operatorRequest);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
await handleControl(operatorRequest, {
|
|
458
|
+
resuming: url.pathname.startsWith("/api/resume"),
|
|
459
|
+
challenge: url.pathname.endsWith("/challenge"),
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
catch (err) {
|
|
463
|
+
if (res.headersSent)
|
|
464
|
+
return;
|
|
465
|
+
if (err instanceof TypeError) {
|
|
466
|
+
send(res, 400, { error: "bad-request" });
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
process.stderr.write(`verax-door: ${terminalText(err instanceof Error ? err.message : "fault")}\n`);
|
|
470
|
+
send(res, 500, { error: "fault" });
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
// An Expect the server does not know never reaches the handler above: Node
|
|
474
|
+
// answers 417 itself and keeps the line. The door gives that answer instead,
|
|
475
|
+
// closed like every other.
|
|
476
|
+
server.on("checkExpectation", (_req, res) => {
|
|
477
|
+
res.setHeader("cache-control", "no-store");
|
|
478
|
+
send(res, 417, { error: "expectation-failed" }, { connection: "close" });
|
|
479
|
+
});
|
|
480
|
+
server.requestTimeout = REQUEST_TIMEOUT_MS;
|
|
481
|
+
server.headersTimeout = HEADERS_TIMEOUT_MS;
|
|
482
|
+
await new Promise((resolve, reject) => {
|
|
483
|
+
server.once("error", reject);
|
|
484
|
+
server.listen(door.bindPort, door.bindHost, () => resolve());
|
|
485
|
+
});
|
|
486
|
+
return server;
|
|
487
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an operator session may do over HTTP: stop and resume the body, and
|
|
3
|
+
* approve a held call. The listener decides who is asking and hands that in;
|
|
4
|
+
* nothing here reads a bearer.
|
|
5
|
+
*/
|
|
6
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
7
|
+
import type { createBodyServices } from "./wiring.ts";
|
|
8
|
+
export type OperatorRequest = {
|
|
9
|
+
req: IncomingMessage;
|
|
10
|
+
res: ServerResponse;
|
|
11
|
+
url: URL;
|
|
12
|
+
stateDir: string;
|
|
13
|
+
services: ReturnType<typeof createBodyServices>;
|
|
14
|
+
/** The session's subject. It is written as who stopped, resumed or approved. */
|
|
15
|
+
subject: string;
|
|
16
|
+
scopes: ReadonlySet<string>;
|
|
17
|
+
/** Answers for a session that died since it was let in, and says so. */
|
|
18
|
+
refuseStale: () => Promise<boolean>;
|
|
19
|
+
/** Where the passkey relying party is read from. */
|
|
20
|
+
env: NodeJS.ProcessEnv;
|
|
21
|
+
};
|
|
22
|
+
/** `GET|POST halt`, `POST resume`, and the challenge for either. */
|
|
23
|
+
export declare function handleControl(ctx: OperatorRequest, what: {
|
|
24
|
+
resuming: boolean;
|
|
25
|
+
challenge: boolean;
|
|
26
|
+
}): Promise<void>;
|
|
27
|
+
export declare function handleApproveChallenge(ctx: OperatorRequest): Promise<void>;
|
|
28
|
+
export declare function handleApprove(ctx: OperatorRequest): Promise<void>;
|