@segmentstream/ontology 0.124.0 → 0.126.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/webhooks.js CHANGED
@@ -5,8 +5,299 @@ import { p } from "./property.js";
5
5
  * Node built-in, so the workflows entry may re-export it; the token derivation, which needs
6
6
  * `node:crypto`, is `webhook-token.ts`.
7
7
  */
8
- /** The signature formats a webhook trigger can check, each a provider's published format. */
9
- export const WEBHOOK_SIGNATURE_SCHEMES = ["stripe", "meta"];
8
+ /**
9
+ * The signature schemes a webhook trigger can check: `hmac` declares a provider's HMAC format
10
+ * with the trigger; `stripe` and `meta` name two published formats.
11
+ */
12
+ export const WEBHOOK_SIGNATURE_SCHEMES = ["stripe", "meta", "hmac"];
13
+ /** The hashes an HMAC signature may use. */
14
+ export const WEBHOOK_HMAC_ALGORITHMS = ["sha1", "sha256", "sha512"];
15
+ /** How a provider writes its signatures. Hex compares in either case. */
16
+ export const WEBHOOK_SIGNATURE_ENCODINGS = ["hex", "base64"];
17
+ /** The bytes of each algorithm's digest, which a signature must decode to. */
18
+ export const WEBHOOK_HMAC_DIGEST_BYTES = {
19
+ sha1: 20,
20
+ sha256: 32,
21
+ sha512: 64,
22
+ };
23
+ /** How far a signed timestamp may be from a delivery's arrival by default, in seconds. */
24
+ export const WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
25
+ /** The widest tolerance a format may declare, in seconds. */
26
+ export const MAX_WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS = 3_600;
27
+ /** The most parts a format's signed message may have. */
28
+ export const MAX_WEBHOOK_MESSAGE_PARTS = 8;
29
+ /** The longest text part of a signed message. */
30
+ export const MAX_WEBHOOK_MESSAGE_TEXT = 64;
31
+ /** Stripe's `Stripe-Signature`: `t=<seconds>,v1=<hex>`, over `<t>.<raw body>`. */
32
+ export const STRIPE_SIGNATURE_FORMAT = {
33
+ algorithm: "sha256",
34
+ encoding: "hex",
35
+ signatures: {
36
+ header: "stripe-signature",
37
+ entries: { separator: ",", assign: "=", name: "v1" },
38
+ },
39
+ timestamp: { entry: "t", tolerance: WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS },
40
+ message: [{ timestamp: true }, ".", { body: true }],
41
+ };
42
+ /** Meta's `X-Hub-Signature-256: sha256=<hex>`, over the raw body. */
43
+ export const META_SIGNATURE_FORMAT = {
44
+ algorithm: "sha256",
45
+ encoding: "hex",
46
+ signatures: { header: "x-hub-signature-256", prefix: "sha256=" },
47
+ };
48
+ /**
49
+ * The format a declared or manifest signature checks: the named schemes' published formats, or
50
+ * the one an `hmac` signature declares. `undefined` for a scheme this SDK does not know.
51
+ */
52
+ export function webhookHmacFormat(signature) {
53
+ switch (signature.scheme) {
54
+ case "stripe":
55
+ return STRIPE_SIGNATURE_FORMAT;
56
+ case "meta":
57
+ return META_SIGNATURE_FORMAT;
58
+ case "hmac":
59
+ return signature;
60
+ default:
61
+ return undefined;
62
+ }
63
+ }
64
+ const FORMAT_KEYS = ["algorithm", "encoding", "key", "signatures", "timestamp", "message"];
65
+ const PRINTABLE = /^[\x21-\x7e]{1,16}$/;
66
+ const ENTRY_NAME = /^[A-Za-z0-9_.-]{1,16}$/;
67
+ function isRecord(value) {
68
+ return typeof value === "object" && value !== null && !Array.isArray(value);
69
+ }
70
+ function unknownKeys(value, known) {
71
+ return Object.keys(value).filter((key) => !known.includes(key));
72
+ }
73
+ /**
74
+ * Every problem of a webhook trigger's `signature`, as `check` and SegmentStream's publication
75
+ * check report them: a known scheme and a workspace secret's name, and for `hmac` a complete
76
+ * format. Empty when the declaration is valid.
77
+ */
78
+ export function webhookSignatureProblems(signature) {
79
+ const problems = [];
80
+ const report = (path, message) => problems.push({ path, message });
81
+ if (!isRecord(signature)) {
82
+ report("", "signature is { scheme, secret }, or omitted for a provider that signs nothing.");
83
+ return problems;
84
+ }
85
+ const { scheme, secret } = signature;
86
+ if (!WEBHOOK_SIGNATURE_SCHEMES.includes(scheme)) {
87
+ report("scheme", `${JSON.stringify(scheme) ?? "undefined"} is not a signature scheme; use one of ` +
88
+ `${WEBHOOK_SIGNATURE_SCHEMES.join(", ")}, or omit signature for a provider that signs ` +
89
+ "nothing.");
90
+ }
91
+ if (typeof secret !== "string" || !WORKSPACE_SECRET_NAME.test(secret)) {
92
+ report("secret", `${JSON.stringify(secret) ?? "undefined"} is not a workspace secret name; name the ` +
93
+ "secret that holds the provider's signing secret, such as stripe-webhook-signing-secret.");
94
+ }
95
+ if (scheme !== "hmac") {
96
+ for (const key of unknownKeys(signature, ["scheme", "secret"])) {
97
+ report(key, FORMAT_KEYS.includes(key)
98
+ ? `${key} declares a format, which only scheme "hmac" takes.`
99
+ : `${key} is not a signature setting.`);
100
+ }
101
+ return problems;
102
+ }
103
+ for (const key of unknownKeys(signature, ["scheme", "secret", ...FORMAT_KEYS])) {
104
+ report(key, `${key} is not a signature setting.`);
105
+ }
106
+ if (!WEBHOOK_HMAC_ALGORITHMS.includes(signature.algorithm)) {
107
+ report("algorithm", `algorithm is one of ${WEBHOOK_HMAC_ALGORITHMS.join(", ")}.`);
108
+ }
109
+ if (!WEBHOOK_SIGNATURE_ENCODINGS.includes(signature.encoding)) {
110
+ report("encoding", `encoding is one of ${WEBHOOK_SIGNATURE_ENCODINGS.join(", ")}.`);
111
+ }
112
+ const { key } = signature;
113
+ if (key !== undefined &&
114
+ (!isRecord(key) ||
115
+ key.decode !== "base64" ||
116
+ unknownKeys(key, ["decode", "prefix"]).length > 0 ||
117
+ (key.prefix !== undefined && (typeof key.prefix !== "string" || !PRINTABLE.test(key.prefix))))) {
118
+ report("key", 'key is { decode: "base64" }, with an optional prefix of up to 16 printable characters, ' +
119
+ "such as whsec_.");
120
+ }
121
+ const signatures = signature.signatures;
122
+ let entries = false;
123
+ if (!isRecord(signatures) ||
124
+ unknownKeys(signatures, ["header", "prefix", "entries"]).length > 0) {
125
+ report("signatures", "signatures is { header, prefix } or { header, entries }.");
126
+ }
127
+ else {
128
+ const headerProblem = signedHeaderProblem(signatures.header);
129
+ if (headerProblem !== undefined) {
130
+ report("signatures.header", headerProblem);
131
+ }
132
+ if (signatures.prefix !== undefined &&
133
+ (typeof signatures.prefix !== "string" || !PRINTABLE.test(signatures.prefix))) {
134
+ report("signatures.prefix", "prefix is up to 16 printable characters, such as sha256=.");
135
+ }
136
+ if (signatures.entries !== undefined) {
137
+ const declared = signatures.entries;
138
+ entries = true;
139
+ if (signatures.prefix !== undefined) {
140
+ report("signatures", "signatures takes a prefix or entries, not both.");
141
+ }
142
+ if (!isRecord(declared) ||
143
+ unknownKeys(declared, ["separator", "assign", "name"]).length > 0 ||
144
+ ![",", ";", " "].includes(declared.separator) ||
145
+ !["=", ","].includes(declared.assign) ||
146
+ declared.separator === declared.assign ||
147
+ typeof declared.name !== "string" ||
148
+ !ENTRY_NAME.test(declared.name)) {
149
+ report("signatures.entries", 'entries is { separator: ",", ";" or " ", assign: "=" or ",", name }, with a ' +
150
+ 'different separator and assign, such as Stripe\'s { separator: ",", assign: "=", ' +
151
+ 'name: "v1" }.');
152
+ }
153
+ }
154
+ }
155
+ const timestamp = signature.timestamp;
156
+ const timed = timestamp !== undefined;
157
+ if (timed) {
158
+ if (!isRecord(timestamp) ||
159
+ unknownKeys(timestamp, ["header", "entry", "unit", "tolerance"]).length > 0 ||
160
+ (timestamp.header === undefined) === (timestamp.entry === undefined)) {
161
+ report("timestamp", "timestamp is { header } or { entry }, with an optional unit and tolerance.");
162
+ }
163
+ else {
164
+ if (timestamp.header !== undefined) {
165
+ const headerProblem = signedHeaderProblem(timestamp.header);
166
+ if (headerProblem !== undefined) {
167
+ report("timestamp.header", headerProblem);
168
+ }
169
+ }
170
+ if (timestamp.entry !== undefined &&
171
+ (typeof timestamp.entry !== "string" || !ENTRY_NAME.test(timestamp.entry) || !entries)) {
172
+ report("timestamp.entry", "entry names an entry of the signature header, which then declares entries.");
173
+ }
174
+ if (timestamp.unit !== undefined &&
175
+ timestamp.unit !== "seconds" &&
176
+ timestamp.unit !== "milliseconds") {
177
+ report("timestamp.unit", 'unit is "seconds" or "milliseconds".');
178
+ }
179
+ if (timestamp.tolerance !== undefined &&
180
+ (typeof timestamp.tolerance !== "number" ||
181
+ !Number.isInteger(timestamp.tolerance) ||
182
+ timestamp.tolerance < 1 ||
183
+ timestamp.tolerance > MAX_WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS)) {
184
+ report("timestamp.tolerance", `tolerance is a whole number of seconds from 1 to ${MAX_WEBHOOK_TIMESTAMP_TOLERANCE_SECONDS}.`);
185
+ }
186
+ }
187
+ }
188
+ const message = signature.message;
189
+ if (message !== undefined) {
190
+ if (!Array.isArray(message) ||
191
+ message.length === 0 ||
192
+ message.length > MAX_WEBHOOK_MESSAGE_PARTS) {
193
+ report("message", `message is a list of 1 to ${MAX_WEBHOOK_MESSAGE_PARTS} parts.`);
194
+ }
195
+ else {
196
+ let bodies = 0;
197
+ for (const [index, part] of message.entries()) {
198
+ const at = `message.${index}`;
199
+ if (typeof part === "string") {
200
+ if (part.length === 0 || part.length > MAX_WEBHOOK_MESSAGE_TEXT) {
201
+ report(at, `A text part has 1 to ${MAX_WEBHOOK_MESSAGE_TEXT} characters.`);
202
+ }
203
+ }
204
+ else if (isRecord(part) && Object.keys(part).length === 1 && part.body === true) {
205
+ bodies += 1;
206
+ }
207
+ else if (isRecord(part) && Object.keys(part).length === 1 && part.timestamp === true) {
208
+ if (!timed) {
209
+ report(at, "{ timestamp: true } needs the signature's timestamp declared.");
210
+ }
211
+ }
212
+ else if (isRecord(part) && Object.keys(part).length === 1 && "header" in part) {
213
+ const headerProblem = signedHeaderProblem(part.header);
214
+ if (headerProblem !== undefined) {
215
+ report(at, headerProblem);
216
+ }
217
+ }
218
+ else {
219
+ report(at, "A part is text, { body: true }, { header } or { timestamp: true }.");
220
+ }
221
+ }
222
+ if (bodies !== 1) {
223
+ report("message", "message includes { body: true } exactly once.");
224
+ }
225
+ }
226
+ }
227
+ if (timed && isRecord(timestamp)) {
228
+ // A timestamp the provider does not sign proves nothing: a replayed delivery would carry a
229
+ // fresh one and pass.
230
+ const signedParts = Array.isArray(message) ? message : [];
231
+ const covered = signedParts.some((part) => isRecord(part) &&
232
+ (part.timestamp === true ||
233
+ (timestamp.header !== undefined && part.header === timestamp.header)));
234
+ if (!covered) {
235
+ report("timestamp", "The signed message must include the timestamp, as { timestamp: true } or its header; " +
236
+ "otherwise a replayed delivery passes with a fresh one.");
237
+ }
238
+ }
239
+ return problems;
240
+ }
241
+ function signedHeaderProblem(name) {
242
+ return typeof name === "string" && HEADER_NAME.test(name)
243
+ ? undefined
244
+ : `${JSON.stringify(name) ?? "undefined"} is not a lowercase header name.`;
245
+ }
246
+ /**
247
+ * A valid signature declaration as the manifest records it: `{ scheme, secret }` for a named
248
+ * scheme, and for `hmac` its format's settings, each written only when declared.
249
+ */
250
+ export function webhookSignatureManifest(signature) {
251
+ if (signature.scheme !== "hmac") {
252
+ return { scheme: signature.scheme, secret: signature.secret };
253
+ }
254
+ const { signatures, timestamp, key, message } = signature;
255
+ return {
256
+ scheme: "hmac",
257
+ secret: signature.secret,
258
+ algorithm: signature.algorithm,
259
+ encoding: signature.encoding,
260
+ ...(key === undefined
261
+ ? {}
262
+ : {
263
+ key: { decode: key.decode, ...(key.prefix === undefined ? {} : { prefix: key.prefix }) },
264
+ }),
265
+ signatures: {
266
+ header: signatures.header,
267
+ ...(signatures.prefix === undefined ? {} : { prefix: signatures.prefix }),
268
+ ...(signatures.entries === undefined
269
+ ? {}
270
+ : {
271
+ entries: {
272
+ separator: signatures.entries.separator,
273
+ assign: signatures.entries.assign,
274
+ name: signatures.entries.name,
275
+ },
276
+ }),
277
+ },
278
+ ...(timestamp === undefined
279
+ ? {}
280
+ : {
281
+ timestamp: {
282
+ ...(timestamp.header === undefined ? {} : { header: timestamp.header }),
283
+ ...(timestamp.entry === undefined ? {} : { entry: timestamp.entry }),
284
+ ...(timestamp.unit === undefined ? {} : { unit: timestamp.unit }),
285
+ ...(timestamp.tolerance === undefined ? {} : { tolerance: timestamp.tolerance }),
286
+ },
287
+ }),
288
+ ...(message === undefined
289
+ ? {}
290
+ : {
291
+ message: message.map((part) => typeof part === "string"
292
+ ? part
293
+ : "body" in part
294
+ ? { body: true }
295
+ : "timestamp" in part
296
+ ? { timestamp: true }
297
+ : { header: part.header }),
298
+ }),
299
+ };
300
+ }
10
301
  /** The most webhook triggers one ontology may declare across its workflows. */
