@mandateops/cli-linux-x64 0.0.0-stage → 0.7.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.
Files changed (68) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +175 -2
  3. package/audit-lab/README.md +194 -0
  4. package/audit-lab/bin/mandateops +0 -0
  5. package/audit-lab/contracts/contact-plain-text.vectors.json +85 -0
  6. package/audit-lab/contracts/history-reading.md +185 -0
  7. package/audit-lab/contracts/history-reading.vectors.json +284 -0
  8. package/audit-lab/contracts/profiles.md +161 -0
  9. package/audit-lab/contracts/properties.md +512 -0
  10. package/audit-lab/contracts/sdk-config.md +155 -0
  11. package/audit-lab/contracts/system-under-test.md +385 -0
  12. package/audit-lab/contracts/test-provider.md +350 -0
  13. package/audit-lab/lab/compose.audit.yml +181 -0
  14. package/audit-lab/lab/config/fault-control.json +14 -0
  15. package/audit-lab/lab/examples/agents/Dockerfile +28 -0
  16. package/audit-lab/lab/examples/agents/codeloc.cjs +199 -0
  17. package/audit-lab/lab/examples/agents/load.cjs +9 -0
  18. package/audit-lab/lab/examples/agents/package-lock.json +2840 -0
  19. package/audit-lab/lab/examples/agents/package.json +9 -0
  20. package/audit-lab/lab/examples/agents/python/mandateops_codeloc.py +271 -0
  21. package/audit-lab/lab/examples/agents/python/sitecustomize.py +51 -0
  22. package/audit-lab/lab/examples/agents/requirements-python.txt +522 -0
  23. package/audit-lab/lab/examples/agents/telemetry-router.cjs +272 -0
  24. package/audit-lab/lab/examples/test-provider/.dockerignore +4 -0
  25. package/audit-lab/lab/examples/test-provider/Dockerfile +28 -0
  26. package/audit-lab/lab/examples/test-provider/bun.lock +405 -0
  27. package/audit-lab/lab/examples/test-provider/package.json +42 -0
  28. package/audit-lab/lab/examples/test-provider/src/amount.ts +32 -0
  29. package/audit-lab/lab/examples/test-provider/src/app.ts +538 -0
  30. package/audit-lab/lab/examples/test-provider/src/auth.ts +30 -0
  31. package/audit-lab/lab/examples/test-provider/src/barrier.ts +262 -0
  32. package/audit-lab/lab/examples/test-provider/src/codeloc.ts +27 -0
  33. package/audit-lab/lab/examples/test-provider/src/config.ts +311 -0
  34. package/audit-lab/lab/examples/test-provider/src/connect.ts +204 -0
  35. package/audit-lab/lab/examples/test-provider/src/declaration.ts +270 -0
  36. package/audit-lab/lab/examples/test-provider/src/declared.ts +198 -0
  37. package/audit-lab/lab/examples/test-provider/src/domain.ts +193 -0
  38. package/audit-lab/lab/examples/test-provider/src/egress.ts +396 -0
  39. package/audit-lab/lab/examples/test-provider/src/flow.ts +263 -0
  40. package/audit-lab/lab/examples/test-provider/src/gate.ts +301 -0
  41. package/audit-lab/lab/examples/test-provider/src/main.ts +31 -0
  42. package/audit-lab/lab/examples/test-provider/src/notify.ts +157 -0
  43. package/audit-lab/lab/examples/test-provider/src/owner.ts +60 -0
  44. package/audit-lab/lab/examples/test-provider/src/payment.ts +103 -0
  45. package/audit-lab/lab/examples/test-provider/src/profile.ts +417 -0
  46. package/audit-lab/lab/examples/test-provider/src/request.ts +201 -0
  47. package/audit-lab/lab/examples/test-provider/src/rows.ts +173 -0
  48. package/audit-lab/lab/examples/test-provider/src/schema.ts +114 -0
  49. package/audit-lab/lab/examples/test-provider/src/signature.ts +86 -0
  50. package/audit-lab/lab/examples/test-provider/src/staged.ts +318 -0
  51. package/audit-lab/lab/examples/test-provider/src/store.ts +432 -0
  52. package/audit-lab/lab/examples/test-provider/src/traffic.ts +50 -0
  53. package/audit-lab/lab/examples/test-provider/src/webauthn.d.ts +11 -0
  54. package/audit-lab/lab/examples/test-provider/src/wire.ts +153 -0
  55. package/audit-lab/lab/examples/test-provider/tsconfig.build.json +9 -0
  56. package/audit-lab/lab/examples/test-provider/tsconfig.json +24 -0
  57. package/audit-lab/lab/images/capture/Dockerfile +15 -0
  58. package/audit-lab/lab/images/capture/LICENSE +201 -0
  59. package/audit-lab/lab/images/fault-control/Dockerfile +13 -0
  60. package/audit-lab/lab/images/fault-control/LICENSE +21 -0
  61. package/audit-lab/lab/images/provider-store/Dockerfile +4 -0
  62. package/audit-lab/lab/images/provider-store/LICENSE +23 -0
  63. package/audit-lab/lab/images/telemetry/Dockerfile +14 -0
  64. package/audit-lab/lab/images/telemetry/LICENSE +201 -0
  65. package/audit-lab/lab/scripts/compose-down.sh +143 -0
  66. package/audit-lab/lab/scripts/compose-lib.sh +632 -0
  67. package/audit-lab/lab/scripts/compose-up.sh +240 -0
  68. package/package.json +16 -4
