@domandigital/synthetic 0.2.2 → 0.3.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 +6 -0
- package/README.md +27 -0
- package/dist/index.cjs +110 -0
- package/dist/index.d.cts +70 -1
- package/dist/index.d.ts +70 -1
- package/dist/index.js +106 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @domandigital/synthetic
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- c31349e: `fakeResend()`: a stand-in for Resend for a client's own pull request and deploy test runs, so they send no real email and use none of anyone's allowance. It answers `POST /emails` and `GET /emails/<id>` as Resend does and `GET /messages?runId=` as DD Checks' canary read does, refuses any address that is not a canary's, and can answer `daily_quota_exceeded` to test an allowance alert. Web Fetch only, so it runs in a Worker as well as in Node.
|
|
8
|
+
|
|
3
9
|
## 0.2.2
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -178,3 +178,30 @@ const safe = scrubHeaders(request.headers);
|
|
|
178
178
|
```sh
|
|
179
179
|
pnpm --filter @domandigital/synthetic test # Node, then workerd
|
|
180
180
|
```
|
|
181
|
+
|
|
182
|
+
## The fake Resend, for a client's own test runs
|
|
183
|
+
|
|
184
|
+
Synthetic standard section O2 (Doman-Digital `services/checks/docs/synthetic-standard.md`): a pull request or deploy run of a client's test suite sends no real email. The site posts to `fakeResend()` instead, through `RESEND_BASE_URL` (Resend's Node SDK reads it; a site that calls the API with `fetch` reads the same variable, and only off production). The suite then checks every email against it in the shapes it already reads: Resend's `GET /emails/<id>` for the body, and DD Checks' canary read (`GET /messages?runId=<run>`, the same answer as `/admin/canary/messages`) for "arrived once". Only the nightly run sends real mail, to the canary inbox.
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import { fakeResend } from "@domandigital/synthetic";
|
|
188
|
+
|
|
189
|
+
const resend = fakeResend(); // in memory; pass { store } to keep sends in a Worker's own storage
|
|
190
|
+
const res = await resend.fetch(request); // POST /emails, GET /emails/<id>, GET /messages?runId=<run>
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
It refuses any recipient, cc, bcc or reply-to that is not a canary address (as a receiver must, N3), so a test that types a real address fails on the pull request, before the nightly run could mail anyone. `fakeResend({ quota: n })` answers 429 `daily_quota_exceeded` after `n` sends, to test the site's allowance alert (O2.4).
|
|
194
|
+
|
|
195
|
+
In Node, behind `node:http`:
|
|
196
|
+
|
|
197
|
+
```js
|
|
198
|
+
import { createServer } from "node:http";
|
|
199
|
+
import { fakeResend } from "@domandigital/synthetic";
|
|
200
|
+
|
|
201
|
+
const resend = fakeResend();
|
|
202
|
+
createServer(async (req, res) => {
|
|
203
|
+
const body = req.method === "POST" ? await new Response(req).arrayBuffer() : undefined;
|
|
204
|
+
const answer = await resend.fetch(new Request(`http://localhost${req.url}`, { method: req.method, headers: req.headers, body }));
|
|
205
|
+
res.writeHead(answer.status, Object.fromEntries(answer.headers)).end(await answer.text());
|
|
206
|
+
}).listen(8790, "localhost"); // RESEND_BASE_URL=http://localhost:8790
|
|
207
|
+
```
|
package/dist/index.cjs
CHANGED
|
@@ -39,7 +39,9 @@ __export(index_exports, {
|
|
|
39
39
|
SyntheticRecipientError: () => SyntheticRecipientError,
|
|
40
40
|
assertCanaryRecipient: () => assertCanaryRecipient,
|
|
41
41
|
canaryAddress: () => canaryAddress,
|
|
42
|
+
canaryRows: () => canaryRows,
|
|
42
43
|
canonicalString: () => canonicalString,
|
|
44
|
+
fakeResend: () => fakeResend,
|
|
43
45
|
generateRunId: () => generateRunId,
|
|
44
46
|
hostAndPath: () => hostAndPath,
|
|
45
47
|
isCanaryRecipient: () => isCanaryRecipient,
|
|
@@ -47,7 +49,9 @@ __export(index_exports, {
|
|
|
47
49
|
isTurnstileTestKey: () => isTurnstileTestKey,
|
|
48
50
|
keysFromEnv: () => keysFromEnv,
|
|
49
51
|
memoryReplayGuard: () => memoryReplayGuard,
|
|
52
|
+
memoryStore: () => memoryStore,
|
|
50
53
|
normaliseHostname: () => normaliseHostname,
|
|
54
|
+
parseCanary: () => parseCanary,
|
|
51
55
|
resetRejectBeaconThrottle: () => resetRejectBeaconThrottle,
|
|
52
56
|
scrubHeaders: () => scrubHeaders,
|
|
53
57
|
scrubSentryEvent: () => scrubSentryEvent,
|
|
@@ -569,6 +573,108 @@ function scrubSentryEvent(event) {
|
|
|
569
573
|
return copy;
|
|
570
574
|
}
|
|
571
575
|
}
|
|
576
|
+
|
|
577
|
+
// src/fake-resend.ts
|
|
578
|
+
function memoryStore() {
|
|
579
|
+
const emails = /* @__PURE__ */ new Map();
|
|
580
|
+
const keys = /* @__PURE__ */ new Map();
|
|
581
|
+
return {
|
|
582
|
+
idFor: async (key) => keys.get(key) ?? null,
|
|
583
|
+
save: async (email, key) => {
|
|
584
|
+
emails.set(email.id, email);
|
|
585
|
+
if (key) keys.set(key, email.id);
|
|
586
|
+
},
|
|
587
|
+
get: async (id) => emails.get(id) ?? null,
|
|
588
|
+
all: async () => [...emails.values()]
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
var CANARY = new RegExp(`^([su])-([a-z0-9]{4,40})@${CANARY_DOMAIN.replace(/\./g, "\\.")}$`);
|
|
592
|
+
function parseCanary(address) {
|
|
593
|
+
const m = CANARY.exec(address.trim().toLowerCase());
|
|
594
|
+
return m ? { kind: m[1], runId: m[2] } : null;
|
|
595
|
+
}
|
|
596
|
+
var list = (value) => {
|
|
597
|
+
if (value === void 0 || value === null) return [];
|
|
598
|
+
const items = Array.isArray(value) ? value : [value];
|
|
599
|
+
return items.every((v) => typeof v === "string") ? items : null;
|
|
600
|
+
};
|
|
601
|
+
var addressOf = (value) => /<([^>]+)>\s*$/.exec(value)?.[1] ?? value;
|
|
602
|
+
function canaryRows(emails, runId) {
|
|
603
|
+
const run = runId.toLowerCase();
|
|
604
|
+
const rows = /* @__PURE__ */ new Map();
|
|
605
|
+
for (const email of emails) {
|
|
606
|
+
for (const address of [...email.to, ...email.cc, ...email.bcc]) {
|
|
607
|
+
const canary = parseCanary(address);
|
|
608
|
+
if (!canary || canary.runId !== run) continue;
|
|
609
|
+
const row = rows.get(canary.kind);
|
|
610
|
+
if (row) row.copies += 1;
|
|
611
|
+
else rows.set(canary.kind, { kind: canary.kind, receivedAt: email.createdAt, subject: email.subject, sender: email.from, authResults: null, resendMessageId: email.id, copies: 1 });
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return [...rows.values()];
|
|
615
|
+
}
|
|
616
|
+
function fakeResend(options = {}) {
|
|
617
|
+
const store = options.store ?? memoryStore();
|
|
618
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
619
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
620
|
+
const error = (status, name, message) => json(status, { statusCode: status, name, message });
|
|
621
|
+
async function send(request) {
|
|
622
|
+
if (!/^Bearer \S+$/.test(request.headers.get("authorization") ?? "")) return error(401, "missing_api_key", "Missing API key in the authorization header");
|
|
623
|
+
let body;
|
|
624
|
+
try {
|
|
625
|
+
const parsed = await request.json();
|
|
626
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
|
|
627
|
+
body = parsed;
|
|
628
|
+
} catch {
|
|
629
|
+
return error(422, "validation_error", "The body is not a JSON object");
|
|
630
|
+
}
|
|
631
|
+
const to = list(body.to), cc = list(body.cc), bcc = list(body.bcc), replyTo = list(body.reply_to ?? body.replyTo);
|
|
632
|
+
if (typeof body.from !== "string" || !to?.length || !cc || !bcc || !replyTo || typeof body.subject !== "string" || !(body.html || body.text)) {
|
|
633
|
+
return error(422, "validation_error", "from, to, subject and html or text are required");
|
|
634
|
+
}
|
|
635
|
+
const strangers = [...to, ...cc, ...bcc, ...replyTo].filter((a) => !parseCanary(addressOf(a)));
|
|
636
|
+
if (strangers.length) return error(422, "validation_error", `not a canary address: tests send only to ${CANARY_DOMAIN}`);
|
|
637
|
+
const key = request.headers.get("idempotency-key");
|
|
638
|
+
const earlier = key ? await store.idFor(key) : null;
|
|
639
|
+
if (earlier) return json(200, { id: earlier });
|
|
640
|
+
if (options.quota !== void 0 && (await store.all()).length >= options.quota) {
|
|
641
|
+
return error(429, "daily_quota_exceeded", "You have reached your daily email sending quota.");
|
|
642
|
+
}
|
|
643
|
+
const email = {
|
|
644
|
+
id: crypto.randomUUID(),
|
|
645
|
+
from: body.from,
|
|
646
|
+
to: to.map(addressOf),
|
|
647
|
+
cc: cc.map(addressOf),
|
|
648
|
+
bcc: bcc.map(addressOf),
|
|
649
|
+
replyTo: replyTo.map(addressOf),
|
|
650
|
+
subject: body.subject,
|
|
651
|
+
html: typeof body.html === "string" ? body.html : null,
|
|
652
|
+
text: typeof body.text === "string" ? body.text : null,
|
|
653
|
+
createdAt: now().toISOString()
|
|
654
|
+
};
|
|
655
|
+
await store.save(email, key);
|
|
656
|
+
return json(200, { id: email.id });
|
|
657
|
+
}
|
|
658
|
+
return {
|
|
659
|
+
store,
|
|
660
|
+
async fetch(request) {
|
|
661
|
+
const url = new URL(request.url);
|
|
662
|
+
if (request.method === "POST" && url.pathname === "/emails") return send(request);
|
|
663
|
+
if (request.method === "GET" && url.pathname === "/messages") {
|
|
664
|
+
const runId = (url.searchParams.get("runId") ?? "").toLowerCase();
|
|
665
|
+
if (!/^[a-z0-9]{4,40}$/.test(runId)) return error(400, "validation_error", "runId is 4 to 40 lower-case letters and digits");
|
|
666
|
+
return json(200, { runId, messages: canaryRows(await store.all(), runId) });
|
|
667
|
+
}
|
|
668
|
+
const one = /^\/emails\/([^/]+)$/.exec(url.pathname);
|
|
669
|
+
if (request.method === "GET" && one) {
|
|
670
|
+
const email = await store.get(decodeURIComponent(one[1]));
|
|
671
|
+
if (!email) return error(404, "not_found", "Email not found");
|
|
672
|
+
return json(200, { object: "email", id: email.id, from: email.from, to: email.to, cc: email.cc, bcc: email.bcc, reply_to: email.replyTo, subject: email.subject, html: email.html, text: email.text, created_at: email.createdAt, last_event: "delivered" });
|
|
673
|
+
}
|
|
674
|
+
return error(404, "not_found", "The requested endpoint does not exist");
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
}
|
|
572
678
|
// Annotate the CommonJS export names for ESM import in node:
|
|
573
679
|
0 && (module.exports = {
|
|
574
680
|
BEACON_CODES,
|
|
@@ -590,7 +696,9 @@ function scrubSentryEvent(event) {
|
|
|
590
696
|
SyntheticRecipientError,
|
|
591
697
|
assertCanaryRecipient,
|
|
592
698
|
canaryAddress,
|
|
699
|
+
canaryRows,
|
|
593
700
|
canonicalString,
|
|
701
|
+
fakeResend,
|
|
594
702
|
generateRunId,
|
|
595
703
|
hostAndPath,
|
|
596
704
|
isCanaryRecipient,
|
|
@@ -598,7 +706,9 @@ function scrubSentryEvent(event) {
|
|
|
598
706
|
isTurnstileTestKey,
|
|
599
707
|
keysFromEnv,
|
|
600
708
|
memoryReplayGuard,
|
|
709
|
+
memoryStore,
|
|
601
710
|
normaliseHostname,
|
|
711
|
+
parseCanary,
|
|
602
712
|
resetRejectBeaconThrottle,
|
|
603
713
|
scrubHeaders,
|
|
604
714
|
scrubSentryEvent,
|
package/dist/index.d.cts
CHANGED
|
@@ -352,4 +352,73 @@ declare function scrubText(text: string): string;
|
|
|
352
352
|
*/
|
|
353
353
|
declare function scrubSentryEvent<T extends object>(event: T): T;
|
|
354
354
|
|
|
355
|
-
|
|
355
|
+
/**
|
|
356
|
+
* A stand-in for Resend, for a client's own test runs (synthetic standard, section O2: Doman-Digital
|
|
357
|
+
* services/checks/docs/synthetic-standard.md). On 22 November 2026 a booking suite sent about 16 real
|
|
358
|
+
* emails a run with the client's own key and used up its 100 a day: every customer confirmation after it
|
|
359
|
+
* would have failed. Pull request and deploy runs post here instead and send nothing.
|
|
360
|
+
*
|
|
361
|
+
* It answers where a suite looks, in the same shapes as the real services:
|
|
362
|
+
*
|
|
363
|
+
* - `POST /emails` as Resend does: a Bearer key, Resend's JSON body, an `Idempotency-Key` that is seen
|
|
364
|
+
* again answers with the first send's id. It refuses any recipient (to, cc, bcc, reply-to) that is not a
|
|
365
|
+
* canary address, as a receiver must (standard N3), so a test that types a real address fails here
|
|
366
|
+
* before it can mail anyone on the nightly run.
|
|
367
|
+
* - `GET /emails/<id>` as Resend does: the send with its body, so a suite can check the wording and links.
|
|
368
|
+
* - `GET /messages?runId=<run>` as DD Checks' canary read does (`/admin/canary/messages`): one row per
|
|
369
|
+
* kind (`s` staff, `u` submitter) with `copies` counting every arrival, so a suite reads the fake on a
|
|
370
|
+
* pull request run and the real canary on the nightly run with the same code. `authResults` is null:
|
|
371
|
+
* nothing was signed because nothing left the machine.
|
|
372
|
+
*
|
|
373
|
+
* `quota` makes it answer 429 `daily_quota_exceeded` after that many sends, so a site's allowance alert
|
|
374
|
+
* (standard O2.4) can be tested.
|
|
375
|
+
*
|
|
376
|
+
* Web Fetch only, like the rest of this package: `fetch(request)` runs in a Worker (a staging Worker can
|
|
377
|
+
* answer its own sends with it) or behind a few lines of node:http (README).
|
|
378
|
+
*/
|
|
379
|
+
interface FakeEmail {
|
|
380
|
+
id: string;
|
|
381
|
+
from: string;
|
|
382
|
+
to: string[];
|
|
383
|
+
cc: string[];
|
|
384
|
+
bcc: string[];
|
|
385
|
+
replyTo: string[];
|
|
386
|
+
subject: string;
|
|
387
|
+
html: string | null;
|
|
388
|
+
text: string | null;
|
|
389
|
+
createdAt: string;
|
|
390
|
+
}
|
|
391
|
+
interface CanaryRow {
|
|
392
|
+
kind: "s" | "u";
|
|
393
|
+
receivedAt: string;
|
|
394
|
+
subject: string;
|
|
395
|
+
sender: string;
|
|
396
|
+
authResults: null;
|
|
397
|
+
resendMessageId: string;
|
|
398
|
+
copies: number;
|
|
399
|
+
}
|
|
400
|
+
/** Where sends are kept. In memory by default; a Worker passes one backed by its own storage. */
|
|
401
|
+
interface FakeResendStore {
|
|
402
|
+
idFor(idempotencyKey: string): Promise<string | null>;
|
|
403
|
+
save(email: FakeEmail, idempotencyKey: string | null): Promise<void>;
|
|
404
|
+
get(id: string): Promise<FakeEmail | null>;
|
|
405
|
+
all(): Promise<FakeEmail[]>;
|
|
406
|
+
}
|
|
407
|
+
declare function memoryStore(): FakeResendStore;
|
|
408
|
+
interface FakeResendOptions {
|
|
409
|
+
store?: FakeResendStore;
|
|
410
|
+
/** Answer 429 daily_quota_exceeded once this many emails have been accepted. */
|
|
411
|
+
quota?: number;
|
|
412
|
+
now?: () => Date;
|
|
413
|
+
}
|
|
414
|
+
declare function parseCanary(address: string): {
|
|
415
|
+
kind: "s" | "u";
|
|
416
|
+
runId: string;
|
|
417
|
+
} | null;
|
|
418
|
+
declare function canaryRows(emails: FakeEmail[], runId: string): CanaryRow[];
|
|
419
|
+
declare function fakeResend(options?: FakeResendOptions): {
|
|
420
|
+
fetch(request: Request): Promise<Response>;
|
|
421
|
+
store: FakeResendStore;
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
export { BEACON_CODES, BEACON_PATH, type BeaconCode, type BeaconEvent, CANARY_DOMAIN, CANONICAL_PREFIX, type CanaryRow, type CanonicalParts, DEFAULT_ENDPOINT, DEFAULT_WINDOW_SECONDS, FORM_MODES, type FakeEmail, type FakeResendOptions, type FakeResendStore, 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, canaryRows, canonicalString, fakeResend, generateRunId, hostAndPath, isCanaryRecipient, isProductionHost, isTurnstileTestKey, keysFromEnv, memoryReplayGuard, memoryStore, normaliseHostname, parseCanary, resetRejectBeaconThrottle, scrubHeaders, scrubSentryEvent, scrubText, sendBeacon, sendPurgeReceipt, sign, syntheticReport, turnstileConfigCheck, upstashReplayGuard, verify, verifyRequest };
|
package/dist/index.d.ts
CHANGED
|
@@ -352,4 +352,73 @@ declare function scrubText(text: string): string;
|
|
|
352
352
|
*/
|
|
353
353
|
declare function scrubSentryEvent<T extends object>(event: T): T;
|
|
354
354
|
|
|
355
|
-
|
|
355
|
+
/**
|
|
356
|
+
* A stand-in for Resend, for a client's own test runs (synthetic standard, section O2: Doman-Digital
|
|
357
|
+
* services/checks/docs/synthetic-standard.md). On 22 November 2026 a booking suite sent about 16 real
|
|
358
|
+
* emails a run with the client's own key and used up its 100 a day: every customer confirmation after it
|
|
359
|
+
* would have failed. Pull request and deploy runs post here instead and send nothing.
|
|
360
|
+
*
|
|
361
|
+
* It answers where a suite looks, in the same shapes as the real services:
|
|
362
|
+
*
|
|
363
|
+
* - `POST /emails` as Resend does: a Bearer key, Resend's JSON body, an `Idempotency-Key` that is seen
|
|
364
|
+
* again answers with the first send's id. It refuses any recipient (to, cc, bcc, reply-to) that is not a
|
|
365
|
+
* canary address, as a receiver must (standard N3), so a test that types a real address fails here
|
|
366
|
+
* before it can mail anyone on the nightly run.
|
|
367
|
+
* - `GET /emails/<id>` as Resend does: the send with its body, so a suite can check the wording and links.
|
|
368
|
+
* - `GET /messages?runId=<run>` as DD Checks' canary read does (`/admin/canary/messages`): one row per
|
|
369
|
+
* kind (`s` staff, `u` submitter) with `copies` counting every arrival, so a suite reads the fake on a
|
|
370
|
+
* pull request run and the real canary on the nightly run with the same code. `authResults` is null:
|
|
371
|
+
* nothing was signed because nothing left the machine.
|
|
372
|
+
*
|
|
373
|
+
* `quota` makes it answer 429 `daily_quota_exceeded` after that many sends, so a site's allowance alert
|
|
374
|
+
* (standard O2.4) can be tested.
|
|
375
|
+
*
|
|
376
|
+
* Web Fetch only, like the rest of this package: `fetch(request)` runs in a Worker (a staging Worker can
|
|
377
|
+
* answer its own sends with it) or behind a few lines of node:http (README).
|
|
378
|
+
*/
|
|
379
|
+
interface FakeEmail {
|
|
380
|
+
id: string;
|
|
381
|
+
from: string;
|
|
382
|
+
to: string[];
|
|
383
|
+
cc: string[];
|
|
384
|
+
bcc: string[];
|
|
385
|
+
replyTo: string[];
|
|
386
|
+
subject: string;
|
|
387
|
+
html: string | null;
|
|
388
|
+
text: string | null;
|
|
389
|
+
createdAt: string;
|
|
390
|
+
}
|
|
391
|
+
interface CanaryRow {
|
|
392
|
+
kind: "s" | "u";
|
|
393
|
+
receivedAt: string;
|
|
394
|
+
subject: string;
|
|
395
|
+
sender: string;
|
|
396
|
+
authResults: null;
|
|
397
|
+
resendMessageId: string;
|
|
398
|
+
copies: number;
|
|
399
|
+
}
|
|
400
|
+
/** Where sends are kept. In memory by default; a Worker passes one backed by its own storage. */
|
|
401
|
+
interface FakeResendStore {
|
|
402
|
+
idFor(idempotencyKey: string): Promise<string | null>;
|
|
403
|
+
save(email: FakeEmail, idempotencyKey: string | null): Promise<void>;
|
|
404
|
+
get(id: string): Promise<FakeEmail | null>;
|
|
405
|
+
all(): Promise<FakeEmail[]>;
|
|
406
|
+
}
|
|
407
|
+
declare function memoryStore(): FakeResendStore;
|
|
408
|
+
interface FakeResendOptions {
|
|
409
|
+
store?: FakeResendStore;
|
|
410
|
+
/** Answer 429 daily_quota_exceeded once this many emails have been accepted. */
|
|
411
|
+
quota?: number;
|
|
412
|
+
now?: () => Date;
|
|
413
|
+
}
|
|
414
|
+
declare function parseCanary(address: string): {
|
|
415
|
+
kind: "s" | "u";
|
|
416
|
+
runId: string;
|
|
417
|
+
} | null;
|
|
418
|
+
declare function canaryRows(emails: FakeEmail[], runId: string): CanaryRow[];
|
|
419
|
+
declare function fakeResend(options?: FakeResendOptions): {
|
|
420
|
+
fetch(request: Request): Promise<Response>;
|
|
421
|
+
store: FakeResendStore;
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
export { BEACON_CODES, BEACON_PATH, type BeaconCode, type BeaconEvent, CANARY_DOMAIN, CANONICAL_PREFIX, type CanaryRow, type CanonicalParts, DEFAULT_ENDPOINT, DEFAULT_WINDOW_SECONDS, FORM_MODES, type FakeEmail, type FakeResendOptions, type FakeResendStore, 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, canaryRows, canonicalString, fakeResend, generateRunId, hostAndPath, isCanaryRecipient, isProductionHost, isTurnstileTestKey, keysFromEnv, memoryReplayGuard, memoryStore, normaliseHostname, parseCanary, resetRejectBeaconThrottle, scrubHeaders, scrubSentryEvent, scrubText, sendBeacon, sendPurgeReceipt, sign, syntheticReport, turnstileConfigCheck, upstashReplayGuard, verify, verifyRequest };
|
package/dist/index.js
CHANGED
|
@@ -504,6 +504,108 @@ function scrubSentryEvent(event) {
|
|
|
504
504
|
return copy;
|
|
505
505
|
}
|
|
506
506
|
}
|
|
507
|
+
|
|
508
|
+
// src/fake-resend.ts
|
|
509
|
+
function memoryStore() {
|
|
510
|
+
const emails = /* @__PURE__ */ new Map();
|
|
511
|
+
const keys = /* @__PURE__ */ new Map();
|
|
512
|
+
return {
|
|
513
|
+
idFor: async (key) => keys.get(key) ?? null,
|
|
514
|
+
save: async (email, key) => {
|
|
515
|
+
emails.set(email.id, email);
|
|
516
|
+
if (key) keys.set(key, email.id);
|
|
517
|
+
},
|
|
518
|
+
get: async (id) => emails.get(id) ?? null,
|
|
519
|
+
all: async () => [...emails.values()]
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
var CANARY = new RegExp(`^([su])-([a-z0-9]{4,40})@${CANARY_DOMAIN.replace(/\./g, "\\.")}$`);
|
|
523
|
+
function parseCanary(address) {
|
|
524
|
+
const m = CANARY.exec(address.trim().toLowerCase());
|
|
525
|
+
return m ? { kind: m[1], runId: m[2] } : null;
|
|
526
|
+
}
|
|
527
|
+
var list = (value) => {
|
|
528
|
+
if (value === void 0 || value === null) return [];
|
|
529
|
+
const items = Array.isArray(value) ? value : [value];
|
|
530
|
+
return items.every((v) => typeof v === "string") ? items : null;
|
|
531
|
+
};
|
|
532
|
+
var addressOf = (value) => /<([^>]+)>\s*$/.exec(value)?.[1] ?? value;
|
|
533
|
+
function canaryRows(emails, runId) {
|
|
534
|
+
const run = runId.toLowerCase();
|
|
535
|
+
const rows = /* @__PURE__ */ new Map();
|
|
536
|
+
for (const email of emails) {
|
|
537
|
+
for (const address of [...email.to, ...email.cc, ...email.bcc]) {
|
|
538
|
+
const canary = parseCanary(address);
|
|
539
|
+
if (!canary || canary.runId !== run) continue;
|
|
540
|
+
const row = rows.get(canary.kind);
|
|
541
|
+
if (row) row.copies += 1;
|
|
542
|
+
else rows.set(canary.kind, { kind: canary.kind, receivedAt: email.createdAt, subject: email.subject, sender: email.from, authResults: null, resendMessageId: email.id, copies: 1 });
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return [...rows.values()];
|
|
546
|
+
}
|
|
547
|
+
function fakeResend(options = {}) {
|
|
548
|
+
const store = options.store ?? memoryStore();
|
|
549
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
550
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
|
|
551
|
+
const error = (status, name, message) => json(status, { statusCode: status, name, message });
|
|
552
|
+
async function send(request) {
|
|
553
|
+
if (!/^Bearer \S+$/.test(request.headers.get("authorization") ?? "")) return error(401, "missing_api_key", "Missing API key in the authorization header");
|
|
554
|
+
let body;
|
|
555
|
+
try {
|
|
556
|
+
const parsed = await request.json();
|
|
557
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
|
|
558
|
+
body = parsed;
|
|
559
|
+
} catch {
|
|
560
|
+
return error(422, "validation_error", "The body is not a JSON object");
|
|
561
|
+
}
|
|
562
|
+
const to = list(body.to), cc = list(body.cc), bcc = list(body.bcc), replyTo = list(body.reply_to ?? body.replyTo);
|
|
563
|
+
if (typeof body.from !== "string" || !to?.length || !cc || !bcc || !replyTo || typeof body.subject !== "string" || !(body.html || body.text)) {
|
|
564
|
+
return error(422, "validation_error", "from, to, subject and html or text are required");
|
|
565
|
+
}
|
|
566
|
+
const strangers = [...to, ...cc, ...bcc, ...replyTo].filter((a) => !parseCanary(addressOf(a)));
|
|
567
|
+
if (strangers.length) return error(422, "validation_error", `not a canary address: tests send only to ${CANARY_DOMAIN}`);
|
|
568
|
+
const key = request.headers.get("idempotency-key");
|
|
569
|
+
const earlier = key ? await store.idFor(key) : null;
|
|
570
|
+
if (earlier) return json(200, { id: earlier });
|
|
571
|
+
if (options.quota !== void 0 && (await store.all()).length >= options.quota) {
|
|
572
|
+
return error(429, "daily_quota_exceeded", "You have reached your daily email sending quota.");
|
|
573
|
+
}
|
|
574
|
+
const email = {
|
|
575
|
+
id: crypto.randomUUID(),
|
|
576
|
+
from: body.from,
|
|
577
|
+
to: to.map(addressOf),
|
|
578
|
+
cc: cc.map(addressOf),
|
|
579
|
+
bcc: bcc.map(addressOf),
|
|
580
|
+
replyTo: replyTo.map(addressOf),
|
|
581
|
+
subject: body.subject,
|
|
582
|
+
html: typeof body.html === "string" ? body.html : null,
|
|
583
|
+
text: typeof body.text === "string" ? body.text : null,
|
|
584
|
+
createdAt: now().toISOString()
|
|
585
|
+
};
|
|
586
|
+
await store.save(email, key);
|
|
587
|
+
return json(200, { id: email.id });
|
|
588
|
+
}
|
|
589
|
+
return {
|
|
590
|
+
store,
|
|
591
|
+
async fetch(request) {
|
|
592
|
+
const url = new URL(request.url);
|
|
593
|
+
if (request.method === "POST" && url.pathname === "/emails") return send(request);
|
|
594
|
+
if (request.method === "GET" && url.pathname === "/messages") {
|
|
595
|
+
const runId = (url.searchParams.get("runId") ?? "").toLowerCase();
|
|
596
|
+
if (!/^[a-z0-9]{4,40}$/.test(runId)) return error(400, "validation_error", "runId is 4 to 40 lower-case letters and digits");
|
|
597
|
+
return json(200, { runId, messages: canaryRows(await store.all(), runId) });
|
|
598
|
+
}
|
|
599
|
+
const one = /^\/emails\/([^/]+)$/.exec(url.pathname);
|
|
600
|
+
if (request.method === "GET" && one) {
|
|
601
|
+
const email = await store.get(decodeURIComponent(one[1]));
|
|
602
|
+
if (!email) return error(404, "not_found", "Email not found");
|
|
603
|
+
return json(200, { object: "email", id: email.id, from: email.from, to: email.to, cc: email.cc, bcc: email.bcc, reply_to: email.replyTo, subject: email.subject, html: email.html, text: email.text, created_at: email.createdAt, last_event: "delivered" });
|
|
604
|
+
}
|
|
605
|
+
return error(404, "not_found", "The requested endpoint does not exist");
|
|
606
|
+
}
|
|
607
|
+
};
|
|
608
|
+
}
|
|
507
609
|
export {
|
|
508
610
|
BEACON_CODES,
|
|
509
611
|
BEACON_PATH,
|
|
@@ -524,7 +626,9 @@ export {
|
|
|
524
626
|
SyntheticRecipientError,
|
|
525
627
|
assertCanaryRecipient,
|
|
526
628
|
canaryAddress,
|
|
629
|
+
canaryRows,
|
|
527
630
|
canonicalString,
|
|
631
|
+
fakeResend,
|
|
528
632
|
generateRunId,
|
|
529
633
|
hostAndPath,
|
|
530
634
|
isCanaryRecipient,
|
|
@@ -532,7 +636,9 @@ export {
|
|
|
532
636
|
isTurnstileTestKey,
|
|
533
637
|
keysFromEnv,
|
|
534
638
|
memoryReplayGuard,
|
|
639
|
+
memoryStore,
|
|
535
640
|
normaliseHostname,
|
|
641
|
+
parseCanary,
|
|
536
642
|
resetRejectBeaconThrottle,
|
|
537
643
|
scrubHeaders,
|
|
538
644
|
scrubSentryEvent,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@domandigital/synthetic",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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",
|