11
302
  export const MAX_WEBHOOKS = 20;
12
303
  /** The most request headers one webhook trigger may pass to its workflow. */
@@ -4,7 +4,7 @@ import type { AnyConnectionHandle } from "./connection.js";
4
4
  import type { ActionHandle, AnyStoredEntity } from "./entity.js";
5
5
  import type { Edit } from "./runtime/history.js";
6
6
  import type { Principal } from "./runtime.js";
7
- import type { WebhookDelivery, WebhookSignatureScheme } from "./webhooks.js";
7
+ import type { WebhookDelivery, WebhookHmacFormat, WebhookSignatureScheme } from "./webhooks.js";
8
8
  /** Marks the values `workflow(…)` returns, so that `check` can tell them from look-alikes. */
9
9
  export declare const WorkflowTypeId: unique symbol;
10
10
  /** Marks the values trigger constructors such as `cron(…)` and `after(…)` return. */
@@ -123,13 +123,18 @@ export interface ActionTrigger<Name extends string = string, Input = unknown> {
123
123
  }
124
124
  /**
125
125
  * Where a webhook's deliveries are checked: a provider's signature format and the workspace secret
126
- * that holds its signing secret. Without one, the webhook's URL ends in a token.
126
+ * that holds its signing secret. Without one, the webhook's URL ends in a token. `stripe` and `meta`
127
+ * name published formats; `hmac` declares any other HMAC format with the trigger.
127
128
  */
