@domandigital/synthetic 0.0.0-stage → 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 +13 -0
- package/LICENSE +202 -0
- package/README.md +179 -2
- package/dist/index.cjs +614 -0
- package/dist/index.d.cts +355 -0
- package/dist/index.d.ts +355 -0
- package/dist/index.js +548 -0
- package/package.json +58 -3
- package/test-vectors.json +57 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
BEACON_CODES: () => BEACON_CODES,
|
|
24
|
+
BEACON_PATH: () => BEACON_PATH,
|
|
25
|
+
CANARY_DOMAIN: () => CANARY_DOMAIN,
|
|
26
|
+
CANONICAL_PREFIX: () => CANONICAL_PREFIX,
|
|
27
|
+
DEFAULT_ENDPOINT: () => DEFAULT_ENDPOINT,
|
|
28
|
+
DEFAULT_WINDOW_SECONDS: () => DEFAULT_WINDOW_SECONDS,
|
|
29
|
+
FORM_MODES: () => FORM_MODES,
|
|
30
|
+
HEADER: () => HEADER,
|
|
31
|
+
ID_PATTERN: () => ID_PATTERN,
|
|
32
|
+
MODES: () => MODES,
|
|
33
|
+
PROTOCOL_VERSION: () => PROTOCOL_VERSION,
|
|
34
|
+
RECEIPT_PATH: () => RECEIPT_PATH,
|
|
35
|
+
REDACTED: () => REDACTED,
|
|
36
|
+
REJECT_REASONS: () => REJECT_REASONS,
|
|
37
|
+
RUN_ID_PATTERN: () => RUN_ID_PATTERN,
|
|
38
|
+
SITEVERIFY_URL: () => SITEVERIFY_URL,
|
|
39
|
+
SyntheticRecipientError: () => SyntheticRecipientError,
|
|
40
|
+
assertCanaryRecipient: () => assertCanaryRecipient,
|
|
41
|
+
canaryAddress: () => canaryAddress,
|
|
42
|
+
canonicalString: () => canonicalString,
|
|
43
|
+
generateRunId: () => generateRunId,
|
|
44
|
+
hostAndPath: () => hostAndPath,
|
|
45
|
+
isCanaryRecipient: () => isCanaryRecipient,
|
|
46
|
+
isProductionHost: () => isProductionHost,
|
|
47
|
+
isTurnstileTestKey: () => isTurnstileTestKey,
|
|
48
|
+
keysFromEnv: () => keysFromEnv,
|
|
49
|
+
memoryReplayGuard: () => memoryReplayGuard,
|
|
50
|
+
normaliseHostname: () => normaliseHostname,
|
|
51
|
+
resetRejectBeaconThrottle: () => resetRejectBeaconThrottle,
|
|
52
|
+
scrubHeaders: () => scrubHeaders,
|
|
53
|
+
scrubSentryEvent: () => scrubSentryEvent,
|
|
54
|
+
scrubText: () => scrubText,
|
|
55
|
+
sendBeacon: () => sendBeacon,
|
|
56
|
+
sendPurgeReceipt: () => sendPurgeReceipt,
|
|
57
|
+
sign: () => sign,
|
|
58
|
+
syntheticReport: () => syntheticReport,
|
|
59
|
+
turnstileConfigCheck: () => turnstileConfigCheck,
|
|
60
|
+
upstashReplayGuard: () => upstashReplayGuard,
|
|
61
|
+
verify: () => verify,
|
|
62
|
+
verifyRequest: () => verifyRequest
|
|
63
|
+
});
|
|
64
|
+
module.exports = __toCommonJS(index_exports);
|
|
65
|
+
|
|
66
|
+
// src/encoding.ts
|
|
67
|
+
var encoder = new TextEncoder();
|
|
68
|
+
function utf8(text) {
|
|
69
|
+
return encoder.encode(text);
|
|
70
|
+
}
|
|
71
|
+
function toHex(bytes) {
|
|
72
|
+
let out = "";
|
|
73
|
+
for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
function fromHex(hex) {
|
|
77
|
+
if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/.test(hex)) return null;
|
|
78
|
+
const out = new Uint8Array(hex.length / 2);
|
|
79
|
+
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
function fromBase64Url(text) {
|
|
83
|
+
if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
|
|
84
|
+
const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
|
|
85
|
+
try {
|
|
86
|
+
const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
|
|
87
|
+
const out = new Uint8Array(binary.length);
|
|
88
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
89
|
+
return out;
|
|
90
|
+
} catch {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function sha256Hex(body) {
|
|
95
|
+
const bytes = typeof body === "string" ? utf8(body) : body;
|
|
96
|
+
return toHex(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)));
|
|
97
|
+
}
|
|
98
|
+
async function importHmacKey(secret) {
|
|
99
|
+
return crypto.subtle.importKey("raw", secret, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
100
|
+
}
|
|
101
|
+
async function hmacSha256(key, message) {
|
|
102
|
+
return new Uint8Array(await crypto.subtle.sign("HMAC", key, utf8(message)));
|
|
103
|
+
}
|
|
104
|
+
function constantTimeEqual(a, b) {
|
|
105
|
+
if (a.length !== b.length) return false;
|
|
106
|
+
let diff = 0;
|
|
107
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
108
|
+
return diff === 0;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/protocol.ts
|
|
112
|
+
var PROTOCOL_VERSION = "v1";
|
|
113
|
+
var CANONICAL_PREFIX = "DD-SYNTH-V1";
|
|
114
|
+
var HEADER = {
|
|
115
|
+
version: "X-DD-Synth",
|
|
116
|
+
kid: "X-DD-Synth-Kid",
|
|
117
|
+
ts: "X-DD-Synth-Ts",
|
|
118
|
+
run: "X-DD-Synth-Run",
|
|
119
|
+
mode: "X-DD-Synth-Mode",
|
|
120
|
+
client: "X-DD-Synth-Client",
|
|
121
|
+
form: "X-DD-Synth-Form",
|
|
122
|
+
sig: "X-DD-Synth-Sig"
|
|
123
|
+
};
|
|
124
|
+
var MODES = ["probe", "full", "beacon", "receipt"];
|
|
125
|
+
var FORM_MODES = ["probe", "full"];
|
|
126
|
+
var ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
127
|
+
var RUN_ID_PATTERN = /^[a-z2-7]{16}$/;
|
|
128
|
+
var SECRET_BYTES = 32;
|
|
129
|
+
var RUN_ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
|
|
130
|
+
function generateRunId() {
|
|
131
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
132
|
+
let out = "";
|
|
133
|
+
for (const byte of bytes) out += RUN_ID_ALPHABET[byte % 32];
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
function canonicalString(p) {
|
|
137
|
+
return [
|
|
138
|
+
CANONICAL_PREFIX,
|
|
139
|
+
p.kid,
|
|
140
|
+
String(p.ts),
|
|
141
|
+
p.runId,
|
|
142
|
+
p.mode,
|
|
143
|
+
p.client,
|
|
144
|
+
p.form,
|
|
145
|
+
"POST",
|
|
146
|
+
p.host,
|
|
147
|
+
p.path,
|
|
148
|
+
p.contentType,
|
|
149
|
+
p.bodySha256
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
|
152
|
+
function decodeSecret(secret) {
|
|
153
|
+
const bytes = fromBase64Url(secret);
|
|
154
|
+
return bytes && bytes.length === SECRET_BYTES ? bytes : null;
|
|
155
|
+
}
|
|
156
|
+
async function computeSignature(secret, parts) {
|
|
157
|
+
return hmacSha256(await importHmacKey(secret), canonicalString(parts));
|
|
158
|
+
}
|
|
159
|
+
function hostAndPath(url) {
|
|
160
|
+
const u = typeof url === "string" ? new URL(url) : url;
|
|
161
|
+
return { host: u.host.toLowerCase(), path: u.pathname };
|
|
162
|
+
}
|
|
163
|
+
async function sign(options) {
|
|
164
|
+
const { key, client, form, mode, contentType } = options;
|
|
165
|
+
const runId = options.runId ?? generateRunId();
|
|
166
|
+
const ts = Math.floor(options.now ?? Date.now() / 1e3);
|
|
167
|
+
if (!ID_PATTERN.test(key.kid)) throw new Error("synthetic: invalid kid");
|
|
168
|
+
if (!ID_PATTERN.test(client)) throw new Error("synthetic: invalid client");
|
|
169
|
+
if (!ID_PATTERN.test(form)) throw new Error("synthetic: invalid form");
|
|
170
|
+
if (!RUN_ID_PATTERN.test(runId)) throw new Error("synthetic: invalid run id");
|
|
171
|
+
if (!MODES.includes(mode)) throw new Error("synthetic: invalid mode");
|
|
172
|
+
if (!contentType || /[\r\n]/.test(contentType)) throw new Error("synthetic: invalid content type");
|
|
173
|
+
const secret = decodeSecret(key.secret);
|
|
174
|
+
if (!secret) throw new Error("synthetic: secret must be 32 bytes of base64url");
|
|
175
|
+
const bytes = typeof options.body === "string" ? utf8(options.body) : options.body;
|
|
176
|
+
const { host, path } = hostAndPath(options.url);
|
|
177
|
+
const signature = await computeSignature(secret, {
|
|
178
|
+
kid: key.kid,
|
|
179
|
+
ts,
|
|
180
|
+
runId,
|
|
181
|
+
mode,
|
|
182
|
+
client,
|
|
183
|
+
form,
|
|
184
|
+
host,
|
|
185
|
+
path,
|
|
186
|
+
contentType,
|
|
187
|
+
bodySha256: await sha256Hex(bytes)
|
|
188
|
+
});
|
|
189
|
+
return {
|
|
190
|
+
runId,
|
|
191
|
+
ts,
|
|
192
|
+
headers: {
|
|
193
|
+
[HEADER.version]: PROTOCOL_VERSION,
|
|
194
|
+
[HEADER.kid]: key.kid,
|
|
195
|
+
[HEADER.ts]: String(ts),
|
|
196
|
+
[HEADER.run]: runId,
|
|
197
|
+
[HEADER.mode]: mode,
|
|
198
|
+
[HEADER.client]: client,
|
|
199
|
+
[HEADER.form]: form,
|
|
200
|
+
[HEADER.sig]: `v1=${toHex(signature)}`
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function keysFromEnv(env) {
|
|
205
|
+
const keys = [];
|
|
206
|
+
if (env.DD_SYNTHETIC_SECRET && env.DD_SYNTHETIC_KID) {
|
|
207
|
+
keys.push({ kid: env.DD_SYNTHETIC_KID, secret: env.DD_SYNTHETIC_SECRET });
|
|
208
|
+
}
|
|
209
|
+
if (env.DD_SYNTHETIC_SECRET && env.DD_SYNTHETIC_SECRET_NEXT && env.DD_SYNTHETIC_KID_NEXT) {
|
|
210
|
+
keys.push({ kid: env.DD_SYNTHETIC_KID_NEXT, secret: env.DD_SYNTHETIC_SECRET_NEXT });
|
|
211
|
+
}
|
|
212
|
+
return keys;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// src/verify.ts
|
|
216
|
+
var DEFAULT_WINDOW_SECONDS = 120;
|
|
217
|
+
var DEFAULT_MAX_BODY_BYTES = 1048576;
|
|
218
|
+
var REJECT_REASONS = [
|
|
219
|
+
"unsupported_version",
|
|
220
|
+
"shape",
|
|
221
|
+
"malformed",
|
|
222
|
+
"mode",
|
|
223
|
+
"unknown_kid",
|
|
224
|
+
"stale",
|
|
225
|
+
"bad_signature",
|
|
226
|
+
"replay",
|
|
227
|
+
"replay_guard_unavailable"
|
|
228
|
+
];
|
|
229
|
+
var ordinary = (reason) => ({ ok: false, rejected: false, reason });
|
|
230
|
+
function reject(reason, h) {
|
|
231
|
+
const claimed = {};
|
|
232
|
+
const client = h?.get(HEADER.client);
|
|
233
|
+
const form = h?.get(HEADER.form);
|
|
234
|
+
if (client && ID_PATTERN.test(client)) claimed.client = client;
|
|
235
|
+
if (form && ID_PATTERN.test(form)) claimed.form = form;
|
|
236
|
+
return { ok: false, rejected: true, reason, claimed };
|
|
237
|
+
}
|
|
238
|
+
var mediaType = (contentType) => contentType.split(";")[0].trim().toLowerCase();
|
|
239
|
+
async function verify(input, config) {
|
|
240
|
+
try {
|
|
241
|
+
return await verifyInner(input, config);
|
|
242
|
+
} catch {
|
|
243
|
+
return reject("malformed", input.headers);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async function verifyInner(input, config) {
|
|
247
|
+
const h = input.headers;
|
|
248
|
+
const claim = h.get(HEADER.version);
|
|
249
|
+
if (claim === null) return ordinary("not_synthetic");
|
|
250
|
+
if (config.keys.length === 0) return ordinary("disabled");
|
|
251
|
+
if (claim !== PROTOCOL_VERSION) return reject("unsupported_version", h);
|
|
252
|
+
const contentType = h.get("content-type");
|
|
253
|
+
const { host, path } = hostAndPath(input.url);
|
|
254
|
+
const paths = typeof config.path === "string" ? [config.path] : config.path;
|
|
255
|
+
if (input.method.toUpperCase() !== "POST" || host !== config.host.toLowerCase() || !paths.includes(path) || contentType === null || !config.contentTypes.map((t) => t.toLowerCase()).includes(mediaType(contentType))) {
|
|
256
|
+
return reject("shape", h);
|
|
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
|
+
}
|
|
262
|
+
const kid = h.get(HEADER.kid);
|
|
263
|
+
const tsText = h.get(HEADER.ts);
|
|
264
|
+
const runId = h.get(HEADER.run);
|
|
265
|
+
const mode = h.get(HEADER.mode);
|
|
266
|
+
const client = h.get(HEADER.client);
|
|
267
|
+
const form = h.get(HEADER.form);
|
|
268
|
+
const sig = h.get(HEADER.sig);
|
|
269
|
+
if (!kid || !ID_PATTERN.test(kid) || !tsText || !/^\d{1,12}$/.test(tsText) || !runId || !RUN_ID_PATTERN.test(runId) || !mode || !client || !ID_PATTERN.test(client) || !form || !ID_PATTERN.test(form) || !sig || !/^v1=[0-9a-f]{64}$/.test(sig)) {
|
|
270
|
+
return reject("malformed", h);
|
|
271
|
+
}
|
|
272
|
+
if (!(config.modes ?? FORM_MODES).includes(mode)) return reject("mode", h);
|
|
273
|
+
const key = config.keys.find((k) => k.kid === kid);
|
|
274
|
+
if (!key) return reject("unknown_kid", h);
|
|
275
|
+
const ts = Number(tsText);
|
|
276
|
+
const now = Math.floor(config.now ?? Date.now() / 1e3);
|
|
277
|
+
if (Math.abs(now - ts) > (config.windowSeconds ?? DEFAULT_WINDOW_SECONDS)) return reject("stale", h);
|
|
278
|
+
const secret = decodeSecret(key.secret);
|
|
279
|
+
if (!secret) return reject("bad_signature", h);
|
|
280
|
+
const body = typeof input.body === "string" ? utf8(input.body) : input.body;
|
|
281
|
+
const expected = await computeSignature(secret, {
|
|
282
|
+
kid,
|
|
283
|
+
ts,
|
|
284
|
+
runId,
|
|
285
|
+
mode,
|
|
286
|
+
client,
|
|
287
|
+
form,
|
|
288
|
+
host,
|
|
289
|
+
path,
|
|
290
|
+
contentType,
|
|
291
|
+
bodySha256: await sha256Hex(body)
|
|
292
|
+
});
|
|
293
|
+
const given = fromHex(sig.slice(3));
|
|
294
|
+
const pinned = (config.client === void 0 || config.client === client) && (config.form === void 0 || config.form === form);
|
|
295
|
+
const signatureOk = given !== null && constantTimeEqual(expected, given);
|
|
296
|
+
if (!signatureOk || !pinned) return reject("bad_signature", h);
|
|
297
|
+
let first;
|
|
298
|
+
try {
|
|
299
|
+
first = await config.replayGuard(runId);
|
|
300
|
+
} catch {
|
|
301
|
+
return reject("replay_guard_unavailable", h);
|
|
302
|
+
}
|
|
303
|
+
if (!first) return reject("replay", h);
|
|
304
|
+
const synthetic = Object.freeze({
|
|
305
|
+
v: 1,
|
|
306
|
+
runId,
|
|
307
|
+
mode,
|
|
308
|
+
client,
|
|
309
|
+
form,
|
|
310
|
+
kid
|
|
311
|
+
});
|
|
312
|
+
return { ok: true, synthetic };
|
|
313
|
+
}
|
|
314
|
+
async function verifyRequest(request, config) {
|
|
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);
|
|
319
|
+
let body;
|
|
320
|
+
try {
|
|
321
|
+
const read = await readCapped(request.clone(), maxBody);
|
|
322
|
+
if (read === null) return reject("shape", request.headers);
|
|
323
|
+
body = read;
|
|
324
|
+
} catch {
|
|
325
|
+
return reject("malformed", request.headers);
|
|
326
|
+
}
|
|
327
|
+
return verify({ method: request.method, url: request.url, headers: request.headers, body }, config);
|
|
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
|
+
}
|
|
352
|
+
function syntheticReport(ctx, stages) {
|
|
353
|
+
return { v: ctx.v, runId: ctx.runId, stages };
|
|
354
|
+
}
|
|
355
|
+
function memoryReplayGuard() {
|
|
356
|
+
const seen = /* @__PURE__ */ new Set();
|
|
357
|
+
return (runId) => {
|
|
358
|
+
if (seen.has(runId)) return false;
|
|
359
|
+
seen.add(runId);
|
|
360
|
+
return true;
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
function upstashReplayGuard(options) {
|
|
364
|
+
const doFetch = options.fetch ?? fetch;
|
|
365
|
+
return async (runId) => {
|
|
366
|
+
const res = await doFetch(options.url.replace(/\/+$/, ""), {
|
|
367
|
+
method: "POST",
|
|
368
|
+
headers: { Authorization: `Bearer ${options.token}`, "Content-Type": "application/json" },
|
|
369
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 2e3),
|
|
370
|
+
body: JSON.stringify(["SET", `synth:${runId}`, "1", "NX", "EX", String(options.ttlSeconds ?? 300)])
|
|
371
|
+
});
|
|
372
|
+
if (!res.ok) throw new Error(`upstash ${res.status}`);
|
|
373
|
+
const json = await res.json();
|
|
374
|
+
return json.result === "OK";
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// src/canary.ts
|
|
379
|
+
var CANARY_DOMAIN = "canary.domandigital.co.uk";
|
|
380
|
+
function isCanaryRecipient(email) {
|
|
381
|
+
if (typeof email !== "string" || email.length > 254) return false;
|
|
382
|
+
const match = /^([A-Za-z0-9][A-Za-z0-9._+-]{0,63})@([A-Za-z0-9.-]+)$/.exec(email);
|
|
383
|
+
return match !== null && match[2].toLowerCase() === CANARY_DOMAIN;
|
|
384
|
+
}
|
|
385
|
+
function assertCanaryRecipient(...emails) {
|
|
386
|
+
for (const email of emails) {
|
|
387
|
+
if (!isCanaryRecipient(email)) throw new SyntheticRecipientError();
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
var SyntheticRecipientError = class extends Error {
|
|
391
|
+
constructor() {
|
|
392
|
+
super("synthetic: recipient is not at the canary domain");
|
|
393
|
+
this.name = "SyntheticRecipientError";
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
function canaryAddress(kind, runId) {
|
|
397
|
+
if (!RUN_ID_PATTERN.test(runId)) throw new Error("synthetic: invalid run id");
|
|
398
|
+
return `${kind}-${runId}@${CANARY_DOMAIN}`;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// src/turnstile.ts
|
|
402
|
+
var SITEVERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
|
403
|
+
function isTurnstileTestKey(key) {
|
|
404
|
+
return /^[123]x0{10,}[0-9A-Za-z]*$/.test(key);
|
|
405
|
+
}
|
|
406
|
+
function normaliseHostname(value) {
|
|
407
|
+
return value.trim().toLowerCase().replace(/^[a-z][a-z0-9+.-]*:\/\//, "").replace(/[/?#].*$/, "").replace(/:\d+$/, "").replace(/\.+$/, "");
|
|
408
|
+
}
|
|
409
|
+
function isProductionHost(host) {
|
|
410
|
+
const h = normaliseHostname(host);
|
|
411
|
+
if (h === "localhost" || /^\d{1,3}(\.\d{1,3}){3}$/.test(h)) return false;
|
|
412
|
+
if (h.startsWith("staging.") || h.startsWith("preview.") || h.startsWith("dev.")) return false;
|
|
413
|
+
return !/\.(local|test|localhost|invalid|workers\.dev|pages\.dev|vercel\.app)$/.test(h);
|
|
414
|
+
}
|
|
415
|
+
async function turnstileConfigCheck(options) {
|
|
416
|
+
const { siteKey, secretKey, expectedHostname, publicHost } = options;
|
|
417
|
+
if (!siteKey || !secretKey || !expectedHostname) return { ok: false, outcome: "missing_keys" };
|
|
418
|
+
if (normaliseHostname(expectedHostname) !== normaliseHostname(publicHost)) {
|
|
419
|
+
return { ok: false, outcome: "hostname_mismatch" };
|
|
420
|
+
}
|
|
421
|
+
const production = options.production ?? isProductionHost(publicHost);
|
|
422
|
+
if (production && (isTurnstileTestKey(siteKey) || isTurnstileTestKey(secretKey))) {
|
|
423
|
+
return { ok: false, outcome: "test_key_on_production" };
|
|
424
|
+
}
|
|
425
|
+
let json;
|
|
426
|
+
try {
|
|
427
|
+
const res = await (options.fetch ?? fetch)(SITEVERIFY_URL, {
|
|
428
|
+
method: "POST",
|
|
429
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
430
|
+
body: new URLSearchParams({ secret: secretKey, response: "dd-synthetic-config-check" }).toString(),
|
|
431
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 5e3)
|
|
432
|
+
});
|
|
433
|
+
json = await res.json();
|
|
434
|
+
} catch {
|
|
435
|
+
return { ok: false, outcome: "siteverify_unreachable" };
|
|
436
|
+
}
|
|
437
|
+
const errorCodes = Array.isArray(json["error-codes"]) ? json["error-codes"].filter((c) => typeof c === "string") : [];
|
|
438
|
+
if (errorCodes.includes("invalid-input-secret")) {
|
|
439
|
+
return { ok: false, outcome: "invalid-input-secret", errorCodes };
|
|
440
|
+
}
|
|
441
|
+
if (errorCodes.includes("invalid-input-response") && json.success !== true) return { ok: true, outcome: "ok", errorCodes };
|
|
442
|
+
if (!production && json.success === true) return { ok: true, outcome: "ok", errorCodes };
|
|
443
|
+
return { ok: false, outcome: "siteverify_unexpected", errorCodes };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// src/beacon.ts
|
|
447
|
+
var DEFAULT_ENDPOINT = "https://checks.domandigital.co.uk";
|
|
448
|
+
var BEACON_PATH = "/beacon";
|
|
449
|
+
var RECEIPT_PATH = "/purge-receipt";
|
|
450
|
+
var BEACON_CODES = [
|
|
451
|
+
"accepted",
|
|
452
|
+
"hostname_mismatch",
|
|
453
|
+
"invalid-input-secret",
|
|
454
|
+
"misconfigured",
|
|
455
|
+
"service_unavailable",
|
|
456
|
+
"delivery_failed",
|
|
457
|
+
"captcha_failed",
|
|
458
|
+
"synthetic_rejected"
|
|
459
|
+
];
|
|
460
|
+
async function post(options, path, mode, form, payload) {
|
|
461
|
+
const body = JSON.stringify(payload);
|
|
462
|
+
const url = `${(options.endpoint ?? DEFAULT_ENDPOINT).replace(/\/+$/, "")}${path}`;
|
|
463
|
+
const contentType = "application/json";
|
|
464
|
+
const signed = await sign({ key: options.key, url, contentType, body, client: options.client, form, mode, now: options.now });
|
|
465
|
+
await (options.fetch ?? fetch)(url, {
|
|
466
|
+
method: "POST",
|
|
467
|
+
headers: { "Content-Type": contentType, ...signed.headers },
|
|
468
|
+
body,
|
|
469
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 3e3)
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
function fireAndForget(options, run) {
|
|
473
|
+
let promise;
|
|
474
|
+
try {
|
|
475
|
+
promise = run().catch(() => void 0);
|
|
476
|
+
} catch {
|
|
477
|
+
promise = Promise.resolve();
|
|
478
|
+
}
|
|
479
|
+
try {
|
|
480
|
+
options.waitUntil?.(promise);
|
|
481
|
+
} catch {
|
|
482
|
+
}
|
|
483
|
+
return promise;
|
|
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
|
+
}
|
|
498
|
+
function sendBeacon(options, event) {
|
|
499
|
+
return fireAndForget(options, async () => {
|
|
500
|
+
if (!BEACON_CODES.includes(event.code) || !ID_PATTERN.test(event.form)) return;
|
|
501
|
+
const payload = {
|
|
502
|
+
v: 1,
|
|
503
|
+
client: options.client,
|
|
504
|
+
form: event.form,
|
|
505
|
+
code: event.code,
|
|
506
|
+
ts: Math.floor(options.now ?? Date.now() / 1e3)
|
|
507
|
+
};
|
|
508
|
+
if (event.code === "synthetic_rejected") {
|
|
509
|
+
if (!event.reason || !REJECT_REASONS.includes(event.reason)) return;
|
|
510
|
+
payload.reason = event.reason;
|
|
511
|
+
if (!rejectBeaconDue(options.client, event, payload.ts)) return;
|
|
512
|
+
}
|
|
513
|
+
await post(options, BEACON_PATH, "beacon", event.form, payload);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
function sendPurgeReceipt(options, receipt) {
|
|
517
|
+
return fireAndForget(options, async () => {
|
|
518
|
+
const counts = [receipt.deleted, receipt.remaining];
|
|
519
|
+
if (!ID_PATTERN.test(receipt.form) || !counts.every((n) => Number.isSafeInteger(n) && n >= 0)) return;
|
|
520
|
+
await post(options, RECEIPT_PATH, "receipt", receipt.form, {
|
|
521
|
+
v: 1,
|
|
522
|
+
client: options.client,
|
|
523
|
+
form: receipt.form,
|
|
524
|
+
deleted: receipt.deleted,
|
|
525
|
+
remaining: receipt.remaining,
|
|
526
|
+
ts: Math.floor(options.now ?? Date.now() / 1e3)
|
|
527
|
+
});
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// src/scrub.ts
|
|
532
|
+
var REDACTED = "[redacted]";
|
|
533
|
+
var SYNTH_NAME = /^x-dd-synth(-.*)?$/i;
|
|
534
|
+
function scrubHeaders(headers) {
|
|
535
|
+
if (typeof Headers !== "undefined" && headers instanceof Headers) {
|
|
536
|
+
const out = new Headers();
|
|
537
|
+
headers.forEach((value, name) => out.append(name, SYNTH_NAME.test(name) ? REDACTED : value));
|
|
538
|
+
return out;
|
|
539
|
+
}
|
|
540
|
+
if (Array.isArray(headers)) {
|
|
541
|
+
return headers.map(([name, value]) => [name, SYNTH_NAME.test(name) ? REDACTED : value]);
|
|
542
|
+
}
|
|
543
|
+
return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, SYNTH_NAME.test(name) ? REDACTED : value]));
|
|
544
|
+
}
|
|
545
|
+
function scrubText(text) {
|
|
546
|
+
return text.replace(/(x-dd-synth(?:-[a-z]+)?)(["']?\s*[:=]\s*["']?)[^\s"',;}&]+/gi, `$1$2${REDACTED}`);
|
|
547
|
+
}
|
|
548
|
+
var MAX_DEPTH = 12;
|
|
549
|
+
function scrubValue(value, depth) {
|
|
550
|
+
if (depth > MAX_DEPTH) return "[truncated]";
|
|
551
|
+
if (typeof value === "string") return scrubText(value);
|
|
552
|
+
if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && SYNTH_NAME.test(value[0])) {
|
|
553
|
+
return [value[0], REDACTED];
|
|
554
|
+
}
|
|
555
|
+
if (Array.isArray(value)) return value.map((v) => scrubValue(v, depth + 1));
|
|
556
|
+
if (value && typeof value === "object") {
|
|
557
|
+
return Object.fromEntries(
|
|
558
|
+
Object.entries(value).map(([k, v]) => [k, SYNTH_NAME.test(k) ? REDACTED : scrubValue(v, depth + 1)])
|
|
559
|
+
);
|
|
560
|
+
}
|
|
561
|
+
return value;
|
|
562
|
+
}
|
|
563
|
+
function scrubSentryEvent(event) {
|
|
564
|
+
try {
|
|
565
|
+
return scrubValue(event, 0);
|
|
566
|
+
} catch {
|
|
567
|
+
const copy = { ...event };
|
|
568
|
+
if (copy.request && typeof copy.request === "object") copy.request = { ...copy.request, headers: void 0 };
|
|
569
|
+
return copy;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
573
|
+
0 && (module.exports = {
|
|
574
|
+
BEACON_CODES,
|
|
575
|
+
BEACON_PATH,
|
|
576
|
+
CANARY_DOMAIN,
|
|
577
|
+
CANONICAL_PREFIX,
|
|
578
|
+
DEFAULT_ENDPOINT,
|
|
579
|
+
DEFAULT_WINDOW_SECONDS,
|
|
580
|
+
FORM_MODES,
|
|
581
|
+
HEADER,
|
|
582
|
+
ID_PATTERN,
|
|
583
|
+
MODES,
|
|
584
|
+
PROTOCOL_VERSION,
|
|
585
|
+
RECEIPT_PATH,
|
|
586
|
+
REDACTED,
|
|
587
|
+
REJECT_REASONS,
|
|
588
|
+
RUN_ID_PATTERN,
|
|
589
|
+
SITEVERIFY_URL,
|
|
590
|
+
SyntheticRecipientError,
|
|
591
|
+
assertCanaryRecipient,
|
|
592
|
+
canaryAddress,
|
|
593
|
+
canonicalString,
|
|
594
|
+
generateRunId,
|
|
595
|
+
hostAndPath,
|
|
596
|
+
isCanaryRecipient,
|
|
597
|
+
isProductionHost,
|
|
598
|
+
isTurnstileTestKey,
|
|
599
|
+
keysFromEnv,
|
|
600
|
+
memoryReplayGuard,
|
|
601
|
+
normaliseHostname,
|
|
602
|
+
resetRejectBeaconThrottle,
|
|
603
|
+
scrubHeaders,
|
|
604
|
+
scrubSentryEvent,
|
|
605
|
+
scrubText,
|
|
606
|
+
sendBeacon,
|
|
607
|
+
sendPurgeReceipt,
|
|
608
|
+
sign,
|
|
609
|
+
syntheticReport,
|
|
610
|
+
turnstileConfigCheck,
|
|
611
|
+
upstashReplayGuard,
|
|
612
|
+
verify,
|
|
613
|
+
verifyRequest
|
|
614
|
+
});
|