@segmentstream/ontology 0.125.0 → 0.127.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.
@@ -1,6 +1,6 @@
1
1
  import { Effect, Redacted } from "effect";
2
2
  import type { HttpServerRequest } from "effect/unstable/http";
3
- import type { WebhookSignatureScheme } from "../webhooks.js";
3
+ import { type WebhookHmacAlgorithm, type WebhookHmacFormat, type WebhookSignatureEncoding } from "../webhooks.js";
4
4
  /**
5
5
  * The pieces of the webhook route that do not need the router: reading the body, the signature
6
6
  * schemes, the backend's verification and the throttle on refused signatures.
@@ -27,8 +27,10 @@ export type WebhookVerification = {
27
27
  export interface WebhookVerifyRequest {
28
28
  /** The workspace secret's name. */
29
29
  readonly secret: string;
30
- readonly algorithm: "sha256";
31
- readonly encoding: "hex";
30
+ readonly algorithm: WebhookHmacAlgorithm;
31
+ readonly encoding: WebhookSignatureEncoding;
32
+ /** How the secret's value becomes the key, when not as its UTF-8 bytes. */
33
+ readonly key?: WebhookHmacFormat["key"];
32
34
  /** The bytes the provider signed. */
33
35
  readonly message: Uint8Array;
34
36
  /** The signatures the delivery carried; any that matches is enough. */
