@grovemotorco/manifold 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +50 -2
- package/dist/api.d.ts +6515 -0
- package/dist/api.js +643 -0
- package/dist/client.d.ts +2603 -0
- package/dist/client.js +42 -0
- package/dist/domain-Dye3ZdC_.js +922 -0
- package/dist/filter-DQnhobby.js +240 -0
- package/dist/ids-Ced7gYBp.d.ts +1704 -0
- package/dist/index.d.ts +640 -0
- package/dist/index.js +1339 -0
- package/dist/listen.d.ts +530 -0
- package/dist/listen.js +566 -0
- package/package.json +49 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1339 @@
|
|
|
1
|
+
import { A as toBufferSource, C as secretAad, D as timingSafeEqual, E as sha256Hex, M as utf8Decode, N as utf8Encode, O as toBase64, S as sealedKeyId, T as sha256, _ as parseKeyring, a as SecretBox, b as sealJson, c as fingerprint, d as fromHex, f as hmac, g as openSecret, h as openJson, i as KeyringError, j as toHex, k as toBase64Url, l as fromBase64, m as needsReseal, n as matchesGlob, o as SecretBoxError, p as importHmacKey, r as matchingRoutes, s as concatBytes, t as matchesEventTypes, u as fromBase64Url, v as randomBytes, w as secretsEqual, x as sealSecret, y as resealSecret } from "./filter-DQnhobby.js";
|
|
2
|
+
import { $ as NoneVerify, $t as idPattern, A as HashAlgorithm, At as SecretInfo, B as LIMITS, Bt as TargetLabel, C as ErrorCode, Ct as RouteConfig, D as FINISHED_DELIVERY_STATUSES, Dt as SecretEncoding, E as ExtractorPart, Et as RouteView, F as IssuedSigningSecret, Ft as SourceConfig, G as ListenerSessionId, Gt as VerifySpec, H as ListenTokenInfo, Ht as Tolerance, I as JsonChallengeHandshake, It as SourceKey, J as LocalAttemptRecord, Jt as sourceConfigFields, K as ListenersSetting, Kt as relayConfigFields, L as JwtAlgorithm, Lt as SourceStats, M as HeaderName, Mt as SignatureEncoding, N as HmacVerify, Nt as SignatureFormat, O as Fingerprint, Ot as SecretHeaderInfo, P as IngestAck, Pt as SigningSecretInfo, Q as Millis, Qt as idAt, R as JwtVerify, Rt as SourceView, S as ErrorBody, St as Revision, T as Extractor, Tt as RouteState, U as ListenerInfo, Ut as ValueSource, V as ListenTokenId, Vt as TokenVerify, W as ListenerName, Wt as VerifyOverride, X as MaxBodyBytes, Xt as LOCAL_ID_PREFIX, Y as LocalId, Yt as ID_PREFIXES, Z as MiB, Zt as ULID_PATTERN, _ as DeliveryDetail, _t as RequestRecord, a as AttemptStatus, an as newId, at as PresetResponse, b as DeliveryStatus, bt as RetentionDays, c as AutoPauseThreshold, ct as RejectionReason, d as ConfigDocument, dt as RelayConfig, en as idTime, et as Page, f as ConfigRelay, ft as RelayId, g as DedupeWindowSeconds, gt as RequestId, h as Count, ht as RequestDetail, i as AttemptRecord, in as minIdAt, it as PresetId, j as HeaderMap, jt as SecretValue, k as HandshakeSpec, kt as SecretHeaders, l as BodyPath, lt as RejectionRecord, m as ConfigSource, mt as RelayView, n as ApplyResult, nn as isLocalId, nt as PayloadTemplate, o as AuditAction, on as newLocalId, ot as Principal, p as ConfigRoute, pt as RelayTimeoutMs, q as LocalAttemptKind, qt as routeConfigFields, r as AttemptId, rn as makeIdGenerator, rt as Preset, s as AuditRecord, st as RejectionCounter, t as ApplyChanges, tn as isId, tt as PauseReason, u as ClaimRequirement, ut as Rejections, v as DeliveryId, vt as RequestStatus, w as EventTypeGlob, wt as RouteId, x as ERROR_STATUS, xt as RetryPolicy, y as DeliveryRecord, yt as ResolvedVerification, z as KiB, zt as TIMINGS } from "./domain-Dye3ZdC_.js";
|
|
3
|
+
import * as Context from "effect/Context";
|
|
4
|
+
import * as Effect from "effect/Effect";
|
|
5
|
+
import * as Layer from "effect/Layer";
|
|
6
|
+
import * as Schema from "effect/Schema";
|
|
7
|
+
import * as Result from "effect/Result";
|
|
8
|
+
import * as Predicate from "effect/Predicate";
|
|
9
|
+
import * as Option from "effect/Option";
|
|
10
|
+
import * as Data from "effect/Data";
|
|
11
|
+
// src/core/headers.ts
|
|
12
|
+
/**
|
|
13
|
+
* Header rules: reading headers case-insensitively, what is stored (§7.4) and
|
|
14
|
+
* what a relay receives (§6.6).
|
|
15
|
+
*/
|
|
16
|
+
const isFetchHeaders = (headers) => headers instanceof Headers;
|
|
17
|
+
/** Every header as `[lowercase name, value]`; repeated values joined with `, `. */
|
|
18
|
+
const headerEntries = (headers) => {
|
|
19
|
+
const out = /* @__PURE__ */ new Map();
|
|
20
|
+
const add = (name, value) => {
|
|
21
|
+
const key = name.toLowerCase();
|
|
22
|
+
const existing = out.get(key);
|
|
23
|
+
out.set(key, existing === void 0 ? value : `${existing}, ${value}`);
|
|
24
|
+
};
|
|
25
|
+
if (isFetchHeaders(headers)) headers.forEach((value, name) => add(name, value));
|
|
26
|
+
else for (const [name, value] of Object.entries(headers)) {
|
|
27
|
+
if (value === void 0) continue;
|
|
28
|
+
if (Predicate.isString(value)) add(name, value);
|
|
29
|
+
else for (const item of value) add(name, item);
|
|
30
|
+
}
|
|
31
|
+
return Array.from(out);
|
|
32
|
+
};
|
|
33
|
+
const getHeader = (headers, name) => {
|
|
34
|
+
if (isFetchHeaders(headers)) return headers.get(name) ?? void 0;
|
|
35
|
+
const lower = name.toLowerCase();
|
|
36
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
37
|
+
if (key.toLowerCase() !== lower || value === void 0) continue;
|
|
38
|
+
return Predicate.isString(value) ? value : value.join(", ");
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
/** Lowercase header names, sorted. What a rejection record keeps (§5.4). */
|
|
42
|
+
const headerNames = (headers) => headerEntries(headers).map(([name]) => name).sort();
|
|
43
|
+
/** Always stored as `[redacted:<fingerprint>]`. */
|
|
44
|
+
const ALWAYS_REDACTED = [
|
|
45
|
+
"authorization",
|
|
46
|
+
"cookie",
|
|
47
|
+
"proxy-authorization"
|
|
48
|
+
];
|
|
49
|
+
const redactedValue = async (value) => `[redacted:${await fingerprint(value)}]`;
|
|
50
|
+
/**
|
|
51
|
+
* The headers to store for a request: lowercase names, credentials and the
|
|
52
|
+
* listed headers replaced by `[redacted:<fingerprint>]`.
|
|
53
|
+
*/
|
|
54
|
+
const redactForStorage = async (headers, redact = []) => {
|
|
55
|
+
const hidden = /* @__PURE__ */ new Set([...ALWAYS_REDACTED, ...redact.map((name) => name.toLowerCase())]);
|
|
56
|
+
const out = {};
|
|
57
|
+
for (const [name, value] of headerEntries(headers)) out[name] = hidden.has(name) ? await redactedValue(value) : value;
|
|
58
|
+
return out;
|
|
59
|
+
};
|
|
60
|
+
/** Response headers redacted on attempt records. */
|
|
61
|
+
const REDACTED_RESPONSE_HEADERS = ["set-cookie", "authorization"];
|
|
62
|
+
const redactResponseHeaders = (headers) => {
|
|
63
|
+
const out = {};
|
|
64
|
+
for (const [name, value] of headerEntries(headers)) out[name] = REDACTED_RESPONSE_HEADERS.includes(name) ? "[redacted]" : value;
|
|
65
|
+
return out;
|
|
66
|
+
};
|
|
67
|
+
const HOP_BY_HOP_HEADERS = [
|
|
68
|
+
"connection",
|
|
69
|
+
"keep-alive",
|
|
70
|
+
"proxy-authenticate",
|
|
71
|
+
"proxy-authorization",
|
|
72
|
+
"proxy-connection",
|
|
73
|
+
"te",
|
|
74
|
+
"trailer",
|
|
75
|
+
"trailers",
|
|
76
|
+
"transfer-encoding",
|
|
77
|
+
"upgrade"
|
|
78
|
+
];
|
|
79
|
+
/** The Standard Webhooks headers manifold sets on signed attempts. */
|
|
80
|
+
const STANDARD_WEBHOOK_HEADERS = [
|
|
81
|
+
"webhook-id",
|
|
82
|
+
"webhook-timestamp",
|
|
83
|
+
"webhook-signature"
|
|
84
|
+
];
|
|
85
|
+
const DROPPED_EXACT = /* @__PURE__ */ new Set([
|
|
86
|
+
...HOP_BY_HOP_HEADERS,
|
|
87
|
+
...ALWAYS_REDACTED,
|
|
88
|
+
...STANDARD_WEBHOOK_HEADERS,
|
|
89
|
+
"host",
|
|
90
|
+
"content-length",
|
|
91
|
+
"x-real-ip"
|
|
92
|
+
]);
|
|
93
|
+
const DROPPED_PREFIXES = [
|
|
94
|
+
"cf-",
|
|
95
|
+
"x-forwarded-",
|
|
96
|
+
"manifold-"
|
|
97
|
+
];
|
|
98
|
+
/** True when an inbound header is never forwarded to a relay. */
|
|
99
|
+
const isDroppedOnForward = (name) => {
|
|
100
|
+
const lower = name.toLowerCase();
|
|
101
|
+
return DROPPED_EXACT.has(lower) || DROPPED_PREFIXES.some((prefix) => lower.startsWith(prefix));
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* True when a relay's configured extra header may not be set, because
|
|
105
|
+
* manifold or the HTTP layer owns it.
|
|
106
|
+
*/
|
|
107
|
+
const isReservedRelayHeader = (name) => {
|
|
108
|
+
const lower = name.toLowerCase();
|
|
109
|
+
return HOP_BY_HOP_HEADERS.includes(lower) || STANDARD_WEBHOOK_HEADERS.includes(lower) || lower === "host" || lower === "content-length" || lower.startsWith("manifold-");
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* The headers of an outbound attempt. Later layers win: inbound headers, then
|
|
113
|
+
* the relay's extra headers, then manifold's own and the signatures.
|
|
114
|
+
*/
|
|
115
|
+
const buildRelayHeaders = (input) => {
|
|
116
|
+
const redact = new Set((input.redactHeaders ?? []).map((name) => name.toLowerCase()));
|
|
117
|
+
const out = {};
|
|
118
|
+
for (const [name, value] of Object.entries(input.requestHeaders)) {
|
|
119
|
+
const lower = name.toLowerCase();
|
|
120
|
+
if (isDroppedOnForward(lower) || redact.has(lower)) continue;
|
|
121
|
+
out[lower] = value;
|
|
122
|
+
}
|
|
123
|
+
for (const [name, value] of Object.entries(input.relayHeaders ?? {})) if (!isReservedRelayHeader(name)) out[name.toLowerCase()] = value;
|
|
124
|
+
const { meta } = input;
|
|
125
|
+
out["manifold-request-id"] = meta.requestId;
|
|
126
|
+
out["manifold-delivery-id"] = meta.deliveryId;
|
|
127
|
+
out["manifold-attempt"] = String(meta.attempt);
|
|
128
|
+
out["manifold-source"] = meta.source;
|
|
129
|
+
if (meta.eventType !== null) out["manifold-event-type"] = meta.eventType;
|
|
130
|
+
if (meta.replay) out["manifold-replay"] = "true";
|
|
131
|
+
for (const [name, value] of Object.entries(input.signatureHeaders ?? {})) out[name.toLowerCase()] = value;
|
|
132
|
+
return out;
|
|
133
|
+
};
|
|
134
|
+
// src/core/signing.ts
|
|
135
|
+
/**
|
|
136
|
+
* The signatures manifold puts on every attempt to a relay with a signing
|
|
137
|
+
* secret (§6.6), and the helpers a relay uses to check them. Runs on Node,
|
|
138
|
+
* Bun and workerd (WebCrypto only).
|
|
139
|
+
*
|
|
140
|
+
* - Standard Webhooks: `webhook-id` (the delivery id), `webhook-timestamp`,
|
|
141
|
+
* `webhook-signature: v1,<base64 HMAC-SHA256("{id}.{timestamp}.{body}")>`.
|
|
142
|
+
* - Signed context: `manifold-context` (base64url JSON) and
|
|
143
|
+
* `manifold-signature: v1,<base64 HMAC-SHA256("{deliveryId}.{timestamp}.{context}.{body}")>`,
|
|
144
|
+
* where `{timestamp}` is the `webhook-timestamp` value.
|
|
145
|
+
*
|
|
146
|
+
* During a rotation both secrets sign, so each signature header carries two
|
|
147
|
+
* space-separated `v1,…` entries; a verifier accepts either.
|
|
148
|
+
*/
|
|
149
|
+
const SIGNING_SECRET_PREFIX = "whsec_";
|
|
150
|
+
/** A new relay signing secret: `whsec_` and 32 random bytes in base64. */
|
|
151
|
+
const generateSigningSecret = () => `${SIGNING_SECRET_PREFIX}${toBase64(randomBytes(32))}`;
|
|
152
|
+
/** The HMAC key of a `whsec_…` secret (a bare base64 secret is accepted too). */
|
|
153
|
+
const signingKeyBytes = (secret) => fromBase64(secret.startsWith("whsec_") ? secret.slice(6) : secret);
|
|
154
|
+
const keyOrThrow = (secret) => {
|
|
155
|
+
const key = signingKeyBytes(secret);
|
|
156
|
+
if (key === void 0 || key.length === 0) throw new TypeError("signing secret is not a valid whsec_ secret");
|
|
157
|
+
return key;
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* What manifold verified about a request, passed to relays in `manifold-context`.
|
|
161
|
+
* `deliveryId` is a `dlv_` id from a relay, or an `lcl_` id when the
|
|
162
|
+
* `manifold` CLI forwards to a local target (docs/LOCAL-RELAY.md §4.2).
|
|
163
|
+
*/
|
|
164
|
+
const SignedContext = Schema.Struct({
|
|
165
|
+
requestId: RequestId,
|
|
166
|
+
deliveryId: Schema.Union([DeliveryId, LocalId]),
|
|
167
|
+
source: SourceKey,
|
|
168
|
+
eventType: Schema.NullOr(Schema.String),
|
|
169
|
+
receivedAt: Millis,
|
|
170
|
+
replay: Schema.Boolean,
|
|
171
|
+
principal: Schema.NullOr(Principal)
|
|
172
|
+
}).annotate({ identifier: "SignedContext" });
|
|
173
|
+
const encodeContext = (context) => toBase64Url(utf8Encode(JSON.stringify(context)));
|
|
174
|
+
const decodeContext = (text) => {
|
|
175
|
+
const bytes = fromBase64Url(text);
|
|
176
|
+
if (bytes === void 0) return void 0;
|
|
177
|
+
try {
|
|
178
|
+
return Option.getOrUndefined(Schema.decodeUnknownOption(SignedContext)(JSON.parse(utf8Decode(bytes))));
|
|
179
|
+
} catch {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const standardPayload = (id, timestamp, body) => concatBytes(utf8Encode(`${id}.${timestamp}.`), body);
|
|
184
|
+
const contextPayload = (deliveryId, timestamp, context, body) => concatBytes(utf8Encode(`${deliveryId}.${timestamp}.${context}.`), body);
|
|
185
|
+
const signList = async (secrets, payload) => {
|
|
186
|
+
return (await Promise.all(secrets.map((secret) => hmac("sha256", keyOrThrow(secret), payload)))).map((signature) => `v1,${toBase64(signature)}`).join(" ");
|
|
187
|
+
};
|
|
188
|
+
const signStandardWebhook = async (input) => ({
|
|
189
|
+
"webhook-id": input.id,
|
|
190
|
+
"webhook-timestamp": String(input.timestamp),
|
|
191
|
+
"webhook-signature": await signList(input.secrets, standardPayload(input.id, input.timestamp, input.body))
|
|
192
|
+
});
|
|
193
|
+
/** All five signature headers for one attempt. Pass them to `buildRelayHeaders`. */
|
|
194
|
+
const relaySignatureHeaders = async (input) => {
|
|
195
|
+
const context = encodeContext(input.context);
|
|
196
|
+
const deliveryId = input.context.deliveryId;
|
|
197
|
+
return {
|
|
198
|
+
...await signStandardWebhook({
|
|
199
|
+
id: deliveryId,
|
|
200
|
+
timestamp: input.timestamp,
|
|
201
|
+
body: input.body,
|
|
202
|
+
secrets: input.secrets
|
|
203
|
+
}),
|
|
204
|
+
"manifold-context": context,
|
|
205
|
+
"manifold-signature": await signList(input.secrets, contextPayload(deliveryId, input.timestamp, context, input.body))
|
|
206
|
+
};
|
|
207
|
+
};
|
|
208
|
+
const parseSignatureList = (value) => value.trim().split(/\s+/).slice(0, 16).flatMap((entry) => {
|
|
209
|
+
if (!entry.startsWith("v1,")) return [];
|
|
210
|
+
const bytes = fromBase64(entry.slice(3));
|
|
211
|
+
return bytes === void 0 ? [] : [bytes];
|
|
212
|
+
});
|
|
213
|
+
const matchesAny = async (secrets, signatures, payload) => {
|
|
214
|
+
for (const secret of secrets) {
|
|
215
|
+
const key = signingKeyBytes(secret);
|
|
216
|
+
if (key === void 0 || key.length === 0) continue;
|
|
217
|
+
const expected = await hmac("sha256", key, payload);
|
|
218
|
+
if (signatures.some((signature) => timingSafeEqual(signature, expected))) return true;
|
|
219
|
+
}
|
|
220
|
+
return false;
|
|
221
|
+
};
|
|
222
|
+
const readTimestamp = (headers, options) => {
|
|
223
|
+
const text = getHeader(headers, "webhook-timestamp")?.trim();
|
|
224
|
+
if (text === void 0) return {
|
|
225
|
+
ok: false,
|
|
226
|
+
reason: "missing_headers"
|
|
227
|
+
};
|
|
228
|
+
if (!/^\d{1,12}$/.test(text)) return {
|
|
229
|
+
ok: false,
|
|
230
|
+
reason: "malformed"
|
|
231
|
+
};
|
|
232
|
+
const timestamp = Number(text);
|
|
233
|
+
const nowSeconds = Math.floor((options.now ?? Date.now()) / 1e3);
|
|
234
|
+
if (Math.abs(nowSeconds - timestamp) > (options.toleranceSeconds ?? 300)) return {
|
|
235
|
+
ok: false,
|
|
236
|
+
reason: "timestamp_out_of_tolerance"
|
|
237
|
+
};
|
|
238
|
+
return {
|
|
239
|
+
ok: true,
|
|
240
|
+
timestamp
|
|
241
|
+
};
|
|
242
|
+
};
|
|
243
|
+
/** Verifies the Standard Webhooks headers (what any Standard Webhooks library does). */
|
|
244
|
+
const verifyStandardWebhook = async (options) => {
|
|
245
|
+
const id = getHeader(options.headers, "webhook-id")?.trim();
|
|
246
|
+
const signatureHeader = getHeader(options.headers, "webhook-signature");
|
|
247
|
+
if (id === void 0 || id === "" || signatureHeader === void 0) return {
|
|
248
|
+
ok: false,
|
|
249
|
+
reason: "missing_headers"
|
|
250
|
+
};
|
|
251
|
+
const timestamp = readTimestamp(options.headers, options);
|
|
252
|
+
if (!timestamp.ok) return timestamp;
|
|
253
|
+
const signatures = parseSignatureList(signatureHeader);
|
|
254
|
+
if (signatures.length === 0) return {
|
|
255
|
+
ok: false,
|
|
256
|
+
reason: "malformed"
|
|
257
|
+
};
|
|
258
|
+
return await matchesAny(options.secrets, signatures, standardPayload(id, timestamp.timestamp, options.body)) ? {
|
|
259
|
+
ok: true,
|
|
260
|
+
id,
|
|
261
|
+
timestamp: timestamp.timestamp
|
|
262
|
+
} : {
|
|
263
|
+
ok: false,
|
|
264
|
+
reason: "bad_signature"
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
/**
|
|
268
|
+
* Verifies manifold's signed context and returns it, so a relay can trust
|
|
269
|
+
* who manifold verified (`context.principal`), not only the body. Relays
|
|
270
|
+
* should still dedupe on `context.deliveryId`.
|
|
271
|
+
*/
|
|
272
|
+
const verifyRelayRequest = async (options) => {
|
|
273
|
+
const contextText = getHeader(options.headers, "manifold-context")?.trim();
|
|
274
|
+
const signatureHeader = getHeader(options.headers, "manifold-signature");
|
|
275
|
+
if (contextText === void 0 || contextText === "" || signatureHeader === void 0) return {
|
|
276
|
+
ok: false,
|
|
277
|
+
reason: "missing_headers"
|
|
278
|
+
};
|
|
279
|
+
const timestamp = readTimestamp(options.headers, options);
|
|
280
|
+
if (!timestamp.ok) return timestamp;
|
|
281
|
+
const context = decodeContext(contextText);
|
|
282
|
+
const signatures = parseSignatureList(signatureHeader);
|
|
283
|
+
if (context === void 0 || signatures.length === 0) return {
|
|
284
|
+
ok: false,
|
|
285
|
+
reason: "malformed"
|
|
286
|
+
};
|
|
287
|
+
const payload = contextPayload(context.deliveryId, timestamp.timestamp, contextText, options.body);
|
|
288
|
+
if (!await matchesAny(options.secrets, signatures, payload)) return {
|
|
289
|
+
ok: false,
|
|
290
|
+
reason: "bad_signature"
|
|
291
|
+
};
|
|
292
|
+
const webhookId = getHeader(options.headers, "webhook-id")?.trim();
|
|
293
|
+
if (webhookId !== void 0 && webhookId !== context.deliveryId) return {
|
|
294
|
+
ok: false,
|
|
295
|
+
reason: "context_mismatch"
|
|
296
|
+
};
|
|
297
|
+
return {
|
|
298
|
+
ok: true,
|
|
299
|
+
context,
|
|
300
|
+
timestamp: timestamp.timestamp
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
// src/core/outbound.ts
|
|
304
|
+
/** Set on requests the CLI forwards to a local target, so an application can tell. */
|
|
305
|
+
const LOCAL_HEADER = "manifold-local";
|
|
306
|
+
/** Methods sent without a body. */
|
|
307
|
+
const BODYLESS_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
308
|
+
const buildOutboundRequest = async (input) => {
|
|
309
|
+
const { request } = input;
|
|
310
|
+
const signatureHeaders = input.signing === void 0 ? void 0 : await relaySignatureHeaders({
|
|
311
|
+
context: {
|
|
312
|
+
requestId: request.id,
|
|
313
|
+
deliveryId: input.deliveryId,
|
|
314
|
+
source: request.sourceKey,
|
|
315
|
+
eventType: request.eventType,
|
|
316
|
+
receivedAt: request.receivedAt,
|
|
317
|
+
replay: input.replay,
|
|
318
|
+
principal: request.principal
|
|
319
|
+
},
|
|
320
|
+
timestamp: input.signing.timestamp,
|
|
321
|
+
body: input.body,
|
|
322
|
+
secrets: input.signing.secrets
|
|
323
|
+
});
|
|
324
|
+
const headers = buildRelayHeaders({
|
|
325
|
+
requestHeaders: request.headers,
|
|
326
|
+
redactHeaders: input.redactHeaders,
|
|
327
|
+
relayHeaders: input.extraHeaders ?? {},
|
|
328
|
+
meta: {
|
|
329
|
+
requestId: request.id,
|
|
330
|
+
deliveryId: input.deliveryId,
|
|
331
|
+
attempt: input.attempt,
|
|
332
|
+
source: request.sourceKey,
|
|
333
|
+
eventType: request.eventType,
|
|
334
|
+
replay: input.replay
|
|
335
|
+
},
|
|
336
|
+
signatureHeaders
|
|
337
|
+
});
|
|
338
|
+
if (input.local === true) headers[LOCAL_HEADER] = "true";
|
|
339
|
+
const method = request.method.toUpperCase();
|
|
340
|
+
return {
|
|
341
|
+
method,
|
|
342
|
+
headers,
|
|
343
|
+
body: BODYLESS_METHODS.has(method) ? void 0 : input.body
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
/** Matches a header value stored as `[redacted:<fingerprint>]` (§7.4). */
|
|
347
|
+
const REDACTED_VALUE_PATTERN = /^\[redacted:[0-9a-f]{8}\]$/;
|
|
348
|
+
/**
|
|
349
|
+
* The names of stored headers whose value was redacted at ingest. A client
|
|
350
|
+
* that cannot read the source's `redactHeaders` (a listen token may not read
|
|
351
|
+
* the source config) uses this instead: the stored set is the same, except
|
|
352
|
+
* for a list changed after the request was stored.
|
|
353
|
+
*/
|
|
354
|
+
const redactedHeaderNames = (headers) => Object.entries(headers).filter(([, value]) => REDACTED_VALUE_PATTERN.test(value)).map(([name]) => name.toLowerCase());
|
|
355
|
+
// src/core/json.ts
|
|
356
|
+
/** Parsed JSON values: narrowing a `Schema.Json` to its array and object cases. */
|
|
357
|
+
const isJsonArray = (value) => Array.isArray(value);
|
|
358
|
+
const isJsonObject = (value) => Predicate.isObject(value);
|
|
359
|
+
// src/core/verify/types.ts
|
|
360
|
+
/** Shared verifier input and result types. */
|
|
361
|
+
const VerifyResult = Data.taggedEnum();
|
|
362
|
+
const verified = (fields = {}) => VerifyResult.Verified({
|
|
363
|
+
principal: fields.principal ?? null,
|
|
364
|
+
timestamp: fields.timestamp ?? null,
|
|
365
|
+
id: fields.id ?? null,
|
|
366
|
+
secretIndex: fields.secretIndex ?? null
|
|
367
|
+
});
|
|
368
|
+
const rejected = (reason, detail) => VerifyResult.Rejected({
|
|
369
|
+
reason,
|
|
370
|
+
detail
|
|
371
|
+
});
|
|
372
|
+
// src/core/verify/token.ts
|
|
373
|
+
/** The shared-token verifier (§5.2): a header compared against the secrets by hash. */
|
|
374
|
+
/**
|
|
375
|
+
* Reads a credential from a header, stripping `{scheme} ` when a scheme is
|
|
376
|
+
* set. Returns `undefined` when absent or when the scheme does not match.
|
|
377
|
+
*/
|
|
378
|
+
const readCredential = (headers, header, scheme) => {
|
|
379
|
+
const value = getHeader(headers, header)?.trim();
|
|
380
|
+
if (value === void 0 || value === "") return void 0;
|
|
381
|
+
if (scheme === void 0) return value;
|
|
382
|
+
const space = value.indexOf(" ");
|
|
383
|
+
if (space === -1 || value.slice(0, space).toLowerCase() !== scheme.toLowerCase()) return void 0;
|
|
384
|
+
const credential = value.slice(space + 1).trim();
|
|
385
|
+
return credential === "" ? void 0 : credential;
|
|
386
|
+
};
|
|
387
|
+
const verifyToken = async (input) => {
|
|
388
|
+
if (input.secrets.length === 0) return rejected("no_secrets", "the source has no secrets");
|
|
389
|
+
const token = readCredential(input.headers, input.spec.header, input.spec.scheme);
|
|
390
|
+
if (token === void 0) {
|
|
391
|
+
const expected = input.spec.scheme === void 0 ? input.spec.header : `${input.spec.header}: ${input.spec.scheme} …`;
|
|
392
|
+
return rejected("missing_token", `missing ${expected}`);
|
|
393
|
+
}
|
|
394
|
+
for (const [index, secret] of input.secrets.entries()) if (await secretsEqual(token, secret)) return verified({ secretIndex: index });
|
|
395
|
+
return rejected("bad_token", "the token matches no secret");
|
|
396
|
+
};
|
|
397
|
+
// src/core/verify/jwt.ts
|
|
398
|
+
/**
|
|
399
|
+
* The JWT verifier (§5.2): RS256 and ES256 via WebCrypto against a JWKS that
|
|
400
|
+
* the caller fetches (so tests need no network), with `kid` selection and
|
|
401
|
+
* `iss`/`aud`/`exp`/`nbf`/claim checks.
|
|
402
|
+
*/
|
|
403
|
+
const Jwk = Schema.Struct({
|
|
404
|
+
kty: Schema.String,
|
|
405
|
+
kid: Schema.optionalKey(Schema.String),
|
|
406
|
+
alg: Schema.optionalKey(Schema.String),
|
|
407
|
+
use: Schema.optionalKey(Schema.String),
|
|
408
|
+
n: Schema.optionalKey(Schema.String),
|
|
409
|
+
e: Schema.optionalKey(Schema.String),
|
|
410
|
+
crv: Schema.optionalKey(Schema.String),
|
|
411
|
+
x: Schema.optionalKey(Schema.String),
|
|
412
|
+
y: Schema.optionalKey(Schema.String)
|
|
413
|
+
});
|
|
414
|
+
const Jwks = Schema.Struct({ keys: Schema.Array(Jwk) });
|
|
415
|
+
/** A per-isolate cached JWKS fetcher backed by `fetch`. */
|
|
416
|
+
const makeJwksCache = (options = {}) => {
|
|
417
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
418
|
+
const ttlMs = options.ttlMs ?? 6e5;
|
|
419
|
+
const minRefreshMs = options.minRefreshMs ?? 3e4;
|
|
420
|
+
const now = options.now ?? Date.now;
|
|
421
|
+
const cache = /* @__PURE__ */ new Map();
|
|
422
|
+
const decode = Schema.decodeUnknownSync(Jwks);
|
|
423
|
+
return async (url, { refresh }) => {
|
|
424
|
+
const cached = cache.get(url);
|
|
425
|
+
const age = cached === void 0 ? Infinity : now() - cached.at;
|
|
426
|
+
if (cached !== void 0 && age < (refresh ? minRefreshMs : ttlMs)) return cached.jwks;
|
|
427
|
+
const response = await fetchImpl(url, { headers: { accept: "application/json" } });
|
|
428
|
+
if (!response.ok) throw new Error(`JWKS fetch failed with status ${response.status}`);
|
|
429
|
+
const jwks = decode(await response.json());
|
|
430
|
+
cache.set(url, {
|
|
431
|
+
at: now(),
|
|
432
|
+
jwks
|
|
433
|
+
});
|
|
434
|
+
return jwks;
|
|
435
|
+
};
|
|
436
|
+
};
|
|
437
|
+
/** The isolate's JWKS fetcher. `JwksCache.layer` is a `makeJwksCache()` over the global `fetch`. */
|
|
438
|
+
var JwksCache = class JwksCache extends Context.Service()("manifold/JwksCache") {
|
|
439
|
+
static layer = Layer.sync(JwksCache, () => makeJwksCache());
|
|
440
|
+
};
|
|
441
|
+
/**
|
|
442
|
+
* JWKS URLs accepted without operator action. `*` matches one DNS label.
|
|
443
|
+
* Operators add more with the `extra` argument of `isAllowedJwksUrl`.
|
|
444
|
+
*/
|
|
445
|
+
const DEFAULT_JWKS_URLS = ["https://www.googleapis.com/oauth2/v3/certs", "https://*.cloudflareaccess.com/cdn-cgi/access/certs"];
|
|
446
|
+
const GOOGLE_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs";
|
|
447
|
+
/** The Cloudflare Access JWKS for a team domain such as `myteam.cloudflareaccess.com`. */
|
|
448
|
+
const accessJwksUrl = (teamDomain) => `https://${teamDomain.replace(/^https?:\/\//, "").replace(/\/+$/, "")}/cdn-cgi/access/certs`;
|
|
449
|
+
const isAllowedJwksUrl = (url, extra = []) => [...DEFAULT_JWKS_URLS, ...extra].some((pattern) => {
|
|
450
|
+
return new RegExp(`^${pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[a-z0-9-]+")}$`, "i").test(url);
|
|
451
|
+
});
|
|
452
|
+
const JwtHeader = Schema.Struct({
|
|
453
|
+
alg: Schema.String,
|
|
454
|
+
kid: Schema.optionalKey(Schema.String),
|
|
455
|
+
typ: Schema.optionalKey(Schema.String)
|
|
456
|
+
});
|
|
457
|
+
const parseJson = (bytes) => {
|
|
458
|
+
if (bytes === void 0) return void 0;
|
|
459
|
+
try {
|
|
460
|
+
return JSON.parse(utf8Decode(bytes));
|
|
461
|
+
} catch {
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
const algorithmParams = {
|
|
466
|
+
RS256: {
|
|
467
|
+
importParams: {
|
|
468
|
+
name: "RSASSA-PKCS1-v1_5",
|
|
469
|
+
hash: "SHA-256"
|
|
470
|
+
},
|
|
471
|
+
verifyParams: { name: "RSASSA-PKCS1-v1_5" },
|
|
472
|
+
kty: "RSA"
|
|
473
|
+
},
|
|
474
|
+
ES256: {
|
|
475
|
+
importParams: {
|
|
476
|
+
name: "ECDSA",
|
|
477
|
+
namedCurve: "P-256"
|
|
478
|
+
},
|
|
479
|
+
verifyParams: {
|
|
480
|
+
name: "ECDSA",
|
|
481
|
+
hash: "SHA-256"
|
|
482
|
+
},
|
|
483
|
+
kty: "EC"
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
const keyFits = (jwk, alg) => jwk.kty === algorithmParams[alg].kty && (jwk.alg === void 0 || jwk.alg === alg) && (jwk.use === void 0 || jwk.use === "sig") && (alg !== "ES256" || jwk.crv === "P-256");
|
|
487
|
+
const importJwk = (jwk, alg) => {
|
|
488
|
+
const material = alg === "RS256" ? {
|
|
489
|
+
kty: "RSA",
|
|
490
|
+
n: jwk.n,
|
|
491
|
+
e: jwk.e
|
|
492
|
+
} : {
|
|
493
|
+
kty: "EC",
|
|
494
|
+
crv: "P-256",
|
|
495
|
+
x: jwk.x,
|
|
496
|
+
y: jwk.y
|
|
497
|
+
};
|
|
498
|
+
return crypto.subtle.importKey("jwk", material, algorithmParams[alg].importParams, false, ["verify"]);
|
|
499
|
+
};
|
|
500
|
+
const asList = (value) => Predicate.isString(value) ? [value] : value;
|
|
501
|
+
const isScalarList = (value) => Array.isArray(value);
|
|
502
|
+
const claimMatches = (actual, required) => {
|
|
503
|
+
return (isScalarList(required) ? required : [required]).some((value) => value === actual);
|
|
504
|
+
};
|
|
505
|
+
/** Verifies a compact JWS token string against `spec`. */
|
|
506
|
+
const verifyJwtToken = async (token, spec, now, fetchJwks) => {
|
|
507
|
+
const parts = token.split(".");
|
|
508
|
+
const [headerPart, payloadPart, signaturePart] = parts;
|
|
509
|
+
if (parts.length !== 3 || headerPart === void 0 || payloadPart === void 0 || signaturePart === void 0) return rejected("jwt_malformed", "token is not a compact JWS");
|
|
510
|
+
const header = Schema.decodeUnknownOption(JwtHeader)(parseJson(fromBase64Url(headerPart)));
|
|
511
|
+
const claims = parseJson(fromBase64Url(payloadPart));
|
|
512
|
+
const signature = fromBase64Url(signaturePart);
|
|
513
|
+
if (Option.isNone(header) || !isJsonObject(claims) || signature === void 0) return rejected("jwt_malformed", "token header, payload or signature does not decode");
|
|
514
|
+
const alg = header.value.alg;
|
|
515
|
+
if (alg !== "RS256" && alg !== "ES256") return rejected("jwt_unsupported_alg", `algorithm ${alg} is not supported`);
|
|
516
|
+
if (!spec.algorithms.includes(alg)) return rejected("jwt_unsupported_alg", `algorithm ${alg} is not allowed`);
|
|
517
|
+
if (fetchJwks === void 0) return rejected("jwks_unavailable", "no JWKS fetcher configured");
|
|
518
|
+
const kid = header.value.kid;
|
|
519
|
+
const candidates = async (refresh) => {
|
|
520
|
+
return (await fetchJwks(spec.jwksUrl, { refresh })).keys.filter((jwk) => keyFits(jwk, alg) && (kid === void 0 || jwk.kid === kid));
|
|
521
|
+
};
|
|
522
|
+
let keys;
|
|
523
|
+
try {
|
|
524
|
+
keys = await candidates(false);
|
|
525
|
+
if (keys.length === 0 && kid !== void 0) keys = await candidates(true);
|
|
526
|
+
} catch {
|
|
527
|
+
return rejected("jwks_unavailable", "the JWKS could not be fetched");
|
|
528
|
+
}
|
|
529
|
+
if (keys.length === 0) return rejected("jwt_unknown_kid", kid === void 0 ? "no key in the JWKS fits the token" : "unknown key id");
|
|
530
|
+
const signingInput = toBufferSource(utf8Encode(`${headerPart}.${payloadPart}`));
|
|
531
|
+
let valid = false;
|
|
532
|
+
for (const jwk of keys) try {
|
|
533
|
+
const key = await importJwk(jwk, alg);
|
|
534
|
+
if (await crypto.subtle.verify(algorithmParams[alg].verifyParams, key, toBufferSource(signature), signingInput)) {
|
|
535
|
+
valid = true;
|
|
536
|
+
break;
|
|
537
|
+
}
|
|
538
|
+
} catch {}
|
|
539
|
+
if (!valid) return rejected("jwt_bad_signature", "token signature is invalid");
|
|
540
|
+
const nowSeconds = now / 1e3;
|
|
541
|
+
const tolerance = spec.clockToleranceSeconds;
|
|
542
|
+
if (!Predicate.isNumber(claims.exp)) return rejected("jwt_malformed", "token has no numeric exp");
|
|
543
|
+
if (nowSeconds > claims.exp + tolerance) return rejected("jwt_expired", "token has expired");
|
|
544
|
+
if (claims.nbf !== void 0) {
|
|
545
|
+
if (!Predicate.isNumber(claims.nbf)) return rejected("jwt_malformed", "token nbf is not numeric");
|
|
546
|
+
if (nowSeconds + tolerance < claims.nbf) return rejected("jwt_not_yet_valid", "token is not valid yet");
|
|
547
|
+
}
|
|
548
|
+
if (!Predicate.isString(claims.iss) || !asList(spec.issuer).includes(claims.iss)) return rejected("jwt_bad_issuer", "token issuer is not accepted");
|
|
549
|
+
const audience = (Predicate.isString(claims.aud) ? [claims.aud] : isJsonArray(claims.aud) ? claims.aud.filter(Predicate.isString) : []).find((value) => asList(spec.audience).includes(value));
|
|
550
|
+
if (audience === void 0) return rejected("jwt_bad_audience", "token audience is not accepted");
|
|
551
|
+
for (const [name, required] of Object.entries(spec.claims)) if (!claimMatches(claims[name], required)) return rejected("jwt_claim_mismatch", `claim ${name} does not match`);
|
|
552
|
+
const principal = {
|
|
553
|
+
kind: "jwt",
|
|
554
|
+
iss: claims.iss,
|
|
555
|
+
sub: Predicate.isString(claims.sub) ? claims.sub : null,
|
|
556
|
+
email: Predicate.isString(claims.email) ? claims.email : null,
|
|
557
|
+
aud: audience
|
|
558
|
+
};
|
|
559
|
+
return verified({ principal });
|
|
560
|
+
};
|
|
561
|
+
const verifyJwt = async (input) => {
|
|
562
|
+
const token = readCredential(input.headers, input.spec.header, input.spec.scheme);
|
|
563
|
+
if (token === void 0) return rejected("jwt_missing", `missing token in ${input.spec.header}`);
|
|
564
|
+
return verifyJwtToken(token, input.spec, input.now, input.fetchJwks);
|
|
565
|
+
};
|
|
566
|
+
// src/core/presets.ts
|
|
567
|
+
/**
|
|
568
|
+
* The v1 preset table (§5.3), the extractors for event type and idempotency
|
|
569
|
+
* key, handshakes, and the merge of a source's overrides over its preset.
|
|
570
|
+
*/
|
|
571
|
+
const header = (name) => ({ header: name });
|
|
572
|
+
const body = (path) => ({ body: path });
|
|
573
|
+
const from = (...parts) => ({ from: parts });
|
|
574
|
+
const PRESETS = {
|
|
575
|
+
github: {
|
|
576
|
+
id: "github",
|
|
577
|
+
description: "GitHub: HMAC-SHA256 of the body in x-hub-signature-256",
|
|
578
|
+
verify: {
|
|
579
|
+
type: "hmac",
|
|
580
|
+
algorithm: "sha256",
|
|
581
|
+
header: "x-hub-signature-256",
|
|
582
|
+
encoding: "hex",
|
|
583
|
+
format: "prefixed",
|
|
584
|
+
prefix: "sha256=",
|
|
585
|
+
payload: "{body}"
|
|
586
|
+
},
|
|
587
|
+
eventType: {
|
|
588
|
+
from: [header("x-github-event")],
|
|
589
|
+
suffix: body("action")
|
|
590
|
+
},
|
|
591
|
+
idempotencyKey: from(header("x-github-delivery")),
|
|
592
|
+
redactHeaders: []
|
|
593
|
+
},
|
|
594
|
+
stripe: {
|
|
595
|
+
id: "stripe",
|
|
596
|
+
description: "Stripe: stripe-signature t=…,v1=… over {timestamp}.{body}, 5 minute tolerance",
|
|
597
|
+
verify: {
|
|
598
|
+
type: "hmac",
|
|
599
|
+
algorithm: "sha256",
|
|
600
|
+
header: "stripe-signature",
|
|
601
|
+
encoding: "hex",
|
|
602
|
+
format: "kv-list",
|
|
603
|
+
key: "v1",
|
|
604
|
+
payload: "{timestamp}.{body}",
|
|
605
|
+
timestamp: { signatureKey: "t" },
|
|
606
|
+
tolerance: {
|
|
607
|
+
pastSeconds: 300,
|
|
608
|
+
futureSeconds: 300
|
|
609
|
+
}
|
|
610
|
+
},
|
|
611
|
+
eventType: from(body("type")),
|
|
612
|
+
idempotencyKey: from(body("id")),
|
|
613
|
+
redactHeaders: []
|
|
614
|
+
},
|
|
615
|
+
slack: {
|
|
616
|
+
id: "slack",
|
|
617
|
+
description: "Slack: x-slack-signature v0=… over v0:{timestamp}:{body}, 5 minute tolerance, url_verification handshake",
|
|
618
|
+
verify: {
|
|
619
|
+
type: "hmac",
|
|
620
|
+
algorithm: "sha256",
|
|
621
|
+
header: "x-slack-signature",
|
|
622
|
+
encoding: "hex",
|
|
623
|
+
format: "prefixed",
|
|
624
|
+
prefix: "v0=",
|
|
625
|
+
payload: "v0:{timestamp}:{body}",
|
|
626
|
+
timestamp: { header: "x-slack-request-timestamp" },
|
|
627
|
+
tolerance: {
|
|
628
|
+
pastSeconds: 300,
|
|
629
|
+
futureSeconds: 300
|
|
630
|
+
}
|
|
631
|
+
},
|
|
632
|
+
eventType: from(body("event.type"), body("type")),
|
|
633
|
+
idempotencyKey: from(body("event_id")),
|
|
634
|
+
handshake: {
|
|
635
|
+
type: "json-challenge",
|
|
636
|
+
path: "type",
|
|
637
|
+
equals: "url_verification",
|
|
638
|
+
challenge: "challenge"
|
|
639
|
+
},
|
|
640
|
+
response: { status: 200 },
|
|
641
|
+
redactHeaders: []
|
|
642
|
+
},
|
|
643
|
+
shopify: {
|
|
644
|
+
id: "shopify",
|
|
645
|
+
description: "Shopify: base64 HMAC-SHA256 of the body in x-shopify-hmac-sha256",
|
|
646
|
+
verify: {
|
|
647
|
+
type: "hmac",
|
|
648
|
+
algorithm: "sha256",
|
|
649
|
+
header: "x-shopify-hmac-sha256",
|
|
650
|
+
encoding: "base64",
|
|
651
|
+
format: "plain",
|
|
652
|
+
payload: "{body}"
|
|
653
|
+
},
|
|
654
|
+
eventType: from(header("x-shopify-topic")),
|
|
655
|
+
idempotencyKey: from(header("x-shopify-webhook-id")),
|
|
656
|
+
redactHeaders: []
|
|
657
|
+
},
|
|
658
|
+
gitlab: {
|
|
659
|
+
id: "gitlab",
|
|
660
|
+
description: "GitLab: shared token in x-gitlab-token",
|
|
661
|
+
verify: {
|
|
662
|
+
type: "token",
|
|
663
|
+
header: "x-gitlab-token"
|
|
664
|
+
},
|
|
665
|
+
eventType: from(header("x-gitlab-event")),
|
|
666
|
+
idempotencyKey: from(header("x-gitlab-event-uuid")),
|
|
667
|
+
redactHeaders: ["x-gitlab-token"]
|
|
668
|
+
},
|
|
669
|
+
linear: {
|
|
670
|
+
id: "linear",
|
|
671
|
+
description: "Linear: hex HMAC-SHA256 of the body in linear-signature",
|
|
672
|
+
verify: {
|
|
673
|
+
type: "hmac",
|
|
674
|
+
algorithm: "sha256",
|
|
675
|
+
header: "linear-signature",
|
|
676
|
+
encoding: "hex",
|
|
677
|
+
format: "plain",
|
|
678
|
+
payload: "{body}"
|
|
679
|
+
},
|
|
680
|
+
eventType: from(body("type")),
|
|
681
|
+
idempotencyKey: from(header("linear-delivery")),
|
|
682
|
+
redactHeaders: []
|
|
683
|
+
},
|
|
684
|
+
"standard-webhooks": {
|
|
685
|
+
id: "standard-webhooks",
|
|
686
|
+
description: "Standard Webhooks: webhook-signature v1,… over {id}.{timestamp}.{body}, whsec_ secrets, 5 minute tolerance",
|
|
687
|
+
verify: {
|
|
688
|
+
type: "hmac",
|
|
689
|
+
algorithm: "sha256",
|
|
690
|
+
header: "webhook-signature",
|
|
691
|
+
encoding: "base64",
|
|
692
|
+
format: "space-list",
|
|
693
|
+
key: "v1",
|
|
694
|
+
payload: "{id}.{timestamp}.{body}",
|
|
695
|
+
id: { header: "webhook-id" },
|
|
696
|
+
timestamp: { header: "webhook-timestamp" },
|
|
697
|
+
tolerance: {
|
|
698
|
+
pastSeconds: 300,
|
|
699
|
+
futureSeconds: 300
|
|
700
|
+
},
|
|
701
|
+
secretEncoding: "whsec"
|
|
702
|
+
},
|
|
703
|
+
eventType: from(body("type")),
|
|
704
|
+
idempotencyKey: from(header("webhook-id")),
|
|
705
|
+
redactHeaders: []
|
|
706
|
+
},
|
|
707
|
+
"google-oidc": {
|
|
708
|
+
id: "google-oidc",
|
|
709
|
+
description: "Google-signed OIDC ID token in authorization: Bearer. The source sets audience and claims.",
|
|
710
|
+
verify: {
|
|
711
|
+
type: "jwt",
|
|
712
|
+
header: "authorization",
|
|
713
|
+
scheme: "Bearer",
|
|
714
|
+
jwksUrl: GOOGLE_JWKS_URL,
|
|
715
|
+
algorithms: ["RS256"],
|
|
716
|
+
issuer: ["https://accounts.google.com", "accounts.google.com"]
|
|
717
|
+
},
|
|
718
|
+
eventType: from(header("x-event-type")),
|
|
719
|
+
idempotencyKey: from(header("idempotency-key")),
|
|
720
|
+
redactHeaders: []
|
|
721
|
+
},
|
|
722
|
+
hmac: {
|
|
723
|
+
id: "hmac",
|
|
724
|
+
description: "Generic HMAC; the source sets every parameter (defaults: sha256, hex, x-signature, {body})",
|
|
725
|
+
verify: {
|
|
726
|
+
type: "hmac",
|
|
727
|
+
algorithm: "sha256",
|
|
728
|
+
header: "x-signature",
|
|
729
|
+
encoding: "hex",
|
|
730
|
+
format: "plain",
|
|
731
|
+
payload: "{body}"
|
|
732
|
+
},
|
|
733
|
+
redactHeaders: []
|
|
734
|
+
},
|
|
735
|
+
bearer: {
|
|
736
|
+
id: "bearer",
|
|
737
|
+
description: "Shared token in authorization: Bearer",
|
|
738
|
+
verify: {
|
|
739
|
+
type: "token",
|
|
740
|
+
header: "authorization",
|
|
741
|
+
scheme: "Bearer"
|
|
742
|
+
},
|
|
743
|
+
redactHeaders: []
|
|
744
|
+
},
|
|
745
|
+
none: {
|
|
746
|
+
id: "none",
|
|
747
|
+
description: "No verification. Requires allowUnverified: true.",
|
|
748
|
+
verify: { type: "none" },
|
|
749
|
+
redactHeaders: []
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
const PRESET_LIST = Object.values(PRESETS);
|
|
753
|
+
const getPreset = (id) => PRESETS[id];
|
|
754
|
+
/**
|
|
755
|
+
* Merges a source's verify override over a preset template. An override with
|
|
756
|
+
* a different `type` replaces the template; otherwise fields are merged
|
|
757
|
+
* shallowly. The result is decoded with `VerifySpec` (defaults applied).
|
|
758
|
+
*/
|
|
759
|
+
const resolveVerifySpec = (template, override) => {
|
|
760
|
+
const merged = {
|
|
761
|
+
...override?.type !== void 0 && override.type !== template.type ? { type: override.type } : template,
|
|
762
|
+
...override
|
|
763
|
+
};
|
|
764
|
+
return Result.mapError(Schema.decodeUnknownResult(VerifySpec)(merged), (error) => error.message);
|
|
765
|
+
};
|
|
766
|
+
/** Header names a verifier reads credentials from; never stored in clear or forwarded. */
|
|
767
|
+
const credentialHeaders = (spec) => spec.type === "token" || spec.type === "jwt" ? [spec.header.toLowerCase()] : [];
|
|
768
|
+
/**
|
|
769
|
+
* A source's effective verification: preset plus overrides. Fails with a
|
|
770
|
+
* message when the merged spec is invalid, or when it is `none` without
|
|
771
|
+
* `allowUnverified`.
|
|
772
|
+
*/
|
|
773
|
+
const resolveSource = (source) => {
|
|
774
|
+
const preset = PRESETS[source.preset];
|
|
775
|
+
return Result.flatMap(resolveVerifySpec(preset.verify, source.verify), (verify) => {
|
|
776
|
+
if (verify.type === "none" && !source.allowUnverified) return Result.fail("verification 'none' requires allowUnverified: true");
|
|
777
|
+
const redactHeaders = Array.from(new Set([
|
|
778
|
+
...preset.redactHeaders,
|
|
779
|
+
...source.redactHeaders,
|
|
780
|
+
...credentialHeaders(verify)
|
|
781
|
+
].map((name) => name.toLowerCase())));
|
|
782
|
+
return Result.succeed({
|
|
783
|
+
verify,
|
|
784
|
+
eventType: source.eventType ?? preset.eventType ?? null,
|
|
785
|
+
idempotencyKey: source.idempotencyKey ?? preset.idempotencyKey ?? null,
|
|
786
|
+
handshake: source.handshake ?? preset.handshake ?? null,
|
|
787
|
+
response: source.response ?? preset.response ?? null,
|
|
788
|
+
redactHeaders
|
|
789
|
+
});
|
|
790
|
+
});
|
|
791
|
+
};
|
|
792
|
+
/** The raw body parsed as JSON, or `undefined` when it is not JSON. */
|
|
793
|
+
const parseJsonBody = (rawBody) => {
|
|
794
|
+
if (rawBody.length === 0) return void 0;
|
|
795
|
+
try {
|
|
796
|
+
return JSON.parse(utf8Decode(rawBody));
|
|
797
|
+
} catch {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
};
|
|
801
|
+
/** The value at a dot path. Numeric segments index arrays. */
|
|
802
|
+
const getPath = (value, path) => {
|
|
803
|
+
let current = value;
|
|
804
|
+
for (const segment of path.split(".")) if (isJsonArray(current)) current = /^\d+$/.test(segment) ? current[Number(segment)] : void 0;
|
|
805
|
+
else if (isJsonObject(current)) current = current[segment];
|
|
806
|
+
else return void 0;
|
|
807
|
+
return current;
|
|
808
|
+
};
|
|
809
|
+
const asText = (value) => {
|
|
810
|
+
if (Predicate.isString(value)) return value === "" ? void 0 : value;
|
|
811
|
+
if (Predicate.isNumber(value) && Number.isFinite(value)) return String(value);
|
|
812
|
+
if (Predicate.isBoolean(value)) return String(value);
|
|
813
|
+
};
|
|
814
|
+
const readPart = (part, input) => "header" in part ? asText(getHeader(input.headers, part.header)?.trim()) : asText(getPath(input.json, part.body));
|
|
815
|
+
/** Applies an extractor. Values longer than `LIMITS.extractedValueChars` are dropped. */
|
|
816
|
+
const extract = (extractor, input) => {
|
|
817
|
+
if (extractor === null || extractor === void 0) return null;
|
|
818
|
+
let value;
|
|
819
|
+
for (const part of extractor.from) {
|
|
820
|
+
value = readPart(part, input);
|
|
821
|
+
if (value !== void 0) break;
|
|
822
|
+
}
|
|
823
|
+
if (value === void 0) return null;
|
|
824
|
+
if (extractor.suffix !== void 0) {
|
|
825
|
+
const suffix = readPart(extractor.suffix, input);
|
|
826
|
+
if (suffix !== void 0) value = `${value}.${suffix}`;
|
|
827
|
+
}
|
|
828
|
+
return value.length > LIMITS.extractedValueChars ? null : value;
|
|
829
|
+
};
|
|
830
|
+
const extractAll = (resolved, input) => ({
|
|
831
|
+
eventType: extract(resolved.eventType, input),
|
|
832
|
+
idempotencyKey: extract(resolved.idempotencyKey, input)
|
|
833
|
+
});
|
|
834
|
+
/** The response to a handshake, or `undefined` when the request is not one. Run after verification. */
|
|
835
|
+
const matchHandshake = (spec, json) => {
|
|
836
|
+
if (spec === null || spec === void 0) return void 0;
|
|
837
|
+
switch (spec.type) {
|
|
838
|
+
case "json-challenge": {
|
|
839
|
+
if (getPath(json, spec.path) !== spec.equals) return void 0;
|
|
840
|
+
const challenge = getPath(json, spec.challenge);
|
|
841
|
+
if (!Predicate.isString(challenge)) return void 0;
|
|
842
|
+
return {
|
|
843
|
+
status: 200,
|
|
844
|
+
body: challenge,
|
|
845
|
+
contentType: "text/plain; charset=utf-8"
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
// src/core/retry.ts
|
|
851
|
+
/**
|
|
852
|
+
* Retry maths and outcome classification (§6.4), as pure functions. The
|
|
853
|
+
* SourceDO calls `decideNext` in `complete` and when a lease expires.
|
|
854
|
+
*/
|
|
855
|
+
/** What happened to one attempt, as the consumer reports it. */
|
|
856
|
+
const AttemptOutcome = Schema.Union([
|
|
857
|
+
Schema.Struct({
|
|
858
|
+
type: Schema.Literal("response"),
|
|
859
|
+
status: Schema.Int,
|
|
860
|
+
/** The relay's `Retry-After` header, when present. */
|
|
861
|
+
retryAfter: Schema.optionalKey(Schema.NullOr(Schema.String))
|
|
862
|
+
}),
|
|
863
|
+
Schema.Struct({
|
|
864
|
+
type: Schema.Literal("network_error"),
|
|
865
|
+
message: Schema.String
|
|
866
|
+
}),
|
|
867
|
+
Schema.Struct({ type: Schema.Literal("timeout") }),
|
|
868
|
+
Schema.Struct({
|
|
869
|
+
type: Schema.Literal("blocked"),
|
|
870
|
+
reason: Schema.String
|
|
871
|
+
}),
|
|
872
|
+
Schema.Struct({ type: Schema.Literal("lost") })
|
|
873
|
+
]).annotate({ identifier: "AttemptOutcome" });
|
|
874
|
+
/** 2xx succeeds; network errors, timeouts, lost attempts, 408, 429 and 5xx retry; anything else fails at once. */
|
|
875
|
+
const classifyOutcome = (outcome) => {
|
|
876
|
+
switch (outcome.type) {
|
|
877
|
+
case "response": {
|
|
878
|
+
const { status } = outcome;
|
|
879
|
+
if (status >= 200 && status < 300) return "success";
|
|
880
|
+
if (status === 408 || status === 429 || status >= 500 && status < 600) return "retryable";
|
|
881
|
+
return "permanent";
|
|
882
|
+
}
|
|
883
|
+
case "network_error":
|
|
884
|
+
case "timeout":
|
|
885
|
+
case "lost": return "retryable";
|
|
886
|
+
case "blocked": return "permanent";
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
/**
|
|
890
|
+
* The backoff before retry number `attempt + 1`, given `attempt` attempts so
|
|
891
|
+
* far (1-based). `random` returns a value in [0, 1).
|
|
892
|
+
*/
|
|
893
|
+
const backoffDelayMs = (policy, attempt, random = Math.random) => {
|
|
894
|
+
const n = Math.max(1, attempt);
|
|
895
|
+
const base = policy.strategy === "exponential" ? policy.baseSeconds * Math.pow(policy.factor, n - 1) : policy.baseSeconds * n;
|
|
896
|
+
const jittered = Math.min(base, policy.capSeconds) * (1 + policy.jitter * (2 * random() - 1));
|
|
897
|
+
return Math.round(Math.min(Math.max(jittered, 0), policy.capSeconds) * 1e3);
|
|
898
|
+
};
|
|
899
|
+
/**
|
|
900
|
+
* Parses `Retry-After` (delta seconds or an HTTP date) into a delay in ms,
|
|
901
|
+
* capped at one hour. `undefined` when absent or malformed.
|
|
902
|
+
*/
|
|
903
|
+
const parseRetryAfter = (value, now) => {
|
|
904
|
+
if (value === null || value === void 0) return void 0;
|
|
905
|
+
const text = value.trim();
|
|
906
|
+
let delay;
|
|
907
|
+
if (/^\d+$/.test(text)) delay = Number(text) * 1e3;
|
|
908
|
+
else {
|
|
909
|
+
const at = Date.parse(text);
|
|
910
|
+
if (Number.isNaN(at)) return void 0;
|
|
911
|
+
delay = at - now;
|
|
912
|
+
}
|
|
913
|
+
return Math.min(Math.max(delay, 0), TIMINGS.retryAfterCapMs);
|
|
914
|
+
};
|
|
915
|
+
/** The state a delivery moves to after an attempt finishes or is lost. */
|
|
916
|
+
const decideNext = (input) => {
|
|
917
|
+
const kind = classifyOutcome(input.outcome);
|
|
918
|
+
if (kind === "success") return { status: "succeeded" };
|
|
919
|
+
if (kind === "permanent") return {
|
|
920
|
+
status: "failed",
|
|
921
|
+
reason: "permanent"
|
|
922
|
+
};
|
|
923
|
+
if (input.attemptCount >= input.maxAttempts) return {
|
|
924
|
+
status: "failed",
|
|
925
|
+
reason: "attempts_exhausted"
|
|
926
|
+
};
|
|
927
|
+
const delayMs = (input.outcome.type === "response" ? parseRetryAfter(input.outcome.retryAfter, input.now) : void 0) ?? backoffDelayMs(input.policy, input.attemptCount, input.random);
|
|
928
|
+
return {
|
|
929
|
+
status: "pending",
|
|
930
|
+
dueAt: input.now + delayMs,
|
|
931
|
+
delayMs
|
|
932
|
+
};
|
|
933
|
+
};
|
|
934
|
+
/** The delivery status a `NextState` stores. */
|
|
935
|
+
const nextStatus = (next) => next.status;
|
|
936
|
+
/**
|
|
937
|
+
* The route's consecutive-failure count after an attempt: a success resets
|
|
938
|
+
* it, a failed attempt adds one, a lost attempt leaves it unchanged (the
|
|
939
|
+
* relay may have received it).
|
|
940
|
+
*/
|
|
941
|
+
const nextConsecutiveFailures = (previous, outcome) => {
|
|
942
|
+
if (outcome.type === "lost") return previous;
|
|
943
|
+
return classifyOutcome(outcome) === "success" ? 0 : previous + 1;
|
|
944
|
+
};
|
|
945
|
+
/** True when the route should be paused with reason `consecutive_failures`. 0 disables auto-pause. */
|
|
946
|
+
const shouldAutoPause = (consecutiveFailures, threshold) => threshold > 0 && consecutiveFailures >= threshold;
|
|
947
|
+
/** Statuses a manual retry accepts (§6.4); `dispatched` and `running` answer 409. */
|
|
948
|
+
const RETRYABLE_BY_OPERATOR = [
|
|
949
|
+
"failed",
|
|
950
|
+
"pending",
|
|
951
|
+
"cancelled"
|
|
952
|
+
];
|
|
953
|
+
const CANCELLABLE = ["pending"];
|
|
954
|
+
// src/core/verify/hmac.ts
|
|
955
|
+
/** The generic HMAC verifier (§5.2) and a matching signer, for tests and senders. */
|
|
956
|
+
/** More signatures than this in one header are ignored. */
|
|
957
|
+
const MAX_SIGNATURES = 16;
|
|
958
|
+
/** HMAC key bytes for a secret, or `undefined` when it does not decode. */
|
|
959
|
+
const decodeHmacSecret = (encoding, secret) => {
|
|
960
|
+
switch (encoding) {
|
|
961
|
+
case "utf8": return utf8Encode(secret);
|
|
962
|
+
case "base64": return fromBase64(secret);
|
|
963
|
+
case "whsec": return fromBase64(secret.startsWith("whsec_") ? secret.slice(6) : secret);
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
/** The bytes a template signs: the template's text with `{body}` replaced by the raw body. */
|
|
967
|
+
const buildSignedPayload = (template, parts) => {
|
|
968
|
+
const fill = (text) => text.replaceAll("{timestamp}", parts.timestamp === void 0 ? "" : String(parts.timestamp)).replaceAll("{id}", parts.id ?? "").replaceAll("{url}", parts.url ?? "");
|
|
969
|
+
const [before = "", after = ""] = template.split("{body}");
|
|
970
|
+
return concatBytes(utf8Encode(fill(before)), parts.body, utf8Encode(fill(after)));
|
|
971
|
+
};
|
|
972
|
+
/** Splits a `kv-list` header (`t=1,v1=a,v1=b`) into entries. */
|
|
973
|
+
const parseKvList = (value) => value.split(",").flatMap((part) => {
|
|
974
|
+
const index = part.indexOf("=");
|
|
975
|
+
return index <= 0 ? [] : [[part.slice(0, index).trim(), part.slice(index + 1).trim()]];
|
|
976
|
+
});
|
|
977
|
+
/** The encoded signatures carried by a signature header, per the spec's format. */
|
|
978
|
+
const extractSignatures = (spec, value) => {
|
|
979
|
+
const trimmed = value.trim();
|
|
980
|
+
let out;
|
|
981
|
+
switch (spec.format) {
|
|
982
|
+
case "plain":
|
|
983
|
+
out = [trimmed];
|
|
984
|
+
break;
|
|
985
|
+
case "prefixed": {
|
|
986
|
+
const prefix = spec.prefix ?? "";
|
|
987
|
+
out = trimmed.toLowerCase().startsWith(prefix.toLowerCase()) ? [trimmed.slice(prefix.length)] : [];
|
|
988
|
+
break;
|
|
989
|
+
}
|
|
990
|
+
case "kv-list":
|
|
991
|
+
out = parseKvList(trimmed).filter(([key]) => key === spec.key).map(([, signature]) => signature);
|
|
992
|
+
break;
|
|
993
|
+
case "space-list": out = trimmed.split(/\s+/).flatMap((entry) => {
|
|
994
|
+
const index = entry.indexOf(",");
|
|
995
|
+
return index > 0 && entry.slice(0, index) === spec.key ? [entry.slice(index + 1)] : [];
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
return out.filter((signature) => signature.length > 0).slice(0, MAX_SIGNATURES);
|
|
999
|
+
};
|
|
1000
|
+
const readSource = (source, headers, signatureHeader) => {
|
|
1001
|
+
if ("header" in source) return getHeader(headers, source.header)?.trim();
|
|
1002
|
+
if (signatureHeader === void 0) return void 0;
|
|
1003
|
+
return parseKvList(signatureHeader).find(([key]) => key === source.signatureKey)?.[1];
|
|
1004
|
+
};
|
|
1005
|
+
const decodeSignature = (encoding, signature) => encoding === "hex" ? fromHex(signature) : fromBase64(signature);
|
|
1006
|
+
const verifyHmac = async (input) => {
|
|
1007
|
+
const { spec } = input;
|
|
1008
|
+
if (input.secrets.length === 0) return rejected("no_secrets", "the source has no secrets");
|
|
1009
|
+
const header = getHeader(input.headers, spec.header);
|
|
1010
|
+
if (header === void 0 || header.trim() === "") return rejected("missing_signature", `missing ${spec.header} header`);
|
|
1011
|
+
const signatures = extractSignatures(spec, header).flatMap((text) => {
|
|
1012
|
+
const bytes = decodeSignature(spec.encoding, text);
|
|
1013
|
+
return bytes === void 0 ? [] : [bytes];
|
|
1014
|
+
});
|
|
1015
|
+
if (signatures.length === 0) return rejected("malformed", `no ${spec.encoding} signature in ${spec.header}`);
|
|
1016
|
+
let timestamp;
|
|
1017
|
+
if (spec.timestamp !== void 0) {
|
|
1018
|
+
const text = readSource(spec.timestamp, input.headers, header);
|
|
1019
|
+
if (text === void 0 || text === "") return rejected("missing_timestamp", "missing signature timestamp");
|
|
1020
|
+
if (!/^\d{1,12}$/.test(text)) return rejected("malformed", "signature timestamp is not unix seconds");
|
|
1021
|
+
timestamp = Number(text);
|
|
1022
|
+
const nowSeconds = Math.floor(input.now / 1e3);
|
|
1023
|
+
if (nowSeconds - timestamp > spec.tolerance.pastSeconds) return rejected("timestamp_out_of_tolerance", "signature timestamp is too old");
|
|
1024
|
+
if (timestamp - nowSeconds > spec.tolerance.futureSeconds) return rejected("timestamp_out_of_tolerance", "signature timestamp is in the future");
|
|
1025
|
+
}
|
|
1026
|
+
let id;
|
|
1027
|
+
if (spec.id !== void 0) {
|
|
1028
|
+
id = readSource(spec.id, input.headers, header);
|
|
1029
|
+
if (id === void 0 || id === "") return rejected("missing_id", "missing signed message id");
|
|
1030
|
+
}
|
|
1031
|
+
const payload = toBufferSource(buildSignedPayload(spec.payload, {
|
|
1032
|
+
body: input.rawBody,
|
|
1033
|
+
timestamp,
|
|
1034
|
+
id,
|
|
1035
|
+
url: input.url
|
|
1036
|
+
}));
|
|
1037
|
+
for (const [index, secret] of input.secrets.entries()) {
|
|
1038
|
+
const keyBytes = decodeHmacSecret(spec.secretEncoding, secret);
|
|
1039
|
+
if (keyBytes === void 0) continue;
|
|
1040
|
+
const key = await importHmacKey(spec.algorithm, keyBytes);
|
|
1041
|
+
const expected = new Uint8Array(await crypto.subtle.sign("HMAC", key, payload));
|
|
1042
|
+
if (signatures.some((signature) => timingSafeEqual(signature, expected))) return verified({
|
|
1043
|
+
timestamp: timestamp ?? null,
|
|
1044
|
+
id: id ?? null,
|
|
1045
|
+
secretIndex: index
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
return rejected("bad_signature", "no secret matches the signature");
|
|
1049
|
+
};
|
|
1050
|
+
/** The encoded HMAC signature of `parts` under `spec`, as a sender would compute it. */
|
|
1051
|
+
const computeHmacSignature = async (spec, secret, parts) => {
|
|
1052
|
+
const key = decodeHmacSecret(spec.secretEncoding, secret);
|
|
1053
|
+
if (key === void 0) throw new TypeError(`secret is not valid ${spec.secretEncoding}`);
|
|
1054
|
+
const mac = await hmac(spec.algorithm, key, buildSignedPayload(spec.payload, parts));
|
|
1055
|
+
return spec.encoding === "hex" ? toHex(mac) : toBase64(mac);
|
|
1056
|
+
};
|
|
1057
|
+
/**
|
|
1058
|
+
* The headers a sender would send for `parts` under `spec`, one signature
|
|
1059
|
+
* per secret. Header-sourced timestamps and ids are included. For tests,
|
|
1060
|
+
* fixtures and tooling.
|
|
1061
|
+
*/
|
|
1062
|
+
const signHmac = async (spec, secrets, parts) => {
|
|
1063
|
+
const signatures = await Promise.all(secrets.map((secret) => computeHmacSignature(spec, secret, parts)));
|
|
1064
|
+
const out = {};
|
|
1065
|
+
const kvExtras = [];
|
|
1066
|
+
for (const [source, value] of [[spec.timestamp, parts.timestamp], [spec.id, parts.id]]) {
|
|
1067
|
+
if (source === void 0 || value === void 0) continue;
|
|
1068
|
+
if ("header" in source) out[source.header.toLowerCase()] = String(value);
|
|
1069
|
+
else kvExtras.push(`${source.signatureKey}=${value}`);
|
|
1070
|
+
}
|
|
1071
|
+
let header;
|
|
1072
|
+
switch (spec.format) {
|
|
1073
|
+
case "plain":
|
|
1074
|
+
header = signatures[0] ?? "";
|
|
1075
|
+
break;
|
|
1076
|
+
case "prefixed":
|
|
1077
|
+
header = `${spec.prefix ?? ""}${signatures[0] ?? ""}`;
|
|
1078
|
+
break;
|
|
1079
|
+
case "kv-list":
|
|
1080
|
+
header = [...kvExtras, ...signatures.map((signature) => `${spec.key}=${signature}`)].join(",");
|
|
1081
|
+
break;
|
|
1082
|
+
case "space-list": header = signatures.map((signature) => `${spec.key},${signature}`).join(" ");
|
|
1083
|
+
}
|
|
1084
|
+
out[spec.header.toLowerCase()] = header;
|
|
1085
|
+
return out;
|
|
1086
|
+
};
|
|
1087
|
+
// src/core/sender.ts
|
|
1088
|
+
/**
|
|
1089
|
+
* Sender-side helpers: sign a webhook the way a source's verification
|
|
1090
|
+
* expects and send it to an ingest URL. For tests, examples and
|
|
1091
|
+
* `manifold trigger`; the real senders (GitHub, Stripe, …) sign their own.
|
|
1092
|
+
*
|
|
1093
|
+
* ```ts
|
|
1094
|
+
* import { sendWebhook } from "@grovemotorco/manifold"
|
|
1095
|
+
*
|
|
1096
|
+
* const response = await sendWebhook({
|
|
1097
|
+
* url: "http://localhost:1337/in/github",
|
|
1098
|
+
* preset: "github",
|
|
1099
|
+
* secret: process.env.GITHUB_WEBHOOK_SECRET,
|
|
1100
|
+
* headers: { "x-github-event": "push", "x-github-delivery": crypto.randomUUID() },
|
|
1101
|
+
* body: { ref: "refs/heads/main" }
|
|
1102
|
+
* })
|
|
1103
|
+
* ```
|
|
1104
|
+
*/
|
|
1105
|
+
/** The verification a preset gives a source with no overrides. */
|
|
1106
|
+
const presetVerification = (preset) => {
|
|
1107
|
+
const definition = PRESETS[preset];
|
|
1108
|
+
const verify = resolveVerifySpec(definition.verify, void 0);
|
|
1109
|
+
if (Result.isFailure(verify)) throw new Error(`preset ${preset}: ${verify.failure}`);
|
|
1110
|
+
return {
|
|
1111
|
+
verify: verify.success,
|
|
1112
|
+
eventType: definition.eventType ?? null,
|
|
1113
|
+
idempotencyKey: definition.idempotencyKey ?? null
|
|
1114
|
+
};
|
|
1115
|
+
};
|
|
1116
|
+
/** The headers that authenticate `body` under `spec`, or why they cannot be made. */
|
|
1117
|
+
const signatureHeaders = async (spec, input) => {
|
|
1118
|
+
switch (spec.type) {
|
|
1119
|
+
case "hmac": {
|
|
1120
|
+
if (input.secret === void 0) return Result.fail("secret_required");
|
|
1121
|
+
const now = input.now ?? Date.now();
|
|
1122
|
+
return Result.succeed(await signHmac(spec, [input.secret], {
|
|
1123
|
+
body: input.body,
|
|
1124
|
+
timestamp: spec.timestamp === void 0 ? void 0 : Math.floor(now / 1e3),
|
|
1125
|
+
id: spec.id === void 0 ? void 0 : `msg_${toHex(randomBytes(12))}`,
|
|
1126
|
+
url: input.url
|
|
1127
|
+
}));
|
|
1128
|
+
}
|
|
1129
|
+
case "token":
|
|
1130
|
+
if (input.secret === void 0) return Result.fail("secret_required");
|
|
1131
|
+
return Result.succeed({ [spec.header.toLowerCase()]: spec.scheme === void 0 ? input.secret : `${spec.scheme} ${input.secret}` });
|
|
1132
|
+
case "jwt": return Result.fail("jwt_unsupported");
|
|
1133
|
+
case "none": return Result.succeed({});
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
const bodyBytes = (body) => body instanceof Uint8Array ? body : utf8Encode(JSON.stringify(body));
|
|
1137
|
+
const isPresetId = Schema.is(PresetId);
|
|
1138
|
+
const SIGN_FAILURES = {
|
|
1139
|
+
secret_required: "this verification needs the source's secret",
|
|
1140
|
+
jwt_unsupported: "JWT verification (e.g. Google OIDC) cannot be signed without the sender's private key"
|
|
1141
|
+
};
|
|
1142
|
+
/** Signs a webhook for a preset or verification. Throws when it cannot be signed (see `SignFailure`). */
|
|
1143
|
+
const signWebhook = async (input) => {
|
|
1144
|
+
const verification = isPresetId(input.preset) ? presetVerification(input.preset) : input.preset;
|
|
1145
|
+
const body = bodyBytes(input.body);
|
|
1146
|
+
const signed = await signatureHeaders(verification.verify, {
|
|
1147
|
+
body,
|
|
1148
|
+
secret: input.secret,
|
|
1149
|
+
url: input.url,
|
|
1150
|
+
now: input.now
|
|
1151
|
+
});
|
|
1152
|
+
if (Result.isFailure(signed)) throw new Error(SIGN_FAILURES[signed.failure]);
|
|
1153
|
+
const extra = Object.entries(input.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]);
|
|
1154
|
+
return {
|
|
1155
|
+
headers: {
|
|
1156
|
+
"content-type": "application/json",
|
|
1157
|
+
...Object.fromEntries(extra),
|
|
1158
|
+
...signed.success
|
|
1159
|
+
},
|
|
1160
|
+
body
|
|
1161
|
+
};
|
|
1162
|
+
};
|
|
1163
|
+
/** Signs a webhook and POSTs it to an ingest URL. A `202` means Manifold stored it. */
|
|
1164
|
+
const sendWebhook = async (input) => {
|
|
1165
|
+
const url = String(input.url);
|
|
1166
|
+
const { headers, body } = await signWebhook({
|
|
1167
|
+
...input,
|
|
1168
|
+
url
|
|
1169
|
+
});
|
|
1170
|
+
return (input.fetch ?? fetch)(url, {
|
|
1171
|
+
method: "POST",
|
|
1172
|
+
headers,
|
|
1173
|
+
body: toBufferSource(body),
|
|
1174
|
+
redirect: "manual"
|
|
1175
|
+
});
|
|
1176
|
+
};
|
|
1177
|
+
// src/core/ssrf.ts
|
|
1178
|
+
const fail = (reason, message) => ({
|
|
1179
|
+
ok: false,
|
|
1180
|
+
reason,
|
|
1181
|
+
message
|
|
1182
|
+
});
|
|
1183
|
+
/** Parses `"a.com, b.com"` into normalized suffixes. */
|
|
1184
|
+
const parseHostAllowlist = (value) => (value ?? "").split(",").map(normalizeSuffix).filter((suffix) => suffix.length > 0);
|
|
1185
|
+
const normalizeSuffix = (suffix) => suffix.trim().toLowerCase().replace(/^\*?\./, "").replace(/\.$/, "");
|
|
1186
|
+
const hostMatchesSuffix = (hostname, suffix) => {
|
|
1187
|
+
const host = hostname.toLowerCase().replace(/\.$/, "");
|
|
1188
|
+
const normalized = normalizeSuffix(suffix);
|
|
1189
|
+
return normalized.length > 0 && (host === normalized || host.endsWith(`.${normalized}`));
|
|
1190
|
+
};
|
|
1191
|
+
const parseOctet = (part) => /^\d{1,3}$/.test(part) && Number(part) <= 255 ? Number(part) : void 0;
|
|
1192
|
+
const parseIpv4 = (text) => {
|
|
1193
|
+
const [a, b, c, d, ...rest] = text.split(".").map(parseOctet);
|
|
1194
|
+
return rest.length === 0 && a !== void 0 && b !== void 0 && c !== void 0 && d !== void 0 ? [
|
|
1195
|
+
a,
|
|
1196
|
+
b,
|
|
1197
|
+
c,
|
|
1198
|
+
d
|
|
1199
|
+
] : void 0;
|
|
1200
|
+
};
|
|
1201
|
+
/** True for IPv4 addresses that are not publicly routable. */
|
|
1202
|
+
const isNonPublicIpv4 = ([a, b, c]) => a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && (c === 0 || c === 2) || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
|
|
1203
|
+
/**
|
|
1204
|
+
* Parses an IPv6 literal (no brackets) into eight 16-bit groups. Accepts the
|
|
1205
|
+
* form WHATWG URL serializes to, which already turns `::ffff:1.2.3.4` into hex.
|
|
1206
|
+
*/
|
|
1207
|
+
const parseIpv6 = (text) => {
|
|
1208
|
+
const halves = text.toLowerCase().split("::");
|
|
1209
|
+
if (halves.length > 2) return void 0;
|
|
1210
|
+
const group = (part) => part === "" ? [] : part.split(":");
|
|
1211
|
+
const head = group(halves[0] ?? "");
|
|
1212
|
+
const rest = halves.length === 2 ? group(halves[1] ?? "") : [];
|
|
1213
|
+
const parsePart = (part) => /^[0-9a-f]{1,4}$/.test(part) ? parseInt(part, 16) : NaN;
|
|
1214
|
+
const headNums = head.map(parsePart);
|
|
1215
|
+
const restNums = rest.map(parsePart);
|
|
1216
|
+
const explicit = headNums.length + restNums.length;
|
|
1217
|
+
if (halves.length === 1 && explicit !== 8) return void 0;
|
|
1218
|
+
if (halves.length === 2 && explicit > 7) return void 0;
|
|
1219
|
+
const groups = [
|
|
1220
|
+
...headNums,
|
|
1221
|
+
...Array(8 - explicit).fill(0),
|
|
1222
|
+
...restNums
|
|
1223
|
+
];
|
|
1224
|
+
return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 65535) ? groups : void 0;
|
|
1225
|
+
};
|
|
1226
|
+
/** True for IPv6 addresses that are not publicly routable, including mapped private IPv4. */
|
|
1227
|
+
const isNonPublicIpv6 = (groups) => {
|
|
1228
|
+
const g = (i) => groups[i] ?? 0;
|
|
1229
|
+
const embeddedV4 = () => [
|
|
1230
|
+
g(6) >> 8,
|
|
1231
|
+
g(6) & 255,
|
|
1232
|
+
g(7) >> 8,
|
|
1233
|
+
g(7) & 255
|
|
1234
|
+
];
|
|
1235
|
+
if ([
|
|
1236
|
+
0,
|
|
1237
|
+
1,
|
|
1238
|
+
2,
|
|
1239
|
+
3,
|
|
1240
|
+
4,
|
|
1241
|
+
5
|
|
1242
|
+
].every((i) => g(i) === 0)) return true;
|
|
1243
|
+
if ([
|
|
1244
|
+
0,
|
|
1245
|
+
1,
|
|
1246
|
+
2,
|
|
1247
|
+
3,
|
|
1248
|
+
4
|
|
1249
|
+
].every((i) => g(i) === 0) && g(5) === 65535) return isNonPublicIpv4(embeddedV4());
|
|
1250
|
+
if (g(0) === 100 && g(1) === 65435 && [
|
|
1251
|
+
2,
|
|
1252
|
+
3,
|
|
1253
|
+
4,
|
|
1254
|
+
5
|
|
1255
|
+
].every((i) => g(i) === 0)) return isNonPublicIpv4(embeddedV4());
|
|
1256
|
+
if ((g(0) & 65024) === 64512) return true;
|
|
1257
|
+
if ((g(0) & 65472) === 65152) return true;
|
|
1258
|
+
if ((g(0) & 65472) === 65216) return true;
|
|
1259
|
+
if ((g(0) & 65280) === 65280) return true;
|
|
1260
|
+
if (g(0) === 8193 && g(1) === 3512) return true;
|
|
1261
|
+
return false;
|
|
1262
|
+
};
|
|
1263
|
+
const LOCAL_NAME_SUFFIXES = [
|
|
1264
|
+
"localhost",
|
|
1265
|
+
"local",
|
|
1266
|
+
"internal",
|
|
1267
|
+
"home.arpa"
|
|
1268
|
+
];
|
|
1269
|
+
/** Checks a relay URL. Returns the parsed URL when it may be used. */
|
|
1270
|
+
const checkRelayUrl = (input, options = {}) => {
|
|
1271
|
+
let url;
|
|
1272
|
+
try {
|
|
1273
|
+
url = new URL(input);
|
|
1274
|
+
} catch {
|
|
1275
|
+
return fail("invalid_url", "relay URL is not a valid absolute URL");
|
|
1276
|
+
}
|
|
1277
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") return fail("insecure_scheme", "relay URL must use https");
|
|
1278
|
+
if (url.username !== "" || url.password !== "") return fail("credentials_in_url", "relay URL must not contain credentials; use relay headers");
|
|
1279
|
+
const hostname = url.hostname.toLowerCase().replace(/\.$/, "");
|
|
1280
|
+
if (options.allowInsecure !== true) {
|
|
1281
|
+
if (url.protocol !== "https:") return fail("insecure_scheme", "relay URL must use https");
|
|
1282
|
+
if (hostname.startsWith("[")) {
|
|
1283
|
+
const groups = parseIpv6(hostname.slice(1, -1));
|
|
1284
|
+
if (groups === void 0 || isNonPublicIpv6(groups)) return fail("private_address", "relay host is a private, loopback, link-local or unspecified address");
|
|
1285
|
+
} else {
|
|
1286
|
+
const v4 = parseIpv4(hostname);
|
|
1287
|
+
if (v4 !== void 0 && isNonPublicIpv4(v4)) return fail("private_address", "relay host is a private, loopback, link-local or unspecified address");
|
|
1288
|
+
if (v4 === void 0 && LOCAL_NAME_SUFFIXES.some((suffix) => hostMatchesSuffix(hostname, suffix))) return fail("local_name", "relay host is a local or internal name");
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
const host = url.host.toLowerCase();
|
|
1292
|
+
if ((options.selfHosts ?? []).some((self) => self.toLowerCase().replace(/\.$/, "") === host)) return fail("self_host", "relay URL points at manifold itself");
|
|
1293
|
+
const allowlist = options.hostAllowlist ?? [];
|
|
1294
|
+
if (allowlist.length > 0 && !allowlist.some((suffix) => hostMatchesSuffix(hostname, suffix))) return fail("not_allowlisted", "relay host is not in MANIFOLD_RELAY_HOST_ALLOWLIST");
|
|
1295
|
+
return {
|
|
1296
|
+
ok: true,
|
|
1297
|
+
url
|
|
1298
|
+
};
|
|
1299
|
+
};
|
|
1300
|
+
// src/core/verify/index.ts
|
|
1301
|
+
/**
|
|
1302
|
+
* One entry point for every verifier: `verify` (async) and `verifyEffect`
|
|
1303
|
+
* (Effect, failing with `VerificationError`).
|
|
1304
|
+
*/
|
|
1305
|
+
const verify = async (input) => {
|
|
1306
|
+
const { spec } = input;
|
|
1307
|
+
switch (spec.type) {
|
|
1308
|
+
case "hmac": return verifyHmac({
|
|
1309
|
+
...input,
|
|
1310
|
+
spec
|
|
1311
|
+
});
|
|
1312
|
+
case "token": return verifyToken({
|
|
1313
|
+
...input,
|
|
1314
|
+
spec
|
|
1315
|
+
});
|
|
1316
|
+
case "jwt": return verifyJwt({
|
|
1317
|
+
...input,
|
|
1318
|
+
spec
|
|
1319
|
+
});
|
|
1320
|
+
case "none": return input.allowUnverified === true ? verified() : rejected("unverified_not_allowed", "the source does not set allowUnverified");
|
|
1321
|
+
}
|
|
1322
|
+
};
|
|
1323
|
+
/** A failed verification. `detail` never contains secrets, signatures or tokens. */
|
|
1324
|
+
var VerificationError = class extends Schema.TaggedError()("VerificationError", {
|
|
1325
|
+
reason: RejectionReason,
|
|
1326
|
+
detail: Schema.String
|
|
1327
|
+
}) {
|
|
1328
|
+
get message() {
|
|
1329
|
+
return `${this.reason}: ${this.detail}`;
|
|
1330
|
+
}
|
|
1331
|
+
};
|
|
1332
|
+
const verifyEffect = (input) => Effect.promise(() => verify(input)).pipe(Effect.flatMap((result) => VerifyResult.$match(result, {
|
|
1333
|
+
Verified: (ok) => Effect.succeed(ok),
|
|
1334
|
+
Rejected: ({ reason, detail }) => Effect.fail(new VerificationError({
|
|
1335
|
+
reason,
|
|
1336
|
+
detail
|
|
1337
|
+
}))
|
|
1338
|
+
})));
|
|
1339
|
+
export { ALWAYS_REDACTED, ApplyChanges, ApplyResult, AttemptId, AttemptOutcome, AttemptRecord, AttemptStatus, AuditAction, AuditRecord, AutoPauseThreshold, BODYLESS_METHODS, BodyPath, CANCELLABLE, ClaimRequirement, ConfigDocument, ConfigRelay, ConfigRoute, ConfigSource, Count, DEFAULT_JWKS_URLS, DedupeWindowSeconds, DeliveryDetail, DeliveryId, DeliveryRecord, DeliveryStatus, ERROR_STATUS, ErrorBody, ErrorCode, EventTypeGlob, Extractor, ExtractorPart, FINISHED_DELIVERY_STATUSES, Fingerprint, GOOGLE_JWKS_URL, HOP_BY_HOP_HEADERS, HandshakeSpec, HashAlgorithm, HeaderMap, HeaderName, HmacVerify, ID_PREFIXES, IngestAck, IssuedSigningSecret, JsonChallengeHandshake, Jwk, Jwks, JwksCache, JwtAlgorithm, JwtVerify, KeyringError, KiB, LIMITS, LOCAL_HEADER, LOCAL_ID_PREFIX, ListenTokenId, ListenTokenInfo, ListenerInfo, ListenerName, ListenerSessionId, ListenersSetting, LocalAttemptKind, LocalAttemptRecord, LocalId, MaxBodyBytes, MiB, Millis, NoneVerify, PRESETS, PRESET_LIST, Page, PauseReason, PayloadTemplate, Preset, PresetId, PresetResponse, Principal, REDACTED_RESPONSE_HEADERS, REDACTED_VALUE_PATTERN, RETRYABLE_BY_OPERATOR, RejectionCounter, RejectionReason, RejectionRecord, Rejections, RelayConfig, RelayId, RelayTimeoutMs, RelayView, RequestDetail, RequestId, RequestRecord, RequestStatus, ResolvedVerification, RetentionDays, RetryPolicy, Revision, RouteConfig, RouteId, RouteState, RouteView, SIGNING_SECRET_PREFIX, STANDARD_WEBHOOK_HEADERS, SecretBox, SecretBoxError, SecretEncoding, SecretHeaderInfo, SecretHeaders, SecretInfo, SecretValue, SignatureEncoding, SignatureFormat, SignedContext, SigningSecretInfo, SourceConfig, SourceKey, SourceStats, SourceView, TIMINGS, TargetLabel, TokenVerify, Tolerance, ULID_PATTERN, ValueSource, VerificationError, VerifyOverride, VerifyResult, VerifySpec, accessJwksUrl, backoffDelayMs, buildOutboundRequest, buildRelayHeaders, buildSignedPayload, checkRelayUrl, classifyOutcome, computeHmacSignature, concatBytes, decideNext, decodeContext, decodeHmacSecret, encodeContext, extract, extractAll, extractSignatures, fingerprint, fromBase64, fromBase64Url, fromHex, generateSigningSecret, getHeader, getPath, getPreset, headerEntries, headerNames, hmac, hostMatchesSuffix, idAt, idPattern, idTime, importHmacKey, isAllowedJwksUrl, isDroppedOnForward, isId, isLocalId, isNonPublicIpv4, isNonPublicIpv6, isReservedRelayHeader, makeIdGenerator, makeJwksCache, matchHandshake, matchesEventTypes, matchesGlob, matchingRoutes, minIdAt, needsReseal, newId, newLocalId, nextConsecutiveFailures, nextStatus, openJson, openSecret, parseHostAllowlist, parseJsonBody, parseKeyring, parseKvList, parseRetryAfter, presetVerification, randomBytes, readCredential, redactForStorage, redactResponseHeaders, redactedHeaderNames, redactedValue, rejected, relayConfigFields, relaySignatureHeaders, resealSecret, resolveSource, resolveVerifySpec, routeConfigFields, sealJson, sealSecret, sealedKeyId, secretAad, secretsEqual, sendWebhook, sha256, sha256Hex, shouldAutoPause, signHmac, signStandardWebhook, signWebhook, signatureHeaders, signingKeyBytes, sourceConfigFields, timingSafeEqual, toBase64, toBase64Url, toBufferSource, toHex, utf8Decode, utf8Encode, verified, verify, verifyEffect, verifyHmac, verifyJwt, verifyJwtToken, verifyRelayRequest, verifyStandardWebhook, verifyToken };
|