128
- export interface WebhookSignature {
129
- readonly scheme: WebhookSignatureScheme;
129
+ export type WebhookSignature = {
130
+ readonly scheme: Exclude<WebhookSignatureScheme, "hmac">;
130
131
  /** A workspace secret's name, such as `stripe-webhook-signing-secret`; its value stays in the platform. */
131
132
  readonly secret: string;
132
- }
133
+ } | ({
134
+ readonly scheme: "hmac";
135
+ /** A workspace secret's name, such as `btcpay-webhook-secret`; its value stays in the platform. */
136
+ readonly secret: string;
137
+ } & WebhookHmacFormat);
133
138
  /** Meta's registration handshake; the verify token is a workspace secret, separate from the app secret. */
134
139
  export interface WebhookVerification {
135
140
  readonly scheme: "meta";
@@ -14,7 +14,7 @@ export { p } from "./property.js";
14
14
  export type { AnyProperty, NumberOptions, Property, PropertyOptions, TextOptions, } from "./property.js";
15
15
  export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_WORKFLOWS, nextCronTime, webhook, workflow, } from "./workflow.js";
16
16
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
17
- export type { WebhookDelivery, WebhookSignatureScheme } from "./webhooks.js";
17
+ export type { WebhookDelivery, WebhookHmacFormat, WebhookSignatureScheme, WebhookSignedPart, } from "./webhooks.js";
18
18
  export type { ActionEvent, ActionTrigger, AfterOptions, AnyActionHandle, AnyWorkflow, ChangedBounds, CronOptions, CronProblem, CronTrigger, TriggerFunction, TriggerRecord, WebhookOptions, WebhookSignature, WebhookVerification, WebhookTrigger, Workflow, WorkflowFunction, WorkflowOptions, WorkflowRunContext, WorkflowTrigger, } from "./workflow.js";
19
19
  export { run, WORKFLOW_BASE_PATH, WorkflowStepRequired } from "./workflow-runtime.js";
20
20
  export { recoverWorkflowStarts, StartRecoveryWorkflowRequired } from "./start-recovery.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.124.0",
3
+ "version": "0.126.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",