@@ -40,7 +42,7 @@ export interface WebhookVerifyRequest {
40
42
  /** Checks webhook signatures. The service calls SegmentStream's backend by default. */
41
43
  export type WebhookVerifier = (request: WebhookVerifyRequest) => Promise<WebhookVerification>;
42
44
  /** Registration checks return only a match; the stored verify token never leaves the backend. */
43
- export type WebhookTokenVerifyRequest = Omit<WebhookVerifyRequest, "algorithm" | "encoding" | "message" | "signatures"> & {
45
+ export type WebhookTokenVerifyRequest = Omit<WebhookVerifyRequest, "algorithm" | "encoding" | "key" | "message" | "signatures"> & {
44
46
  readonly token: string;
45
47
  };
46
48
  export type WebhookTokenVerifier = (request: WebhookTokenVerifyRequest) => Promise<WebhookVerification>;
@@ -92,6 +94,12 @@ export type SignedContent = {
92
94
  export type SignatureScheme = (headers: Readonly<Record<string, string | undefined>>, body: Uint8Array, receivedAt: Date) => SignedContent;
93
95
  /** How far Stripe's `t` may be from the time the delivery arrived, in seconds. */
94
96
  export declare const STRIPE_TOLERANCE_SECONDS = 300;
97
+ /**
98
+ * The scheme a format describes: it finds the candidate signatures and the timestamp in the
99
+ * delivery's headers, refuses a stale timestamp, and assembles the signed bytes. The HMAC itself
100
+ * is SegmentStream's, which holds the secret.
101
+ */
102
+ export declare function hmacSignature(format: WebhookHmacFormat): SignatureScheme;
95
103
  /**
96
104
  * Stripe's `Stripe-Signature`: `t=<unix seconds>` and one or more `v1=<hex>`. The signed bytes are
97
105
  * `<t>.` followed by the raw body; the HMAC is SHA-256 keyed with the whole `whsec_…` string.
@@ -99,8 +107,16 @@ export declare const STRIPE_TOLERANCE_SECONDS = 300;
99
107
  export declare const stripeSignature: SignatureScheme;
100
108
  /** Meta signs exactly the raw body; its app secret stays in the backend. */
101
109
  export declare const metaSignature: SignatureScheme;
102
- /** Every scheme the SDK checks, by the name a declaration uses. */
103
- export declare const SIGNATURE_SCHEMES: Readonly<Record<WebhookSignatureScheme, SignatureScheme>>;
110
+ /**
111
+ * What checks a manifest signature: its format and that format's scheme, or `undefined` for a
112
+ * scheme this SDK does not know.
113
+ */
114
+ export declare function signatureCheck(signature: {
115
+ readonly scheme: string;
116
+ }): {
117
+ readonly format: WebhookHmacFormat;
118
+ readonly scheme: SignatureScheme;
119
+ } | undefined;
104
120
  /**
105
121
  * The request's body, read up to `limit` bytes: `too_large` without reading further, or
106
122
  * `unreadable` when the client went away.
@@ -1,4 +1,5 @@
1
1
  import { Effect, Redacted } from "effect";
2
+ import { META_SIGNATURE_FORMAT, STRIPE_SIGNATURE_FORMAT, WEBHOOK_HMAC_DIGEST_BYTES, WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS, webhookHmacFormat, } from "../webhooks.js";
2
3
  import { fixedWindowLimiter } from "./rate-limit.js";
3
4
  /** How long the service waits for the backend's answer before answering 503. */
4
5
  export const WEBHOOK_VERIFY_TIMEOUT_MS = 3_000;
@@ -12,6 +13,14 @@ export function deployedWebhookVerifier(environment, fetchImpl = fetch) {
12
13
  return (request) => verify(request, {
13
14
  algorithm: request.algorithm,
14
15
  encoding: request.encoding,
16
+ ...(request.key === undefined
17
+ ? {}
18
+ : {
19
+ key: {
20
+ decode: request.key.decode,
21
+ ...(request.key.prefix === undefined ? {} : { prefix: request.key.prefix }),
22
+ },
23
+ }),
15
24
  message: Buffer.from(request.message).toString("base64"),
16
25
  signatures: request.signatures,
17
26
  });
@@ -89,64 +98,136 @@ export function deployedSecretVerifier(environment, operation, fetchImpl) {
89
98
  };
90
99
  }
91
100
  /** How far Stripe's `t` may be from the time the delivery arrived, in seconds. */
92
- export const STRIPE_TOLERANCE_SECONDS = 300;
101
+ export const STRIPE_TOLERANCE_SECONDS = WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS;
93
102
  /** The most signatures of one delivery that are sent to the backend. */
94
103
  const MAX_SIGNATURES = 5;
104
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
105
+ /** A signature written as the format says and as long as its digest, normalized; else undefined. */
106
+ function signatureCandidate(value, format) {
107
+ const bytes = WEBHOOK_HMAC_DIGEST_BYTES[format.algorithm];
108
+ if (format.encoding === "hex") {
109
+ return value.length === bytes * 2 && /^[0-9a-f]+$/i.test(value)
110
+ ? value.toLowerCase()
111
+ : undefined;
112
+ }
113
+ const unpadded = value.replace(/=+$/, "");
114
+ return BASE64.test(value) &&
115
+ unpadded.length === Math.ceil((bytes * 4) / 3) &&
116
+ (value.length === unpadded.length || value.length === Math.ceil(bytes / 3) * 4)
117
+ ? value
118
+ : undefined;
119
+ }
120
+ /** A header's entries, such as `t=1,v1=ab`, as name and value pairs in order. */
121
+ function headerEntries(header, entries) {
122
+ return header.split(entries.separator).flatMap((part) => {
123
+ const trimmed = part.trim();
124
+ const at = trimmed.indexOf(entries.assign);
125
+ return at <= 0 ? [] : [[trimmed.slice(0, at).trim(), trimmed.slice(at + 1).trim()]];
126
+ });
127
+ }
95
128
  /**
96
- * Stripe's `Stripe-Signature`: `t=<unix seconds>` and one or more `v1=<hex>`. The signed bytes are
97
- * `<t>.` followed by the raw body; the HMAC is SHA-256 keyed with the whole `whsec_…` string.
129
+ * The scheme a format describes: it finds the candidate signatures and the timestamp in the
130
+ * delivery's headers, refuses a stale timestamp, and assembles the signed bytes. The HMAC itself
131
+ * is SegmentStream's, which holds the secret.
98
132
  */
99
- export const stripeSignature = (headers, body, receivedAt) => {
100
- const header = headers["stripe-signature"];
101
- if (header === undefined || header.trim() === "") {
102
- return { ok: false, reason: "signature_missing" };
103
- }
104
- let timestamp;
105
- const signatures = [];
106
- for (const part of header.split(",")) {
107
- const separator = part.indexOf("=");
108
- if (separator <= 0) {
109
- continue;
133
+ export function hmacSignature(format) {
134
+ const encoder = new TextEncoder();
135
+ return (headers, body, receivedAt) => {
136
+ const header = headers[format.signatures.header];
137
+ if (header === undefined || header.trim() === "") {
138
+ return { ok: false, reason: "signature_missing" };
139
+ }
140
+ const signatures = [];
141
+ const declared = format.signatures.entries;
142
+ const entries = declared === undefined ? undefined : headerEntries(header, declared);
143
+ if (entries !== undefined && declared !== undefined) {
144
+ for (const [name, value] of entries) {
145
+ const candidate = name === declared.name ? signatureCandidate(value, format) : undefined;
146
+ if (candidate !== undefined && signatures.length < MAX_SIGNATURES) {
147
+ signatures.push(candidate);
148
+ }
149
+ }
110
150
  }
111
- const key = part.slice(0, separator).trim();
112
- const value = part.slice(separator + 1).trim();
113
- if (key === "t") {
114
- timestamp = value;
151
+ else {
152
+ const prefix = format.signatures.prefix ?? "";
153
+ const value = header.trim();
154
+ if (value.slice(0, prefix.length).toLowerCase() !== prefix.toLowerCase()) {
155
+ return { ok: false, reason: "signature_malformed" };
156
+ }
157
+ const candidate = signatureCandidate(value.slice(prefix.length), format);
158
+ if (candidate !== undefined) {
159
+ signatures.push(candidate);
160
+ }
115
161
  }
116
- else if (key === "v1" &&
117
- /^[0-9a-f]{64}$/i.test(value) &&
118
- signatures.length < MAX_SIGNATURES) {
119
- signatures.push(value.toLowerCase());
162
+ const declaredTimestamp = format.timestamp;
163
+ let timestamp;
164
+ if (declaredTimestamp !== undefined) {
165
+ timestamp =
166
+ declaredTimestamp.entry !== undefined
167
+ ? entries?.find(([name]) => name === declaredTimestamp.entry)?.[1]
168
+ : headers[declaredTimestamp.header ?? ""]?.trim();
169
+ const milliseconds = declaredTimestamp.unit === "milliseconds";
170
+ if (timestamp === undefined ||
171
+ !(milliseconds ? /^\d{1,15}$/ : /^\d{1,12}$/).test(timestamp)) {
172
+ return { ok: false, reason: "signature_malformed" };
173
+ }
120
174
  }
121
- }
122
- if (timestamp === undefined || !/^\d{1,12}$/.test(timestamp) || signatures.length === 0) {
123
- return { ok: false, reason: "signature_malformed" };
124
- }
125
- if (Math.abs(receivedAt.getTime() / 1000 - Number(timestamp)) > STRIPE_TOLERANCE_SECONDS) {
126
- return { ok: false, reason: "signature_stale" };
127
- }
128
- const prefix = new TextEncoder().encode(`${timestamp}.`);
129
- const message = new Uint8Array(prefix.length + body.length);
130
- message.set(prefix);
131
- message.set(body, prefix.length);
132
- return { ok: true, message, signatures };
133
- };
175
+ if (signatures.length === 0) {
176
+ return { ok: false, reason: "signature_malformed" };
177
+ }
178
+ if (declaredTimestamp !== undefined && timestamp !== undefined) {
179
+ const signedAt = Number(timestamp) / (declaredTimestamp.unit === "milliseconds" ? 1000 : 1);
180
+ const tolerance = declaredTimestamp.tolerance ?? WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS;
181
+ if (Math.abs(receivedAt.getTime() / 1000 - signedAt) > tolerance) {
182
+ return { ok: false, reason: "signature_stale" };
183
+ }
184
+ }
185
+ const parts = [];
186
+ for (const part of format.message ?? [{ body: true }]) {
187
+ if (typeof part === "string") {
188
+ parts.push(encoder.encode(part));
189
+ }
190
+ else if ("body" in part) {
191
+ parts.push(body);
192
+ }
193
+ else if ("timestamp" in part) {
194
+ parts.push(encoder.encode(timestamp ?? ""));
195
+ }
196
+ else {
197
+ const value = headers[part.header];
198
+ if (value === undefined) {
199
+ return { ok: false, reason: "signature_malformed" };
200
+ }
201
+ parts.push(encoder.encode(value));
202
+ }
203
+ }
204
+ if (parts.length === 1 && parts[0] === body) {
205
+ return { ok: true, message: body, signatures };
206
+ }
207
+ const message = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
208
+ let offset = 0;
209
+ for (const part of parts) {
210
+ message.set(part, offset);
211
+ offset += part.byteLength;
212
+ }
213
+ return { ok: true, message, signatures };
214
+ };
215
+ }
216
+ /**
217
+ * Stripe's `Stripe-Signature`: `t=<unix seconds>` and one or more `v1=<hex>`. The signed bytes are
218
+ * `<t>.` followed by the raw body; the HMAC is SHA-256 keyed with the whole `whsec_…` string.
219
+ */
220
+ export const stripeSignature = hmacSignature(STRIPE_SIGNATURE_FORMAT);
134
221
  /** Meta signs exactly the raw body; its app secret stays in the backend. */
135
- export const metaSignature = (headers, body) => {
136
- const header = headers["x-hub-signature-256"];
137
- if (header === undefined || header === "") {
138
- return { ok: false, reason: "signature_missing" };
139
- }
140
- if (!/^sha256=[0-9a-f]{64}$/i.test(header)) {
141
- return { ok: false, reason: "signature_malformed" };
142
- }
143
- return { ok: true, message: body, signatures: [header.slice(7).toLowerCase()] };
144
- };
145
- /** Every scheme the SDK checks, by the name a declaration uses. */
146
- export const SIGNATURE_SCHEMES = {
147
- stripe: stripeSignature,
148
- meta: metaSignature,
149
- };
222
+ export const metaSignature = hmacSignature(META_SIGNATURE_FORMAT);
223
+ /**
224
+ * What checks a manifest signature: its format and that format's scheme, or `undefined` for a
225
+ * scheme this SDK does not know.
226
+ */
227
+ export function signatureCheck(signature) {
228
+ const format = webhookHmacFormat(signature);
229
+ return format === undefined ? undefined : { format, scheme: hmacSignature(format) };
230
+ }
150
231
  /**
151
232
  * The request's body, read up to `limit` bytes: `too_large` without reading further, or
152
233
  * `unreadable` when the client went away.
@@ -16,7 +16,7 @@ import { ActionRejected, PermissionDenied, } from "../errors.js";
16
16
  import { isActionTrigger, isCronTrigger, isWebhookTrigger, } from "../manifest.js";
17
17
  import { webhookTokenMatches } from "../webhook-token.js";
18
18
  import { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_VERIFICATION_CHARS, WEBHOOK_BASE_PATH, webhookPath, } from "../webhooks.js";
19
- import { readWebhookBody, SIGNATURE_SCHEMES, signatureRefusals, utf8Text, } from "./webhooks.js";
19
+ import { readWebhookBody, signatureCheck, signatureRefusals, utf8Text, } from "./webhooks.js";
20
20
  import { clientAddress } from "./rate-limit.js";
21
21
  import { isAllowed, workflowPermission } from "../permissions.js";
22
22
  import { OntologyActions, OntologyReads, OntologyWrites, } from "../runtime.js";
@@ -1348,11 +1348,12 @@ export function workflowsLayer(options) {
1348
1348
  if (wait !== undefined) {
1349
1349
  return yield* refuse("signature_throttled", 429, { "retry-after": String(wait) });
1350
1350
  }
1351
- const scheme = SIGNATURE_SCHEMES[signature.scheme];
1352
- if (scheme === undefined || options.webhookVerifier === undefined) {
1351
+ const checked = signatureCheck(signature);
1352
+ if (checked === undefined || options.webhookVerifier === undefined) {
1353
1353
  return yield* refuse("scheme_unavailable", 503);
1354
1354
  }
1355
- const content = scheme(request.headers, body, receivedAt);
1355
+ const { format } = checked;
1356
+ const content = checked.scheme(request.headers, body, receivedAt);
1356
1357
  if (!content.ok) {
1357
1358
  refusals.refused(client);
1358
1359
  return yield* refuse(content.reason, 401);
@@ -1360,8 +1361,9 @@ export function workflowsLayer(options) {
1360
1361
  const verifier = options.webhookVerifier;
1361
1362
  const verified = yield* Effect.promise(() => verifier({
1362
1363
  secret: signature.secret,
1363
- algorithm: "sha256",
1364
- encoding: "hex",
1364
+ algorithm: format.algorithm,
1365
+ encoding: format.encoding,
1366
+ ...(format.key === undefined ? {} : { key: format.key }),
1365
1367
  message: content.message,
1366
1368
  signatures: content.signatures,
1367
1369
  identityToken: requestIdentityToken(request),
@@ -4,9 +4,112 @@ import { Schema } from "effect";
4
4
  * Node built-in, so the workflows entry may re-export it; the token derivation, which needs
5
5
  * `node:crypto`, is `webhook-token.ts`.
6
6
  */
7
- /** The signature formats a webhook trigger can check, each a provider's published format. */
8
- export declare const WEBHOOK_SIGNATURE_SCHEMES: readonly ["stripe", "meta"];
7
+ /**
8
+ * The signature schemes a webhook trigger can check: `hmac` declares a provider's HMAC format
9
+ * with the trigger; `stripe` and `meta` name two published formats.
10
+ */
11
+ export declare const WEBHOOK_SIGNATURE_SCHEMES: readonly ["stripe", "meta", "hmac"];
9
12
  export type WebhookSignatureScheme = (typeof WEBHOOK_SIGNATURE_SCHEMES)[number];
13
+ /** The hashes an HMAC signature may use. */
14
+ export declare const WEBHOOK_HMAC_ALGORITHMS: readonly ["sha1", "sha256", "sha512"];
15
+ export type WebhookHmacAlgorithm = (typeof WEBHOOK_HMAC_ALGORITHMS)[number];
16
+ /** How a provider writes its signatures. Hex compares in either case. */
17
+ export declare const WEBHOOK_SIGNATURE_ENCODINGS: readonly ["hex", "base64"];
18
+ export type WebhookSignatureEncoding = (typeof WEBHOOK_SIGNATURE_ENCODINGS)[number];
19
+ /** The bytes of each algorithm's digest, which a signature must decode to. */
20
+ export declare const WEBHOOK_HMAC_DIGEST_BYTES: Readonly<Record<WebhookHmacAlgorithm, number>>;
21
+ /** One piece of the signed bytes: text, the raw body, a header's value or the timestamp. */
22
+ export type WebhookSignedPart = string | {
23
+ readonly body: true;
24
+ } | {
25
+ readonly header: string;
26
+ } | {
27
+ readonly timestamp: true;
28
+ };
29
+ /**
30
+ * A provider's HMAC signature format: which bytes it signs, where its signatures travel and how
31
+ * they are written. The ontology service reads them from each delivery; SegmentStream computes
32
+ * the HMAC with the workspace secret, which never leaves it.
33
+ */
34
+ export interface WebhookHmacFormat {
35
+ readonly algorithm: WebhookHmacAlgorithm;
36
+ readonly encoding: WebhookSignatureEncoding;
37
+ /**
38
+ * How the secret's value becomes the HMAC key. Omitted: its UTF-8 bytes. `decode: "base64"`
39
+ * decodes the value after `prefix`, when it starts with it, such as Svix's `whsec_…`.
40
+ */
41
+ readonly key?: {
42
+ readonly decode: "base64";
43
+ readonly prefix?: string | undefined;
44
+ } | undefined;
45
+ /**
46
+ * The header that carries the signatures: the whole value after an optional `prefix`, such as
47
+ * `sha256=`, or with `entries` a list such as `t=…,v1=…`, whose entries called `name` are the
48
+ * candidates.
49
+ */
50
+ readonly signatures: {
51
+ readonly header: string;
52
+ readonly prefix?: string | undefined;
53
+ readonly entries?: {
54
+ readonly separator: "," | ";" | " ";
55
+ readonly assign: "=" | ",";
56
+ readonly name: string;
57
+ } | undefined;
58
+ };
59
+ /**
60
+ * When the provider signed the delivery, in a `header` of its own or an `entry` of the signature
61
+ * header; a delivery further than `tolerance` seconds from its arrival is stale.
62
+ */
63
+ readonly timestamp?: {
64
+ readonly header?: string | undefined;
65
+ readonly entry?: string | undefined;
66
+ readonly unit?: "seconds" | "milliseconds" | undefined;
67
+ readonly tolerance?: number | undefined;
68
+ } | undefined;
69
+ /** The signed bytes in order; the raw body alone when omitted. */
70
+ readonly message?: ReadonlyArray<WebhookSignedPart> | undefined;
71
+ }
72
+ /** How far a signed timestamp may be from a delivery's arrival by default, in seconds. */
73
+ export declare const WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
74
+ /** The widest tolerance a format may declare, in seconds. */
75
+ export declare const MAX_WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 3600;
76
+ /** The most parts a format's signed message may have. */
77
+ export declare const MAX_WEBHOOK_MESSAGE_PARTS = 8;
78
+ /** The longest text part of a signed message. */
79
+ export declare const MAX_WEBHOOK_MESSAGE_TEXT = 64;
80
+ /** Stripe's `Stripe-Signature`: `t=<seconds>,v1=<hex>`, over `<t>.<raw body>`. */
81
+ export declare const STRIPE_SIGNATURE_FORMAT: WebhookHmacFormat;
82
+ /** Meta's `X-Hub-Signature-256: sha256=<hex>`, over the raw body. */
83
+ export declare const META_SIGNATURE_FORMAT: WebhookHmacFormat;
84
+ /**
85
+ * The format a declared or manifest signature checks: the named schemes' published formats, or
86
+ * the one an `hmac` signature declares. `undefined` for a scheme this SDK does not know.
87
+ */
88
+ export declare function webhookHmacFormat(signature: {
89
+ readonly scheme: string;
90
+ }): WebhookHmacFormat | undefined;
91
+ /** A problem with a signature declaration: the key it concerns, under `signature`, and why. */
92
+ export interface WebhookSignatureProblem {
93
+ readonly path: string;
94
+ readonly message: string;
95
+ }
96
+ /**
97
+ * Every problem of a webhook trigger's `signature`, as `check` and SegmentStream's publication
98
+ * check report them: a known scheme and a workspace secret's name, and for `hmac` a complete
99
+ * format. Empty when the declaration is valid.
100
+ */
101
+ export declare function webhookSignatureProblems(signature: unknown): ReadonlyArray<WebhookSignatureProblem>;
102
+ /**
103
+ * A valid signature declaration as the manifest records it: `{ scheme, secret }` for a named
104
+ * scheme, and for `hmac` its format's settings, each written only when declared.
105
+ */
106
+ export declare function webhookSignatureManifest(signature: {
107
+ readonly scheme: string;
108
+ readonly secret: string;
109
+ } & Partial<WebhookHmacFormat>): {
110
+ readonly scheme: string;
111
+ readonly secret: string;
112
+ } & Partial<WebhookHmacFormat>;
10
113
  /** The most webhook triggers one ontology may declare across its workflows. */
11
114
  export declare const MAX_WEBHOOKS = 20;
12
115
  /** The most request headers one webhook trigger may pass to its workflow. */