@@ -0,0 +1,538 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import rateLimit from "@fastify/rate-limit";
3
+ import Fastify from "fastify";
4
+ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
5
+ import { z } from "zod";
6
+ import { BEARER, requireCredential } from "./auth.js";
7
+ import { Barrier, Drops, Refusal } from "./barrier.js";
8
+ import type { Config, ServedProvider } from "./config.js";
9
+ import {
10
+ CONTROL_PREFIX,
11
+ idSchema,
12
+ instructionSchema,
13
+ ProviderError,
14
+ providerHostname,
15
+ } from "./domain.js";
16
+ import { providerLedger, settle } from "./payment.js";
17
+ import type { PaymentStep, SharedLedger } from "./payment.js";
18
+ import type { Observations } from "./store.js";
19
+ import { combinedFlow, FlowLog } from "./flow.js";
20
+ import { Traffic } from "./traffic.js";
21
+ import { callLine, takeCallId } from "./codeloc.js";
22
+ import type { PaymentWire, WireReply } from "./wire.js";
23
+ import { MAX_NOTIFY_COPIES, Notifier } from "./notify.js";
24
+ import type { DeliveryRecord } from "./notify.js";
25
+ import { InFlight, observedReply, RaceChoice } from "./profile.js";
26
+ import { MAX_COUNTED_KEYS } from "./domain.js";
27
+ import type { Effect, EffectSummary } from "./domain.js";
28
+
29
+ const effectParamsSchema = z.object({ effectId: idSchema }).strict();
30
+ const notifySchema = z
31
+ .object({
32
+ hold: z.boolean().default(false),
33
+ copies: z.number().int().min(1).max(MAX_NOTIFY_COPIES).optional(),
34
+ })
35
+ .strict();
36
+ const holdSchema = z
37
+ .object({ match: instructionSchema.partial().optional() })
38
+ .strict();
39
+ const effectCountsSchema = z
40
+ .object({
41
+ keys: z.array(z.string().min(1).max(255)).min(1).max(MAX_COUNTED_KEYS),
42
+ })
43
+ .strict();
44
+ const FORM_TYPE = "application/x-www-form-urlencoded";
45
+
46
+ /** Everything the provider keeps; a store owns it and nothing here sees how. */
47
+ export type ProviderRecords = SharedLedger &
48
+ Readonly<{
49
+ ping: () => Promise<void>;
50
+ observations: () => Promise<Observations>;
51
+ effect: (effectId: string) => Promise<Effect>;
52
+ /** Effects per key, for at most `MAX_COUNTED_KEYS` keys. */
53
+ effectCounts: (
54
+ keys: readonly string[],
55
+ ) => Promise<ReadonlyMap<string, number>>;
56
+ /** Totals over the whole run, with duplicates named up to a bound. */
57
+ effectSummary: () => Promise<EffectSummary>;
58
+ recordDelivery: (delivery: DeliveryRecord) => Promise<void>;
59
+ reset: () => Promise<void>;
60
+ close: () => Promise<void>;
61
+ }>;
62
+
63
+ const send = (reply: FastifyReply, { status, body, headers }: WireReply) =>
64
+ reply.code(status).headers(headers).send(body);
65
+
66
+ /** Route handlers by the provider name their routes are constrained to. */
67
+ function handlerStore<Handler>() {
68
+ const handlers = new Map<unknown, Handler>();
69
+ return {
70
+ get: (name: unknown): Handler | null => handlers.get(name) ?? null,
71
+ set: (name: unknown, handler: Handler): void => {
72
+ handlers.set(name, handler);
73
+ },
74
+ };
75
+ }
76
+
77
+ /** One provider of the run as the app serves it. */
78
+ type Served = Readonly<{
79
+ name: string;
80
+ wire: PaymentWire;
81
+ flow: FlowLog;
82
+ step: PaymentStep;
83
+ /** Waited before committing a key's first request; 0 for none. */
84
+ commitDelayMs: number;
85
+ /** Keys whose first request has waited, so a later one does not. */
86
+ delayedKeys: Set<string>;
87
+ }>;
88
+
89
+ /** The host a request names, without its port, in lower case. */
90
+ const requestedHost = (host: string | undefined): string =>
91
+ (host ?? "").replace(/:\d+$/, "").toLowerCase();
92
+
93
+ /**
94
+ * Which provider of the run a request reached, by the host it names. A run
95
+ * of one provider answers whatever host a request names; in a run of several
96
+ * a host naming none of them reaches none, so no call is credited to a
97
+ * provider it was not sent to.
98
+ */
99
+ function servedIndex(
100
+ providers: readonly ServedProvider[],
101
+ host: string | undefined,
102
+ ): number | undefined {
103
+ if (providers.length === 1) return 0;
104
+ const named = requestedHost(host);
105
+ const index = providers.findIndex(
106
+ (_provider, position) => providerHostname(position) === named,
107
+ );
108
+ return index < 0 ? undefined : index;
109
+ }
110
+
111
+ /** How a request to a host naming no provider of the run is listed. */
112
+ const UNKNOWN_HOST = "(unknown host)";
113
+
114
+ /** The media types one provider's format reads a body in. */
115
+ const acceptedTypes = (wire: PaymentWire): readonly string[] => [
116
+ "application/json",
117
+ ...(wire.jsonType ? [wire.jsonType] : []),
118
+ ...(wire.form ? [FORM_TYPE] : []),
119
+ ];
120
+
121
+ /** A request's media type, without parameters, in lower case. */
122
+ const mediaType = (header: string | undefined): string | undefined =>
123
+ header?.split(";")[0]?.trim().toLowerCase() || undefined;
124
+
125
+ const pause = (milliseconds: number): Promise<void> =>
126
+ milliseconds > 0
127
+ ? new Promise((resolve) => setTimeout(resolve, milliseconds))
128
+ : Promise.resolve();
129
+
130
+ /**
131
+ * Builds the test provider. Payments and runner controls require
132
+ * separate tokens; the payment caller cannot observe or steer the barrier.
133
+ */
134
+ export async function createApp(
135
+ config: Config,
136
+ records: ProviderRecords,
137
+ ): Promise<FastifyInstance> {
138
+ const { providers } = config;
139
+ // A host naming no provider derives a name no route is constrained to.
140
+ const providerOf = (request: IncomingMessage): string => {
141
+ const index = servedIndex(providers, request.headers.host);
142
+ return index === undefined ? "" : (providers[index]?.name ?? "");
143
+ };
144
+ const app = Fastify({
145
+ logger: false,
146
+ // Each provider's routes answer only the host that names that provider,
147
+ // so two providers may serve the same path.
148
+ routerOptions: {
149
+ constraints: {
150
+ provider: {
151
+ name: "provider",
152
+ storage: handlerStore,
153
+ deriveConstraint: providerOf,
154
+ mustMatchWhenDerived: false,
155
+ validate: (value: unknown) => idSchema.parse(value),
156
+ },
157
+ },
158
+ },
159
+ bodyLimit: config.bodyLimitBytes,
160
+ requestTimeout: config.requestTimeoutMs,
161
+ // A held response is idle by design; only the runner may end it.
162
+ connectionTimeout: 0,
163
+ onProtoPoisoning: "error",
164
+ onConstructorPoisoning: "error",
165
+ });
166
+ app.server.maxConnections = config.maxConnections;
167
+ await app.register(rateLimit, {
168
+ global: false,
169
+ max: config.rateLimitPerSecond,
170
+ timeWindow: config.rateWindowMs,
171
+ });
172
+ const wires = providers.map((provider) => provider.wire);
173
+ const jsonTypes = [
174
+ "application/json",
175
+ ...new Set(wires.flatMap((wire) => (wire.jsonType ? [wire.jsonType] : []))),
176
+ ];
177
+ const rawBodies = new WeakMap<FastifyRequest, string>();
178
+ const parseJson = app.getDefaultJsonParser("error", "error");
179
+ app.addContentTypeParser(
180
+ jsonTypes,
181
+ { parseAs: "string" },
182
+ (request, body, done) => {
183
+ rawBodies.set(request, String(body));
184
+ void parseJson(request, String(body), done);
185
+ },
186
+ );
187
+ if (wires.some((wire) => wire.form)) {
188
+ app.addContentTypeParser(
189
+ FORM_TYPE,
190
+ { parseAs: "string" },
191
+ (request, body, done) => {
192
+ rawBodies.set(request, String(body));
193
+ done(null, Object.fromEntries(new URLSearchParams(String(body))));
194
+ },
195
+ );
196
+ }
197
+ const traffic = new Traffic(config.proxyHost);
198
+ // Before every other hook: the code-location header is taken off, so no
199
+ // later step reads it, and kept for the payment's one log line.
200
+ const callIds = new WeakMap<FastifyRequest, string | null>();
201
+ app.addHook("onRequest", (request, _reply, done) => {
202
+ callIds.set(request, takeCallId(request.headers));
203
+ done();
204
+ });
205
+ const barrier = new Barrier();
206
+ const refusal = new Refusal();
207
+ const drops = new Drops();
208
+ const served: readonly Served[] = providers.map(
209
+ ({ name, wire, commitDelayMs }) => ({
210
+ name,
211
+ wire,
212
+ commitDelayMs,
213
+ delayedKeys: new Set<string>(),
214
+ flow: new FlowLog(name, {
215
+ payment: wire.path,
216
+ steps: wire.preparatory.map((route) => route.path),
217
+ flow: wire.financialFlow,
218
+ }),
219
+ step: {
220
+ ledger: providerLedger(records, name),
221
+ refusal,
222
+ counter: traffic,
223
+ wire,
224
+ },
225
+ }),
226
+ );
227
+ // Requests to a host naming no provider of the run, listed as unplaced.
228
+ const unknownHost = new FlowLog(UNKNOWN_HOST, {
229
+ payment: CONTROL_PREFIX,
230
+ steps: [],
231
+ flow: { operation: "unknown", moneyRoutes: {} },
232
+ });
233
+ const isControl = (request: FastifyRequest): boolean =>
234
+ request.routeOptions.url?.startsWith(CONTROL_PREFIX) ?? false;
235
+ const servedFor = (request: FastifyRequest): Served => {
236
+ const index = servedIndex(providers, request.headers.host);
237
+ const found = index === undefined ? undefined : served[index];
238
+ if (!found) throw new ProviderError(421, "misdirected_request");
239
+ return found;
240
+ };
241
+ // First of all: a request refused by a later hook still counts as received
242
+ // and is placed against the flow of the provider it reached. One naming no
243
+ // provider is listed as unplaced and refused.
244
+ app.addHook("onRequest", async (request) => {
245
+ if (isControl(request)) return;
246
+ const index = servedIndex(providers, request.headers.host);
247
+ const found = index === undefined ? undefined : served[index];
248
+ if (!found) {
249
+ unknownHost.record(request.method, request.routeOptions.url, request.url);
250
+ throw new ProviderError(421, "misdirected_request");
251
+ }
252
+ found.flow.record(request.method, request.routeOptions.url, request.url);
253
+ if (request.routeOptions.url === found.wire.path) {
254
+ await traffic.received(request.ip);
255
+ }
256
+ });
257
+ // A global hook runs before authentication, including rejected requests.
258
+ app.addHook("onRequest", app.rateLimit());
259
+ app.addHook("onClose", async () => {
260
+ barrier.reset();
261
+ await records.close();
262
+ });
263
+ const authenticate = async (request: FastifyRequest) => {
264
+ await servedFor(request).wire.authenticator.authenticate({
265
+ headers: request.headers,
266
+ url: request.url,
267
+ rawBody: rawBodies.get(request),
268
+ });
269
+ };
270
+ app.addHook("onRequest", async (request) => {
271
+ if (isControl(request))
272
+ requireCredential(
273
+ request.headers.authorization,
274
+ BEARER,
275
+ config.controlToken,
276
+ );
277
+ else if (!servedFor(request).wire.authenticator.needsBody)
278
+ await authenticate(request);
279
+ });
280
+ // Each provider reads bodies only in its own format's media types, whatever
281
+ // another provider of the run reads.
282
+ app.addHook("preValidation", (request, _reply, done) => {
283
+ if (isControl(request)) {
284
+ done();
285
+ return;
286
+ }
287
+ const type = mediaType(request.headers["content-type"]);
288
+ if (
289
+ type !== undefined &&
290
+ !acceptedTypes(servedFor(request).wire).includes(type)
291
+ )
292
+ done(new ProviderError(415, "unsupported_media_type"));
293
+ else done();
294
+ });
295
+ // After parsing, as a signed credential covers the exact body received.
296
+ app.addHook("preValidation", async (request) => {
297
+ if (!isControl(request) && servedFor(request).wire.authenticator.needsBody)
298
+ await authenticate(request);
299
+ });
300
+ app.setErrorHandler((error, _request, reply) => {
301
+ if (error instanceof ProviderError)
302
+ return reply.code(error.status).send({ error: error.code });
303
+ if (error instanceof z.ZodError)
304
+ return reply.code(400).send({ error: "invalid_input" });
305
+ if (
306
+ error instanceof Error &&
307
+ "statusCode" in error &&
308
+ (error.statusCode === 413 ||
309
+ error.statusCode === 415 ||
310
+ error.statusCode === 400 ||
311
+ error.statusCode === 429)
312
+ ) {
313
+ return reply.code(error.statusCode).send({ error: "invalid_request" });
314
+ }
315
+ return reply.code(503).send({ error: "operation_unavailable" });
316
+ });
317
+
318
+ const notifier = new Notifier(
319
+ records,
320
+ config.notifyTarget,
321
+ config.recordLimit,
322
+ );
323
+ // A replica answers as slowly as its calibration observed, and notifies
324
+ // with the observed copies and delay; without a profile, at once and once.
325
+ const routeBehaviour = new Map(
326
+ (config.profile?.replica.routes ?? []).map((one) => [one.route, one]),
327
+ );
328
+ const inFlight = new InFlight();
329
+ const raceChoice = new RaceChoice(config.raceSeed ?? 1);
330
+ /**
331
+ * A replica route answers after its observed delay; an identical request
332
+ * arriving meanwhile gets the observed race reply, before any record.
333
+ */
334
+ const paced = async (
335
+ request: FastifyRequest,
336
+ path: string,
337
+ answer: () => Promise<WireReply | FastifyReply>,
338
+ ): Promise<WireReply | FastifyReply> => {
339
+ const behaviour = routeBehaviour.get(path);
340
+ if (!behaviour) return answer();
341
+ const key = request.headers["idempotency-key"];
342
+ const fingerprint = JSON.stringify([
343
+ request.url,
344
+ typeof key === "string" ? key : null,
345
+ rawBodies.get(request) ?? null,
346
+ ]);
347
+ const race = behaviour.race;
348
+ return inFlight.run(
349
+ fingerprint,
350
+ () => {
351
+ if (!race.observed) return answer();
352
+ const reply = race.replies[raceChoice.next(race.replies.length)];
353
+ return reply ? observedReply(reply) : answer();
354
+ },
355
+ async () => {
356
+ await pause(behaviour.delayMs);
357
+ return answer();
358
+ },
359
+ );
360
+ };
361
+ const observedNotifications = config.profile?.replica.notifications;
362
+ const notifyDefaults = observedNotifications?.observed
363
+ ? {
364
+ copies: observedNotifications.copies,
365
+ delayMs: observedNotifications.delayMs,
366
+ }
367
+ : { copies: 1, delayMs: 0 };
368
+ const answer = (reply: FastifyReply, answered: WireReply | FastifyReply) =>
369
+ "sent" in answered ? answered : send(reply, answered);
370
+ const pay = async (
371
+ { wire, step, commitDelayMs, delayedKeys }: Served,
372
+ request: FastifyRequest,
373
+ reply: FastifyReply,
374
+ ): Promise<WireReply | FastifyReply> => {
375
+ if (wire.form && !request.headers["content-type"]?.startsWith(FORM_TYPE))
376
+ throw new ProviderError(415, "form_required");
377
+ const payment = wire.read(request.headers, request.body, request.params);
378
+ // A delayed provider has neither paid nor refused while it waits. Only a
379
+ // payment a reply fault is armed for waits, so an unfaulted run is not
380
+ // slowed.
381
+ const faulted =
382
+ barrier.armedFor(payment.instruction) ||
383
+ drops.armedFor(payment.instruction);
384
+ if (commitDelayMs > 0 && faulted && !delayedKeys.has(payment.key)) {
385
+ delayedKeys.add(payment.key);
386
+ await pause(commitDelayMs);
387
+ }
388
+ const settled = await settle(step, payment).catch((error: unknown) => {
389
+ console.log(callLine(callIds.get(request) ?? null, null));
390
+ throw error;
391
+ });
392
+ console.log(
393
+ callLine(
394
+ callIds.get(request) ?? null,
395
+ settled.kind === "answered" ? null : settled.effect.effectId,
396
+ ),
397
+ );
398
+ if (settled.kind === "answered") return settled.reply;
399
+ if (settled.created) wire.committed?.(settled.effect);
400
+ // A lost reply: the effect is committed and the answer never arrives.
401
+ if (drops.takes(settled.effect.instruction)) {
402
+ request.raw.socket.destroy();
403
+ reply.hijack();
404
+ return reply;
405
+ }
406
+ // The effect is committed; the barrier may now delay the information.
407
+ if (
408
+ barrier.capture(
409
+ settled.effect.effectId,
410
+ {
411
+ // Destroy the socket, not the response: under Bun 1.4.4,
412
+ // ServerResponse.destroy() writes an empty 200 before closing.
413
+ discard: () => request.raw.socket.destroy(),
414
+ },
415
+ settled.effect.instruction,
416
+ )
417
+ ) {
418
+ reply.hijack();
419
+ return reply;
420
+ }
421
+ return wire.paid(settled.effect, settled.created, payment.sentKey);
422
+ };
423
+ for (const provider of served) {
424
+ const { name, wire, step } = provider;
425
+ const constraints = { provider: name };
426
+ for (const route of wire.preparatory) {
427
+ app.route({
428
+ method: route.method ?? "POST",
429
+ url: route.path,
430
+ constraints,
431
+ handler: async (request, reply) =>
432
+ answer(
433
+ reply,
434
+ await paced(request, route.path, async () => {
435
+ const answered = route.answer(
436
+ request.body,
437
+ request.params,
438
+ request.headers,
439
+ );
440
+ if (answered.refused)
441
+ await step.ledger.reject(
442
+ answered.refused,
443
+ "idempotency_key_conflict",
444
+ );
445
+ return answered.reply;
446
+ }),
447
+ ),
448
+ });
449
+ }
450
+ app.post(wire.path, { constraints }, async (request, reply) =>
451
+ answer(
452
+ reply,
453
+ await paced(request, wire.path, () => pay(provider, request, reply)),
454
+ ),
455
+ );
456
+ }
457
+
458
+ app.get("/_control/ready", async () => {
459
+ await records.ping();
460
+ return { ready: true };
461
+ });
462
+ app.post("/_control/hold-next", (request) => {
463
+ barrier.arm(holdSchema.parse(request.body ?? {}).match);
464
+ return { armed: true };
465
+ });
466
+ app.post("/_control/refuse-next", (request) => {
467
+ refusal.arm(holdSchema.parse(request.body ?? {}).match);
468
+ return { armed: true };
469
+ });
470
+ app.post("/_control/drop-next", (request) => {
471
+ drops.arm(holdSchema.parse(request.body ?? {}).match);
472
+ return { armed: true };
473
+ });
474
+ app.post("/_control/withdraw", (request) => {
475
+ const match = holdSchema.parse(request.body ?? {}).match ?? {};
476
+ return {
477
+ refusal: refusal.withdraw(match),
478
+ drop: drops.withdraw(match),
479
+ };
480
+ });
481
+ app.get("/_control/barrier", () => barrier.view());
482
+ app.post("/_control/release", () => {
483
+ barrier.release();
484
+ return { released: true };
485
+ });
486
+ app.post("/_control/disarm", () => {
487
+ barrier.disarm();
488
+ return { disarmed: true };
489
+ });
490
+ app.get("/_control/traffic", () => ({
491
+ ...traffic.view(),
492
+ flow: combinedFlow(
493
+ served.map(({ flow }) => flow.view()),
494
+ unknownHost.view(),
495
+ ),
496
+ }));
497
+ app.get("/_control/effects", async () => ({
498
+ ...(await records.observations()),
499
+ payouts: wires.flatMap((wire) => wire.payouts?.() ?? []),
500
+ }));
501
+ app.post("/_control/effect-counts", async (request) => {
502
+ const { keys } = effectCountsSchema.parse(request.body ?? {});
503
+ return { counts: Object.fromEntries(await records.effectCounts(keys)) };
504
+ });
505
+ app.get("/_control/effect-summary", () => records.effectSummary());
506
+ app.post("/_control/notify/:effectId", async (request) => {
507
+ const { effectId } = effectParamsSchema.parse(request.params);
508
+ const asked = notifySchema.parse(request.body ?? {});
509
+ const plan = {
510
+ hold: asked.hold,
511
+ copies: asked.copies ?? notifyDefaults.copies,
512
+ };
513
+ if (!plan.hold) await pause(notifyDefaults.delayMs);
514
+ const answers = await notifier.issue(effectId, plan);
515
+ return { notified: true, held: plan.hold, answers };
516
+ });
517
+ app.post("/_control/notify-release", async () => ({
518
+ released: true,
519
+ answers: await notifier.release(),
520
+ }));
521
+ app.post("/_control/reset", async () => {
522
+ barrier.reset();
523
+ refusal.reset();
524
+ drops.reset();
525
+ for (const provider of served) {
526
+ provider.wire.reset();
527
+ provider.flow.reset();
528
+ provider.delayedKeys.clear();
529
+ }
530
+ unknownHost.reset();
531
+ traffic.reset();
532
+ notifier.reset();
533
+ raceChoice.reset();
534
+ await records.reset();
535
+ return { reset: true };
536
+ });
537
+ return app;
538
+ }
@@ -0,0 +1,30 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { ProviderError } from "./domain.js";
3
+
4
+ export const BEARER = "Bearer ";
5
+ const BASIC = "Basic ";
6
+
7
+ /** A constant-time comparison of two secrets. */
8
+ export function sameSecret(first: string, second: string): boolean {
9
+ const left = Buffer.from(first);
10
+ const right = Buffer.from(second);
11
+ return left.length === right.length && timingSafeEqual(left, right);
12
+ }
13
+
14
+ /** Basic credentials carry the secret as the password; the user name is free. */
15
+ export function requireBasicPassword(header: unknown, token: string): void {
16
+ if (typeof header !== "string" || !header.startsWith(BASIC))
17
+ throw new ProviderError(401, "unauthorised");
18
+ const decoded = Buffer.from(header.slice(BASIC.length), "base64");
19
+ const password = decoded.toString("utf8").split(":").slice(1).join(":");
20
+ requireCredential(password, "", token);
21
+ }
22
+
23
+ export function requireCredential(
24
+ header: unknown,
25
+ prefix: string,
26
+ token: string,
27
+ ): void {
28
+ if (typeof header !== "string" || !sameSecret(header, `${prefix}${token}`))
29
+ throw new ProviderError(401, "unauthorised");
30
+ }