@domandigital/synthetic 0.1.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @domandigital/synthetic
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 7c2f815: Security review (DD Checks C38). `verify` and `verifyRequest` refuse a body over `maxBodyBytes` (default 1 MiB) as a `shape` rejection before hashing, reading a streamed body only up to the cap. `upstashReplayGuard` times out after 2 s and so fails closed. `synthetic_rejected` beacons are throttled to one per client, form and reason a minute, so forged traffic cannot flood dd-checks. See `docs/synthetic-threat-model.md`.
8
+
3
9
  ## 0.1.0
4
10
 
5
11
  ### Minor Changes
package/dist/index.cjs CHANGED
@@ -48,6 +48,7 @@ __export(index_exports, {
48
48
  keysFromEnv: () => keysFromEnv,
49
49
  memoryReplayGuard: () => memoryReplayGuard,
50
50
  normaliseHostname: () => normaliseHostname,
51
+ resetRejectBeaconThrottle: () => resetRejectBeaconThrottle,
51
52
  scrubHeaders: () => scrubHeaders,
52
53
  scrubSentryEvent: () => scrubSentryEvent,
53
54
  scrubText: () => scrubText,
@@ -213,6 +214,7 @@ function keysFromEnv(env) {
213
214
 
214
215
  // src/verify.ts
215
216
  var DEFAULT_WINDOW_SECONDS = 120;
217
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
216
218
  var REJECT_REASONS = [
217
219
  "unsupported_version",
218
220
  "shape",
@@ -253,6 +255,10 @@ async function verifyInner(input, config) {
253
255
  if (input.method.toUpperCase() !== "POST" || host !== config.host.toLowerCase() || !paths.includes(path) || contentType === null || !config.contentTypes.map((t) => t.toLowerCase()).includes(mediaType(contentType))) {
254
256
  return reject("shape", h);
255
257
  }
258
+ const maxBody = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
259
+ if ((typeof input.body === "string" ? utf8(input.body).length : input.body.length) > maxBody) {
260
+ return reject("shape", h);
261
+ }
256
262
  const kid = h.get(HEADER.kid);
257
263
  const tsText = h.get(HEADER.ts);
258
264
  const runId = h.get(HEADER.run);
@@ -307,14 +313,42 @@ async function verifyInner(input, config) {
307
313
  }
308
314
  async function verifyRequest(request, config) {
309
315
  if (request.headers.get(HEADER.version) === null) return ordinary("not_synthetic");
316
+ const maxBody = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
317
+ const declared = Number(request.headers.get("content-length"));
318
+ if (Number.isFinite(declared) && declared > maxBody) return reject("shape", request.headers);
310
319
  let body;
311
320
  try {
312
- body = new Uint8Array(await request.clone().arrayBuffer());
321
+ const read = await readCapped(request.clone(), maxBody);
322
+ if (read === null) return reject("shape", request.headers);
323
+ body = read;
313
324
  } catch {
314
325
  return reject("malformed", request.headers);
315
326
  }
316
327
  return verify({ method: request.method, url: request.url, headers: request.headers, body }, config);
317
328
  }
329
+ async function readCapped(request, max) {
330
+ if (!request.body) return new Uint8Array(0);
331
+ const reader = request.body.getReader();
332
+ const chunks = [];
333
+ let total = 0;
334
+ for (; ; ) {
335
+ const { done, value } = await reader.read();
336
+ if (done) break;
337
+ total += value.length;
338
+ if (total > max) {
339
+ void reader.cancel().catch(() => void 0);
340
+ return null;
341
+ }
342
+ chunks.push(value);
343
+ }
344
+ const out = new Uint8Array(total);
345
+ let at = 0;
346
+ for (const c of chunks) {
347
+ out.set(c, at);
348
+ at += c.length;
349
+ }
350
+ return out;
351
+ }
318
352
  function syntheticReport(ctx, stages) {
319
353
  return { v: ctx.v, runId: ctx.runId, stages };
320
354
  }
@@ -332,6 +366,7 @@ function upstashReplayGuard(options) {
332
366
  const res = await doFetch(options.url.replace(/\/+$/, ""), {
333
367
  method: "POST",
334
368
  headers: { Authorization: `Bearer ${options.token}`, "Content-Type": "application/json" },
369
+ signal: AbortSignal.timeout(options.timeoutMs ?? 2e3),
335
370
  body: JSON.stringify(["SET", `synth:${runId}`, "1", "NX", "EX", String(options.ttlSeconds ?? 300)])
336
371
  });
337
372
  if (!res.ok) throw new Error(`upstash ${res.status}`);
@@ -447,6 +482,19 @@ function fireAndForget(options, run) {
447
482
  }
448
483
  return promise;
449
484
  }
485
+ var REJECT_BEACON_WINDOW_SECONDS = 60;
486
+ var recentRejects = /* @__PURE__ */ new Map();
487
+ function rejectBeaconDue(client, event, nowSeconds) {
488
+ const key = `${client}|${event.form}|${event.reason}`;
489
+ const last = recentRejects.get(key);
490
+ if (last !== void 0 && nowSeconds - last < REJECT_BEACON_WINDOW_SECONDS) return false;
491
+ if (recentRejects.size >= 256) recentRejects.clear();
492
+ recentRejects.set(key, nowSeconds);
493
+ return true;
494
+ }
495
+ function resetRejectBeaconThrottle() {
496
+ recentRejects.clear();
497
+ }
450
498
  function sendBeacon(options, event) {
451
499
  return fireAndForget(options, async () => {
452
500
  if (!BEACON_CODES.includes(event.code) || !ID_PATTERN.test(event.form)) return;
@@ -460,6 +508,7 @@ function sendBeacon(options, event) {
460
508
  if (event.code === "synthetic_rejected") {
461
509
  if (!event.reason || !REJECT_REASONS.includes(event.reason)) return;
462
510
  payload.reason = event.reason;
511
+ if (!rejectBeaconDue(options.client, event, payload.ts)) return;
463
512
  }
464
513
  await post(options, BEACON_PATH, "beacon", event.form, payload);
465
514
  });
@@ -550,6 +599,7 @@ function scrubSentryEvent(event) {
550
599
  keysFromEnv,
551
600
  memoryReplayGuard,
552
601
  normaliseHostname,
602
+ resetRejectBeaconThrottle,
553
603
  scrubHeaders,
554
604
  scrubSentryEvent,
555
605
  scrubText,
package/dist/index.d.cts CHANGED
@@ -140,6 +140,8 @@ interface VerifyConfig {
140
140
  /** Unix seconds. Defaults to the current time. */
141
141
  now?: number;
142
142
  windowSeconds?: number;
143
+ /** Largest body to hash, in bytes. Defaults to 1 MiB; a larger body is a `shape` rejection, unread. */
144
+ maxBodyBytes?: number;
143
145
  }
144
146
  interface VerifyInput {
145
147
  method: string;
@@ -205,6 +207,8 @@ interface UpstashReplayOptions {
205
207
  /** Defaults to 300 seconds, well past the ±120 s window. */
206
208
  ttlSeconds?: number;
207
209
  fetch?: typeof fetch;
210
+ /** Defaults to 2000 ms. A slow guard fails closed rather than holding the form open. */
211
+ timeoutMs?: number;
208
212
  }
209
213
  /** `SET synth:<runId> 1 NX EX 300` over Upstash's REST API. A failed call throws, which `verify` treats as a rejection. */
210
214
  declare function upstashReplayGuard(options: UpstashReplayOptions): ReplayGuard;
@@ -313,6 +317,8 @@ interface PurgeReceipt {
313
317
  /** Rows still present that are past `purge_after`. Anything above zero opens a warning. */
314
318
  remaining: number;
315
319
  }
320
+ /** Test hook: forget the throttle. */
321
+ declare function resetRejectBeaconThrottle(): void;
316
322
  /**
317
323
  * Sends a signed beacon to dd-checks. Fire-and-forget: never throws, never
318
324
  * rejects, and a bad argument is dropped rather than raised, because the
@@ -346,4 +352,4 @@ declare function scrubText(text: string): string;
346
352
  */
347
353
  declare function scrubSentryEvent<T extends object>(event: T): T;
348
354
 
349
- export { BEACON_CODES, BEACON_PATH, type BeaconCode, type BeaconEvent, CANARY_DOMAIN, CANONICAL_PREFIX, type CanonicalParts, DEFAULT_ENDPOINT, DEFAULT_WINDOW_SECONDS, FORM_MODES, HEADER, ID_PATTERN, MODES, PROTOCOL_VERSION, type PurgeReceipt, RECEIPT_PATH, REDACTED, REJECT_REASONS, RUN_ID_PATTERN, type RejectReason, type ReplayGuard, type ReporterOptions, SITEVERIFY_URL, type SignOptions, type SignedHeaders, type StageResult, type StageStatus, type SyntheticContext, type SyntheticEnv, type SyntheticKey, type SyntheticMode, SyntheticRecipientError, type TurnstileCheckOptions, type TurnstileCheckResult, type TurnstileOutcome, type UpstashReplayOptions, type VerifyConfig, type VerifyInput, type VerifyResult, assertCanaryRecipient, canaryAddress, canonicalString, generateRunId, hostAndPath, isCanaryRecipient, isProductionHost, isTurnstileTestKey, keysFromEnv, memoryReplayGuard, normaliseHostname, scrubHeaders, scrubSentryEvent, scrubText, sendBeacon, sendPurgeReceipt, sign, syntheticReport, turnstileConfigCheck, upstashReplayGuard, verify, verifyRequest };
355
+ export { BEACON_CODES, BEACON_PATH, type BeaconCode, type BeaconEvent, CANARY_DOMAIN, CANONICAL_PREFIX, type CanonicalParts, DEFAULT_ENDPOINT, DEFAULT_WINDOW_SECONDS, FORM_MODES, HEADER, ID_PATTERN, MODES, PROTOCOL_VERSION, type PurgeReceipt, RECEIPT_PATH, REDACTED, REJECT_REASONS, RUN_ID_PATTERN, type RejectReason, type ReplayGuard, type ReporterOptions, SITEVERIFY_URL, type SignOptions, type SignedHeaders, type StageResult, type StageStatus, type SyntheticContext, type SyntheticEnv, type SyntheticKey, type SyntheticMode, SyntheticRecipientError, type TurnstileCheckOptions, type TurnstileCheckResult, type TurnstileOutcome, type UpstashReplayOptions, type VerifyConfig, type VerifyInput, type VerifyResult, assertCanaryRecipient, canaryAddress, canonicalString, generateRunId, hostAndPath, isCanaryRecipient, isProductionHost, isTurnstileTestKey, keysFromEnv, memoryReplayGuard, normaliseHostname, resetRejectBeaconThrottle, scrubHeaders, scrubSentryEvent, scrubText, sendBeacon, sendPurgeReceipt, sign, syntheticReport, turnstileConfigCheck, upstashReplayGuard, verify, verifyRequest };
package/dist/index.d.ts CHANGED
@@ -140,6 +140,8 @@ interface VerifyConfig {
140
140
  /** Unix seconds. Defaults to the current time. */
141
141
  now?: number;
142
142
  windowSeconds?: number;
143
+ /** Largest body to hash, in bytes. Defaults to 1 MiB; a larger body is a `shape` rejection, unread. */
144
+ maxBodyBytes?: number;
143
145
  }
144
146
  interface VerifyInput {
145
147
  method: string;
@@ -205,6 +207,8 @@ interface UpstashReplayOptions {
205
207
  /** Defaults to 300 seconds, well past the ±120 s window. */
206
208
  ttlSeconds?: number;
207
209
  fetch?: typeof fetch;
210
+ /** Defaults to 2000 ms. A slow guard fails closed rather than holding the form open. */
211
+ timeoutMs?: number;
208
212
  }
209
213
  /** `SET synth:<runId> 1 NX EX 300` over Upstash's REST API. A failed call throws, which `verify` treats as a rejection. */
210
214
  declare function upstashReplayGuard(options: UpstashReplayOptions): ReplayGuard;
@@ -313,6 +317,8 @@ interface PurgeReceipt {
313
317
  /** Rows still present that are past `purge_after`. Anything above zero opens a warning. */
314
318
  remaining: number;
315
319
  }
320
+ /** Test hook: forget the throttle. */
321
+ declare function resetRejectBeaconThrottle(): void;
316
322
  /**
317
323
  * Sends a signed beacon to dd-checks. Fire-and-forget: never throws, never
318
324
  * rejects, and a bad argument is dropped rather than raised, because the
@@ -346,4 +352,4 @@ declare function scrubText(text: string): string;
346
352
  */
347
353
  declare function scrubSentryEvent<T extends object>(event: T): T;
348
354
 
349
- export { BEACON_CODES, BEACON_PATH, type BeaconCode, type BeaconEvent, CANARY_DOMAIN, CANONICAL_PREFIX, type CanonicalParts, DEFAULT_ENDPOINT, DEFAULT_WINDOW_SECONDS, FORM_MODES, HEADER, ID_PATTERN, MODES, PROTOCOL_VERSION, type PurgeReceipt, RECEIPT_PATH, REDACTED, REJECT_REASONS, RUN_ID_PATTERN, type RejectReason, type ReplayGuard, type ReporterOptions, SITEVERIFY_URL, type SignOptions, type SignedHeaders, type StageResult, type StageStatus, type SyntheticContext, type SyntheticEnv, type SyntheticKey, type SyntheticMode, SyntheticRecipientError, type TurnstileCheckOptions, type TurnstileCheckResult, type TurnstileOutcome, type UpstashReplayOptions, type VerifyConfig, type VerifyInput, type VerifyResult, assertCanaryRecipient, canaryAddress, canonicalString, generateRunId, hostAndPath, isCanaryRecipient, isProductionHost, isTurnstileTestKey, keysFromEnv, memoryReplayGuard, normaliseHostname, scrubHeaders, scrubSentryEvent, scrubText, sendBeacon, sendPurgeReceipt, sign, syntheticReport, turnstileConfigCheck, upstashReplayGuard, verify, verifyRequest };
355
+ export { BEACON_CODES, BEACON_PATH, type BeaconCode, type BeaconEvent, CANARY_DOMAIN, CANONICAL_PREFIX, type CanonicalParts, DEFAULT_ENDPOINT, DEFAULT_WINDOW_SECONDS, FORM_MODES, HEADER, ID_PATTERN, MODES, PROTOCOL_VERSION, type PurgeReceipt, RECEIPT_PATH, REDACTED, REJECT_REASONS, RUN_ID_PATTERN, type RejectReason, type ReplayGuard, type ReporterOptions, SITEVERIFY_URL, type SignOptions, type SignedHeaders, type StageResult, type StageStatus, type SyntheticContext, type SyntheticEnv, type SyntheticKey, type SyntheticMode, SyntheticRecipientError, type TurnstileCheckOptions, type TurnstileCheckResult, type TurnstileOutcome, type UpstashReplayOptions, type VerifyConfig, type VerifyInput, type VerifyResult, assertCanaryRecipient, canaryAddress, canonicalString, generateRunId, hostAndPath, isCanaryRecipient, isProductionHost, isTurnstileTestKey, keysFromEnv, memoryReplayGuard, normaliseHostname, resetRejectBeaconThrottle, scrubHeaders, scrubSentryEvent, scrubText, sendBeacon, sendPurgeReceipt, sign, syntheticReport, turnstileConfigCheck, upstashReplayGuard, verify, verifyRequest };
package/dist/index.js CHANGED
@@ -149,6 +149,7 @@ function keysFromEnv(env) {
149
149
 
150
150
  // src/verify.ts
151
151
  var DEFAULT_WINDOW_SECONDS = 120;
152
+ var DEFAULT_MAX_BODY_BYTES = 1048576;
152
153
  var REJECT_REASONS = [
153
154
  "unsupported_version",
154
155
  "shape",
@@ -189,6 +190,10 @@ async function verifyInner(input, config) {
189
190
  if (input.method.toUpperCase() !== "POST" || host !== config.host.toLowerCase() || !paths.includes(path) || contentType === null || !config.contentTypes.map((t) => t.toLowerCase()).includes(mediaType(contentType))) {
190
191
  return reject("shape", h);
191
192
  }
193
+ const maxBody = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
194
+ if ((typeof input.body === "string" ? utf8(input.body).length : input.body.length) > maxBody) {
195
+ return reject("shape", h);
196
+ }
192
197
  const kid = h.get(HEADER.kid);
193
198
  const tsText = h.get(HEADER.ts);
194
199
  const runId = h.get(HEADER.run);
@@ -243,14 +248,42 @@ async function verifyInner(input, config) {
243
248
  }
244
249
  async function verifyRequest(request, config) {
245
250
  if (request.headers.get(HEADER.version) === null) return ordinary("not_synthetic");
251
+ const maxBody = config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
252
+ const declared = Number(request.headers.get("content-length"));
253
+ if (Number.isFinite(declared) && declared > maxBody) return reject("shape", request.headers);
246
254
  let body;
247
255
  try {
248
- body = new Uint8Array(await request.clone().arrayBuffer());
256
+ const read = await readCapped(request.clone(), maxBody);
257
+ if (read === null) return reject("shape", request.headers);
258
+ body = read;
249
259
  } catch {
250
260
  return reject("malformed", request.headers);
251
261
  }
252
262
  return verify({ method: request.method, url: request.url, headers: request.headers, body }, config);
253
263
  }
264
+ async function readCapped(request, max) {
265
+ if (!request.body) return new Uint8Array(0);
266
+ const reader = request.body.getReader();
267
+ const chunks = [];
268
+ let total = 0;
269
+ for (; ; ) {
270
+ const { done, value } = await reader.read();
271
+ if (done) break;
272
+ total += value.length;
273
+ if (total > max) {
274
+ void reader.cancel().catch(() => void 0);
275
+ return null;
276
+ }
277
+ chunks.push(value);
278
+ }
279
+ const out = new Uint8Array(total);
280
+ let at = 0;
281
+ for (const c of chunks) {
282
+ out.set(c, at);
283
+ at += c.length;
284
+ }
285
+ return out;
286
+ }
254
287
  function syntheticReport(ctx, stages) {
255
288
  return { v: ctx.v, runId: ctx.runId, stages };
256
289
  }
@@ -268,6 +301,7 @@ function upstashReplayGuard(options) {
268
301
  const res = await doFetch(options.url.replace(/\/+$/, ""), {
269
302
  method: "POST",
270
303
  headers: { Authorization: `Bearer ${options.token}`, "Content-Type": "application/json" },
304
+ signal: AbortSignal.timeout(options.timeoutMs ?? 2e3),
271
305
  body: JSON.stringify(["SET", `synth:${runId}`, "1", "NX", "EX", String(options.ttlSeconds ?? 300)])
272
306
  });
273
307
  if (!res.ok) throw new Error(`upstash ${res.status}`);
@@ -383,6 +417,19 @@ function fireAndForget(options, run) {
383
417
  }
384
418
  return promise;
385
419
  }
420
+ var REJECT_BEACON_WINDOW_SECONDS = 60;
421
+ var recentRejects = /* @__PURE__ */ new Map();
422
+ function rejectBeaconDue(client, event, nowSeconds) {
423
+ const key = `${client}|${event.form}|${event.reason}`;
424
+ const last = recentRejects.get(key);
425
+ if (last !== void 0 && nowSeconds - last < REJECT_BEACON_WINDOW_SECONDS) return false;
426
+ if (recentRejects.size >= 256) recentRejects.clear();
427
+ recentRejects.set(key, nowSeconds);
428
+ return true;
429
+ }
430
+ function resetRejectBeaconThrottle() {
431
+ recentRejects.clear();
432
+ }
386
433
  function sendBeacon(options, event) {
387
434
  return fireAndForget(options, async () => {
388
435
  if (!BEACON_CODES.includes(event.code) || !ID_PATTERN.test(event.form)) return;
@@ -396,6 +443,7 @@ function sendBeacon(options, event) {
396
443
  if (event.code === "synthetic_rejected") {
397
444
  if (!event.reason || !REJECT_REASONS.includes(event.reason)) return;
398
445
  payload.reason = event.reason;
446
+ if (!rejectBeaconDue(options.client, event, payload.ts)) return;
399
447
  }
400
448
  await post(options, BEACON_PATH, "beacon", event.form, payload);
401
449
  });
@@ -485,6 +533,7 @@ export {
485
533
  keysFromEnv,
486
534
  memoryReplayGuard,
487
535
  normaliseHostname,
536
+ resetRejectBeaconThrottle,
488
537
  scrubHeaders,
489
538
  scrubSentryEvent,
490
539
  scrubText,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@domandigital/synthetic",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "description": "Signed synthetic-submission protocol for Doman Digital client forms: sign and verify, replay guard, recipient lock, Turnstile config self-check, beacons and purge receipts. Web Crypto only.",
6
6
  "license": "Apache-2.0",
@@ -30,12 +30,6 @@
30
30
  "dist",
31
31
  "test-vectors.json"
32
32
  ],
33
- "scripts": {
34
- "build": "tsup src/index.ts --format cjs,esm --dts --clean",
35
- "typecheck": "tsc --noEmit",
36
- "test": "vitest run && vitest run --config vitest.workers.config.ts",
37
- "prepublishOnly": "pnpm run build"
38
- },
39
33
  "devDependencies": {
40
34
  "@cloudflare/vitest-plugin": "^1.3.7",
41
35
  "@types/node": "^20",
@@ -58,5 +52,10 @@
58
52
  "publishConfig": {
59
53
  "access": "public",
60
54
  "provenance": true
55
+ },
56
+ "scripts": {
57
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
58
+ "typecheck": "tsc --noEmit",
59
+ "test": "vitest run && vitest run --config vitest.workers.config.ts"
61
60
  }
62
- }
61
+ }