@mountaya/client 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -0
- package/LICENCE.fr.txt +280 -0
- package/LICENSE.txt +262 -0
- package/README.md +1260 -2
- package/dist/admin/index.cjs +3521 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +1070 -0
- package/dist/admin/index.d.ts +1070 -0
- package/dist/admin/index.js +301 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/browser.cjs +8073 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +106 -0
- package/dist/browser.d.ts +106 -0
- package/dist/browser.js +53 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-BM526BHG.js +342 -0
- package/dist/chunk-BM526BHG.js.map +1 -0
- package/dist/chunk-D2YEVTG7.js +327 -0
- package/dist/chunk-D2YEVTG7.js.map +1 -0
- package/dist/chunk-OHKVUREN.js +3500 -0
- package/dist/chunk-OHKVUREN.js.map +1 -0
- package/dist/chunk-TDTK2L5H.js +3842 -0
- package/dist/chunk-TDTK2L5H.js.map +1 -0
- package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
- package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
- package/dist/errors-B-GqAtQv.d.cts +75960 -0
- package/dist/errors-B-GqAtQv.d.ts +75960 -0
- package/dist/events/index.cjs +1972 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +781 -0
- package/dist/events/index.d.ts +781 -0
- package/dist/events/index.js +826 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.cjs +8072 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
- package/dist/operations.gen-DUD406TV.d.ts +3993 -0
- package/package.json +127 -4
- package/src/admin/index.ts +47 -0
- package/src/admin/rules/mountayaAdmin.ts +102 -0
- package/src/browser.ts +232 -0
- package/src/core/engines/sessionToken.ts +870 -0
- package/src/core/rules/auth.ts +1017 -0
- package/src/core/rules/clientHeader.ts +28 -0
- package/src/core/rules/dates.ts +200 -0
- package/src/core/rules/decode.ts +154 -0
- package/src/core/rules/envelope.ts +41 -0
- package/src/core/rules/errors.ts +1486 -0
- package/src/core/rules/graphql.ts +576 -0
- package/src/core/rules/headerValue.ts +42 -0
- package/src/core/rules/idempotencyKey.ts +64 -0
- package/src/core/rules/nullMask.ts +127 -0
- package/src/core/rules/nullMasks.gen.ts +416 -0
- package/src/core/rules/paginate.ts +316 -0
- package/src/core/rules/rateLimit.ts +507 -0
- package/src/core/rules/redaction.ts +219 -0
- package/src/core/rules/resourceRef.ts +110 -0
- package/src/core/rules/responseBody.ts +492 -0
- package/src/core/rules/retry.ts +386 -0
- package/src/core/rules/selection.ts +416 -0
- package/src/core/rules/sessionAnswer.ts +90 -0
- package/src/core/rules/sessionSchedule.ts +131 -0
- package/src/core/rules/sessionWait.ts +112 -0
- package/src/core/rules/transport.ts +2386 -0
- package/src/core/rules/version.gen.ts +16 -0
- package/src/core/rules/webAddress.ts +165 -0
- package/src/core/rules/webAddresses.gen.ts +30 -0
- package/src/data/operations.gen.ts +603 -0
- package/src/data/schema.gen.ts +8078 -0
- package/src/data/selection.gen.ts +472 -0
- package/src/events/index.ts +67 -0
- package/src/events/rules/agent.ts +439 -0
- package/src/events/rules/collab.ts +554 -0
- package/src/events/rules/collabNulls.gen.ts +17 -0
- package/src/events/rules/eventStream.ts +94 -0
- package/src/events/rules/openSseStream.ts +594 -0
- package/src/events/rules/sse.ts +349 -0
- package/src/index.ts +231 -0
- package/src/rest/adminOperations.gen.ts +70 -0
- package/src/rest/adminResources.gen.ts +136 -0
- package/src/rest/coreOperations.gen.ts +74 -0
- package/src/rest/coreResources.gen.ts +244 -0
- package/src/rest/dates.gen.ts +217 -0
- package/src/rest/operations.gen.ts +4341 -0
- package/src/rest/resources.gen.ts +369 -0
- package/src/rest/schema.gen.ts +56840 -0
- package/src/tiles/operations.gen.ts +206 -0
- package/src/tiles/schema.gen.ts +8408 -0
- package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
- package/src/webhooks/rules/webhookEvent.ts +38 -0
- package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Verifying a webhook delivery, and reading the event it carries.
|
|
3
|
+
*
|
|
4
|
+
* Mountaya signs every delivery with the endpoint's secret and sends the signature in the
|
|
5
|
+
* `Mountaya-Signature` header, `t=<unix seconds>,v1=<signature>`, with one `v1` for each secret in
|
|
6
|
+
* force: two while a rotated secret overlaps its successor. Each `v1` is the lowercase hexadecimal
|
|
7
|
+
* HMAC-SHA256 of `<t>.<body>`, keyed by the secret's UTF-8 bytes, `whsk_` included, where
|
|
8
|
+
* `<body>` is the request body exactly as it arrived. The rule is the contract's, and its cases are
|
|
9
|
+
* the signature vectors `mountaya/schemas` publishes beside its bundle, in
|
|
10
|
+
* openapi/api/webhooks/signature-vectors.json.
|
|
11
|
+
*
|
|
12
|
+
* The order is part of the rule: the header is read first, then the signature, then the time. `t`
|
|
13
|
+
* is inside what is signed, so it is compared with the clock only once a signature vouches for it,
|
|
14
|
+
* and a forged delivery is refused for its signature whatever time it claims.
|
|
15
|
+
*
|
|
16
|
+
* The clock is the receiver's: the machine's wall clock, read once the signature verifies, unless
|
|
17
|
+
* the caller states the instant as `now`. A rule whose answer moves with the wall clock is one no
|
|
18
|
+
* test can pin, so a receiver's tests and the conformance suite state the instant, and a receiver
|
|
19
|
+
* that keeps a clock of its own hands it.
|
|
20
|
+
*
|
|
21
|
+
* The MAC is computed with Web Crypto, which Node, the browsers, workers and edge runtimes provide,
|
|
22
|
+
* and which answers a promise. The comparison is this module's own and reads every character of
|
|
23
|
+
* every `v1` whatever the first difference, so the time it takes says nothing about how much of a
|
|
24
|
+
* forged signature was right.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { decodeRestSchema, decodeSchemaInstants } from "../../core/rules/decode.js";
|
|
28
|
+
import {
|
|
29
|
+
describeType,
|
|
30
|
+
MountayaConfigurationError,
|
|
31
|
+
MountayaError,
|
|
32
|
+
refuseOption,
|
|
33
|
+
} from "../../core/rules/errors.js";
|
|
34
|
+
import type { WebhookEvent } from "./webhookEvent.js";
|
|
35
|
+
|
|
36
|
+
/** The name refusals give the call they refuse. */
|
|
37
|
+
const CONTEXT = "constructWebhookEvent";
|
|
38
|
+
|
|
39
|
+
/** The seconds a delivery's timestamp may stand from the receiver's clock, either way, by default. */
|
|
40
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
41
|
+
|
|
42
|
+
/** The prefix of every endpoint's signing secret, which the MAC is keyed with as well. */
|
|
43
|
+
const SECRET_PREFIX = "whsk_";
|
|
44
|
+
|
|
45
|
+
/** A timestamp of the header: whole seconds, in digits alone. */
|
|
46
|
+
const wholeSeconds = /^\d+$/;
|
|
47
|
+
|
|
48
|
+
/** The last Unix second an instant is written for, 9999-12-31T23:59:59Z, the end of a 4-digit year. */
|
|
49
|
+
const LATEST_WRITTEN_SECONDS = 253_402_300_799;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* signedAt writes the instant a header's `t` names, or the `t` itself past the year 9999, where an
|
|
53
|
+
* instant has no 4-digit year to write and, past the year 275760, the runtime's date throws.
|
|
54
|
+
*/
|
|
55
|
+
const signedAt = (timestamp: number): string =>
|
|
56
|
+
timestamp <= LATEST_WRITTEN_SECONDS ? new Date(timestamp * 1000).toISOString() : `t=${timestamp}`;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* WebhookSignatureFailure is why {@link constructWebhookEvent} refused a delivery, as
|
|
60
|
+
* {@link MountayaWebhookSignatureError} carries it:
|
|
61
|
+
*
|
|
62
|
+
* - `missing-header`: the request carries no `Mountaya-Signature` header, or an empty one.
|
|
63
|
+
* - `malformed-header`: the header is not `t=<unix seconds>,v1=<signature>`. It holds no `t` or
|
|
64
|
+
* more than one, a `t` that is not whole seconds, or no `v1`.
|
|
65
|
+
* - `signature`: no `v1` is the signature of this body under this secret. The body was changed on
|
|
66
|
+
* the way, the secret is another endpoint's or one rotated away, or the delivery is not
|
|
67
|
+
* Mountaya's.
|
|
68
|
+
* - `timestamp`: the signature verifies and `t` stands further from the receiver's clock than the
|
|
69
|
+
* tolerance, either way: a delivery replayed later, or a clock that is wrong.
|
|
70
|
+
*/
|
|
71
|
+
export type WebhookSignatureFailure =
|
|
72
|
+
| "malformed-header"
|
|
73
|
+
| "missing-header"
|
|
74
|
+
| "signature"
|
|
75
|
+
| "timestamp";
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* MountayaWebhookSignatureError is a webhook delivery {@link constructWebhookEvent} cannot trust:
|
|
79
|
+
* a signature header missing or malformed, a signature no `v1` matches, or a timestamp outside
|
|
80
|
+
* the tolerance. `reason` says which.
|
|
81
|
+
*
|
|
82
|
+
* Answer such a delivery with a `400` and do nothing it asks. Mountaya repeats a delivery that
|
|
83
|
+
* failed, so a refusal a wrong secret or a wrong clock caused costs an attempt and not the event:
|
|
84
|
+
* once the secret or the clock is right, the next attempt verifies.
|
|
85
|
+
*/
|
|
86
|
+
export class MountayaWebhookSignatureError extends MountayaError {
|
|
87
|
+
override readonly name = "MountayaWebhookSignatureError";
|
|
88
|
+
|
|
89
|
+
/** Why the delivery was refused: see {@link WebhookSignatureFailure}. */
|
|
90
|
+
readonly reason: WebhookSignatureFailure;
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* @param message - what was refused, and what to do about it.
|
|
94
|
+
* @param reason - why the delivery was refused.
|
|
95
|
+
*/
|
|
96
|
+
constructor(message: string, reason: WebhookSignatureFailure) {
|
|
97
|
+
super(message);
|
|
98
|
+
this.reason = reason;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** ConstructWebhookEventOptions is how {@link constructWebhookEvent} judges a delivery's time. */
|
|
103
|
+
export interface ConstructWebhookEventOptions {
|
|
104
|
+
/**
|
|
105
|
+
* The instant the receiver's clock reads, which a delivery's timestamp is judged against. Pass it
|
|
106
|
+
* where the receiver keeps a clock of its own, or where a test pins the time; left out, it is the
|
|
107
|
+
* machine's wall clock, read once the signature verifies.
|
|
108
|
+
*
|
|
109
|
+
* @default the machine's wall clock, as `Date.now()` reads it
|
|
110
|
+
*/
|
|
111
|
+
readonly now?: Date | undefined;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* How far a delivery's timestamp may stand from the receiver's clock, in seconds, either way. A
|
|
115
|
+
* delivery signed longer ago is refused as a replay. Raise it for a receiver whose clock drifts,
|
|
116
|
+
* never to accept a delivery a queue held back: verify a delivery as it arrives, then queue it.
|
|
117
|
+
*
|
|
118
|
+
* @default 300
|
|
119
|
+
*/
|
|
120
|
+
readonly toleranceSeconds?: number | undefined;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** What a `Mountaya-Signature` header states: when it was signed, and each signature. */
|
|
124
|
+
interface SignatureHeader {
|
|
125
|
+
/** Every `v1` of the header, in the order written. */
|
|
126
|
+
readonly signatures: readonly string[];
|
|
127
|
+
/** The header's `t` as written, which is what a `v1` signs. */
|
|
128
|
+
readonly stated: string;
|
|
129
|
+
/** The header's `t`: the Unix time, in seconds, the attempt was signed at. */
|
|
130
|
+
readonly timestamp: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* parseSignatureHeader reads a `Mountaya-Signature` header, or answers undefined where it is not
|
|
135
|
+
* one: no `t` or more than one, a `t` that is not whole seconds, no `v1`, or an element that is
|
|
136
|
+
* no `key=value` pair.
|
|
137
|
+
*
|
|
138
|
+
* A key other than `t` and `v1` names a signature scheme this release does not compute, and is
|
|
139
|
+
* passed over, so a header that adds one beside `v1` still verifies here.
|
|
140
|
+
*/
|
|
141
|
+
const parseSignatureHeader = (header: string): SignatureHeader | undefined => {
|
|
142
|
+
const signatures: string[] = [];
|
|
143
|
+
const timestamps: string[] = [];
|
|
144
|
+
|
|
145
|
+
for (const element of header.split(",")) {
|
|
146
|
+
const separator = element.indexOf("=");
|
|
147
|
+
if (separator === -1) {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const key = element.slice(0, separator).trim();
|
|
152
|
+
const value = element.slice(separator + 1).trim();
|
|
153
|
+
|
|
154
|
+
if (key === "t") {
|
|
155
|
+
timestamps.push(value);
|
|
156
|
+
} else if (key === "v1") {
|
|
157
|
+
signatures.push(value);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const [stated] = timestamps;
|
|
162
|
+
if (timestamps.length !== 1 || stated === undefined || !wholeSeconds.test(stated)) {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const timestamp = Number(stated);
|
|
167
|
+
if (!Number.isSafeInteger(timestamp) || signatures.length === 0) {
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { signatures, stated, timestamp };
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* subtleCrypto resolves the Web Crypto implementation, or nothing where the runtime has none.
|
|
176
|
+
*
|
|
177
|
+
* The widened binding is what lets the check compile: `lib.dom` declares `crypto` as always
|
|
178
|
+
* present, and React Native and a page served over plain HTTP have none.
|
|
179
|
+
*/
|
|
180
|
+
const subtleCrypto = (): SubtleCrypto | undefined => {
|
|
181
|
+
const runtime: { readonly crypto?: Crypto | undefined } = globalThis;
|
|
182
|
+
|
|
183
|
+
return runtime.crypto?.subtle;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/** hexOf spells bytes as lowercase hexadecimal, two characters a byte. */
|
|
187
|
+
const hexOf = (bytes: ArrayBuffer): string =>
|
|
188
|
+
Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* equalInConstantTime reports whether two strings are equal, reading every character of both
|
|
192
|
+
* whatever the first difference, so the time it takes says nothing about where they differ. A
|
|
193
|
+
* length is no secret: a `v1` of another length than a signature is unequal at once.
|
|
194
|
+
*/
|
|
195
|
+
const equalInConstantTime = (candidate: string, expected: string): boolean => {
|
|
196
|
+
if (candidate.length !== expected.length) {
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
let difference = 0;
|
|
201
|
+
for (let index = 0; index < expected.length; index += 1) {
|
|
202
|
+
difference |= candidate.charCodeAt(index) ^ expected.charCodeAt(index);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return difference === 0;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* signedBytes is what a `v1` signs: the header's `t` as written, a dot, and the body's own bytes.
|
|
210
|
+
*/
|
|
211
|
+
const signedBytes = (stated: string, body: Uint8Array): Uint8Array<ArrayBuffer> => {
|
|
212
|
+
const prefix = new TextEncoder().encode(`${stated}.`);
|
|
213
|
+
const signed = new Uint8Array(prefix.length + body.length);
|
|
214
|
+
|
|
215
|
+
signed.set(prefix);
|
|
216
|
+
signed.set(body, prefix.length);
|
|
217
|
+
|
|
218
|
+
return signed;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/** isRecord narrows a parsed value to an object that is no list. */
|
|
222
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
223
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* envelopeOf reads the envelope a verified body holds: the JSON object every event is delivered
|
|
227
|
+
* in.
|
|
228
|
+
*
|
|
229
|
+
* The body verified, so it is what this endpoint's secret signed, and one that holds no envelope
|
|
230
|
+
* is no delivery a receiver can act on: no event reads from it, and no answer and no status stands
|
|
231
|
+
* behind it for a reason to name. It is refused as a configuration error, carrying the parser's
|
|
232
|
+
* failure as its `cause` where the body is not even JSON, rather than as the runtime's own
|
|
233
|
+
* `SyntaxError`, outside the family a receiver catches.
|
|
234
|
+
*
|
|
235
|
+
* @throws `MountayaConfigurationError` for a body that is not JSON, or JSON that is no object.
|
|
236
|
+
*/
|
|
237
|
+
const envelopeOf = (body: Uint8Array): Record<string, unknown> => {
|
|
238
|
+
const refusal =
|
|
239
|
+
`${CONTEXT}: the delivery verified and its body holds no webhook event, not even the ` +
|
|
240
|
+
"envelope every event is delivered in. Answer the request with a 400 and act on nothing it asks.";
|
|
241
|
+
|
|
242
|
+
let parsed: unknown;
|
|
243
|
+
try {
|
|
244
|
+
parsed = JSON.parse(new TextDecoder().decode(body));
|
|
245
|
+
} catch (cause) {
|
|
246
|
+
throw new MountayaConfigurationError(refusal, { cause });
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (!isRecord(parsed)) {
|
|
250
|
+
throw new MountayaConfigurationError(refusal);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return parsed;
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* withPreviousAttributes answers `event` with the instants of its `data.previous_attributes`
|
|
258
|
+
* decoded, by the mask `data.object` is decoded with: each field there is a field of the object,
|
|
259
|
+
* and holds the value it held before the change, an instant where the object's field is one. It
|
|
260
|
+
* writes no null there: a field the object types required and nullable that `previous_attributes`
|
|
261
|
+
* leaves out is one the change left as it was.
|
|
262
|
+
*/
|
|
263
|
+
const withPreviousAttributes = (event: unknown): unknown => {
|
|
264
|
+
if (!isRecord(event) || !isRecord(event.data) || !isRecord(event.data.previous_attributes)) {
|
|
265
|
+
return event;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const held = event.data.previous_attributes;
|
|
269
|
+
const decoded = decodeSchemaInstants("WebhookEventObject", held);
|
|
270
|
+
|
|
271
|
+
return decoded === held
|
|
272
|
+
? event
|
|
273
|
+
: { ...event, data: { ...event.data, previous_attributes: decoded } };
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* millisecondsOf answers the instant a `Date` names, in milliseconds since the epoch, or undefined
|
|
278
|
+
* for a value that is no `Date`. `Date.prototype.getTime` reads the date's own slot, so a `Date`
|
|
279
|
+
* built in another realm (a frame, another context) is read as the instant it is, and an object
|
|
280
|
+
* that only claims the tag is none.
|
|
281
|
+
*/
|
|
282
|
+
const millisecondsOf = (value: unknown): number | undefined => {
|
|
283
|
+
try {
|
|
284
|
+
return Date.prototype.getTime.call(value);
|
|
285
|
+
} catch {
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* constructWebhookEvent verifies a webhook delivery's signature and answers the event its body
|
|
292
|
+
* holds, typed by its `type`.
|
|
293
|
+
*
|
|
294
|
+
* Pass the body exactly as it arrived, before any JSON parser reads it: the signature covers those
|
|
295
|
+
* bytes, and a body parsed and written out again is another string, which does not verify. A
|
|
296
|
+
* `Uint8Array`, a Node `Buffer` among them, is verified as it is, and a string as its UTF-8 bytes,
|
|
297
|
+
* which is what `await request.text()` answers for a body Mountaya sent.
|
|
298
|
+
*
|
|
299
|
+
* The header is read first, then the signature, then the time, so a forged delivery is refused
|
|
300
|
+
* for its signature whatever time it claims. A `v1` that matches is enough: while a rotated secret
|
|
301
|
+
* overlaps its successor the header carries one for each, and either secret verifies it. The time
|
|
302
|
+
* is judged against the receiver's clock: `options.now` where the caller states it, and the
|
|
303
|
+
* machine's wall clock otherwise.
|
|
304
|
+
*
|
|
305
|
+
* The event's instants are `Date`s, as a method of this client answers them: its `created_at`,
|
|
306
|
+
* those of `data.object` and those `data.previous_attributes` holds. A member of the event or of
|
|
307
|
+
* its `data.object` the contract types required and nullable reads null where the delivery leaves
|
|
308
|
+
* it out, as in an answer, and `data.previous_attributes` holds only what it was sent with. An
|
|
309
|
+
* event of a type a newer contract added is answered too, with the type it arrived with, which no
|
|
310
|
+
* case of a `switch` over the types this release knows reaches.
|
|
311
|
+
*
|
|
312
|
+
* @param rawBody - The request body, exactly as it arrived.
|
|
313
|
+
* @param signatureHeader - The request's `Mountaya-Signature` header, as `request.headers.get`
|
|
314
|
+
* answers it: `null` or `undefined` where the request carries none.
|
|
315
|
+
* @param secret - The signing secret of the endpoint the delivery was sent to, `whsk_` included.
|
|
316
|
+
* @param options - How far a timestamp may stand from the receiver's clock, and the instant that
|
|
317
|
+
* clock reads.
|
|
318
|
+
* @returns The event, once a `v1` verifies and its timestamp is within the tolerance.
|
|
319
|
+
* @throws `MountayaWebhookSignatureError` for a delivery that cannot be trusted, its `reason`
|
|
320
|
+
* saying why: answer it with a `400`.
|
|
321
|
+
* @throws `MountayaConfigurationError` for a body that is no string or `Uint8Array`, a secret
|
|
322
|
+
* that does not start with `whsk_`, a `toleranceSeconds` that is no finite number from 0, a
|
|
323
|
+
* `now` that is no `Date` naming an instant, or a runtime with no Web Crypto; and, once the
|
|
324
|
+
* delivery verifies, for a body that holds no event, not even the envelope every event is
|
|
325
|
+
* delivered in, with the parser's failure as its `cause` where the body is not JSON. It names no
|
|
326
|
+
* `reason`: answer it with a `400` as well.
|
|
327
|
+
*
|
|
328
|
+
* @example
|
|
329
|
+
* ```ts
|
|
330
|
+
* declare const webhookSecret: string; // The endpoint's signing secret, whsk_…
|
|
331
|
+
*
|
|
332
|
+
* export const POST = async (request: Request): Promise<Response> => {
|
|
333
|
+
* let event: WebhookEvent;
|
|
334
|
+
* try {
|
|
335
|
+
* event = await constructWebhookEvent(
|
|
336
|
+
* await request.text(),
|
|
337
|
+
* request.headers.get("Mountaya-Signature"),
|
|
338
|
+
* webhookSecret,
|
|
339
|
+
* );
|
|
340
|
+
* } catch (error) {
|
|
341
|
+
* if (error instanceof MountayaWebhookSignatureError) {
|
|
342
|
+
* return new Response(error.reason, { status: 400 });
|
|
343
|
+
* }
|
|
344
|
+
* throw error;
|
|
345
|
+
* }
|
|
346
|
+
*
|
|
347
|
+
* if (event.type === "organization.member.deleted") {
|
|
348
|
+
* console.log(`${event.data.object.user_id} left: ${event.data.object.reason}`);
|
|
349
|
+
* }
|
|
350
|
+
*
|
|
351
|
+
* return new Response(null, { status: 204 });
|
|
352
|
+
* };
|
|
353
|
+
* ```
|
|
354
|
+
*/
|
|
355
|
+
export const constructWebhookEvent = async (
|
|
356
|
+
rawBody: string | Uint8Array,
|
|
357
|
+
signatureHeader: string | null | undefined,
|
|
358
|
+
secret: string,
|
|
359
|
+
options?: ConstructWebhookEventOptions | undefined,
|
|
360
|
+
): Promise<WebhookEvent> => {
|
|
361
|
+
if (typeof rawBody !== "string" && !(rawBody instanceof Uint8Array)) {
|
|
362
|
+
throw new MountayaConfigurationError(
|
|
363
|
+
`${CONTEXT}: rawBody is ${describeType(rawBody)}; pass the body exactly as it arrived, as a ` +
|
|
364
|
+
"string or a Uint8Array, before any JSON parser reads it.",
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// The secret is never quoted: a refusal is logged, and the value is a credential whatever it holds.
|
|
369
|
+
if (typeof secret !== "string" || !secret.startsWith(SECRET_PREFIX)) {
|
|
370
|
+
throw new MountayaConfigurationError(
|
|
371
|
+
`${CONTEXT}: secret is ${typeof secret === "string" ? "a string that does not start with whsk_" : describeType(secret)}; ` +
|
|
372
|
+
"pass the signing secret of the endpoint the delivery was sent to, whsk_ included.",
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
if (options !== undefined && (typeof options !== "object" || options === null)) {
|
|
377
|
+
throw refuseOption(
|
|
378
|
+
"options",
|
|
379
|
+
options,
|
|
380
|
+
"pass an object such as { toleranceSeconds: 600 }, or leave it out for the defaults.",
|
|
381
|
+
CONTEXT,
|
|
382
|
+
);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const toleranceSeconds = options?.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
386
|
+
if (
|
|
387
|
+
typeof toleranceSeconds !== "number" ||
|
|
388
|
+
!Number.isFinite(toleranceSeconds) ||
|
|
389
|
+
toleranceSeconds < 0
|
|
390
|
+
) {
|
|
391
|
+
throw refuseOption(
|
|
392
|
+
"toleranceSeconds",
|
|
393
|
+
toleranceSeconds,
|
|
394
|
+
`pass a finite number of seconds from 0, or leave it out for ${DEFAULT_TOLERANCE_SECONDS}.`,
|
|
395
|
+
CONTEXT,
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// The stated instant is checked with the tolerance, before the header is read; the wall clock is
|
|
400
|
+
// read only once the signature verifies, as the time is judged last.
|
|
401
|
+
const stated = options?.now;
|
|
402
|
+
const statedMilliseconds = stated === undefined ? undefined : millisecondsOf(stated);
|
|
403
|
+
if (
|
|
404
|
+
stated !== undefined &&
|
|
405
|
+
(statedMilliseconds === undefined || !Number.isFinite(statedMilliseconds))
|
|
406
|
+
) {
|
|
407
|
+
throw refuseOption(
|
|
408
|
+
"now",
|
|
409
|
+
stated,
|
|
410
|
+
"pass a Date that names an instant, or leave it out for the machine's wall clock.",
|
|
411
|
+
CONTEXT,
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const subtle = subtleCrypto();
|
|
416
|
+
if (subtle === undefined) {
|
|
417
|
+
throw new MountayaConfigurationError(
|
|
418
|
+
`${CONTEXT}: this runtime provides no Web Crypto (crypto.subtle) to compute the signature ` +
|
|
419
|
+
"with. Verify the delivery on a server, in Node 22.18 or later, a worker or an edge runtime.",
|
|
420
|
+
);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
if (signatureHeader === null || signatureHeader === undefined || signatureHeader.trim() === "") {
|
|
424
|
+
throw new MountayaWebhookSignatureError(
|
|
425
|
+
`${CONTEXT}: the request carries no Mountaya-Signature header. Pass the header the request ` +
|
|
426
|
+
'carries, such as request.headers.get("Mountaya-Signature"), and answer a request ' +
|
|
427
|
+
"without one with a 400.",
|
|
428
|
+
"missing-header",
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const header = parseSignatureHeader(signatureHeader);
|
|
433
|
+
if (header === undefined) {
|
|
434
|
+
throw new MountayaWebhookSignatureError(
|
|
435
|
+
`${CONTEXT}: the Mountaya-Signature header ${JSON.stringify(signatureHeader)} is not ` +
|
|
436
|
+
"t=<unix seconds>,v1=<signature>. Pass the header exactly as the request carries it.",
|
|
437
|
+
"malformed-header",
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const body = typeof rawBody === "string" ? new TextEncoder().encode(rawBody) : rawBody;
|
|
442
|
+
const key = await subtle.importKey(
|
|
443
|
+
"raw",
|
|
444
|
+
new TextEncoder().encode(secret),
|
|
445
|
+
{ hash: "SHA-256", name: "HMAC" },
|
|
446
|
+
false,
|
|
447
|
+
["sign"],
|
|
448
|
+
);
|
|
449
|
+
const expected = hexOf(await subtle.sign("HMAC", key, signedBytes(header.stated, body)));
|
|
450
|
+
|
|
451
|
+
// Every `v1` is compared, a match found early included, so the time taken does not say which
|
|
452
|
+
// of the secrets in force signed the delivery.
|
|
453
|
+
const verified = header.signatures.reduce(
|
|
454
|
+
(found, candidate) => equalInConstantTime(candidate, expected) || found,
|
|
455
|
+
false,
|
|
456
|
+
);
|
|
457
|
+
if (!verified) {
|
|
458
|
+
throw new MountayaWebhookSignatureError(
|
|
459
|
+
`${CONTEXT}: no v1 of the Mountaya-Signature header is the signature of this body under ` +
|
|
460
|
+
"this secret. Pass the body exactly as it arrived, before any JSON parser reads it, and " +
|
|
461
|
+
"the secret of the endpoint the delivery was sent to.",
|
|
462
|
+
"signature",
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const skew = Math.abs((statedMilliseconds ?? Date.now()) / 1000 - header.timestamp);
|
|
467
|
+
if (skew > toleranceSeconds) {
|
|
468
|
+
throw new MountayaWebhookSignatureError(
|
|
469
|
+
`${CONTEXT}: the delivery was signed at ${signedAt(header.timestamp)}, ` +
|
|
470
|
+
`${Math.round(skew)} seconds from this clock, past the tolerance of ${toleranceSeconds} ` +
|
|
471
|
+
"seconds. A delivery replayed later is refused this way; where the clock is wrong, set it " +
|
|
472
|
+
"right.",
|
|
473
|
+
"timestamp",
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// The body verified, so it is the event Mountaya signed: the contract types it, and nothing
|
|
478
|
+
// past its envelope is validated, as nothing is in a response a method answers.
|
|
479
|
+
const event = withPreviousAttributes(decodeRestSchema("WebhookEvent", envelopeOf(body)));
|
|
480
|
+
|
|
481
|
+
return event as WebhookEvent;
|
|
482
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The webhook event a delivery carries, typed by its `type`.
|
|
3
|
+
*
|
|
4
|
+
* The contract describes the envelope once, as `WebhookEvent`, whose `type` is any public type and
|
|
5
|
+
* whose `data.object` is any kind of object. Which object a type carries, and which fields its
|
|
6
|
+
* previous attributes can hold, is stated per type in the contract's `webhooks`, and
|
|
7
|
+
* `webhookEvents.gen.ts` restates it as one member per type. The union below is those members, so
|
|
8
|
+
* comparing `type` with one type narrows `data` to what that type carries.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { WebhookEventType } from "../../rest/schema.gen.js";
|
|
12
|
+
import type { WebhookEventsByType } from "./webhookEvents.gen.js";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* WebhookEvent is a webhook event as Mountaya delivers it to an endpoint, typed by its `type`:
|
|
16
|
+
* comparing `type` with one of the public types narrows `data.object` to the object that type
|
|
17
|
+
* carries and `data.previous_attributes` to the fields its change can move.
|
|
18
|
+
*
|
|
19
|
+
* Name one type, `WebhookEvent<"organization.member.updated">`, for the event of that type alone,
|
|
20
|
+
* and several for their union. With no argument it is every public type's event, which is what
|
|
21
|
+
* {@link constructWebhookEvent} answers.
|
|
22
|
+
*
|
|
23
|
+
* Every event is the contract's envelope, so a value of this type is also a
|
|
24
|
+
* `RestSchema.components["schemas"]["WebhookEvent"]`, the shape `getOrganizationWebhookEvents`
|
|
25
|
+
* lists, where `type` and `data` are not tied together.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* declare const event: WebhookEvent;
|
|
30
|
+
*
|
|
31
|
+
* if (event.type === "organization.member.updated") {
|
|
32
|
+
* // The member's role now, and the role it held before the change.
|
|
33
|
+
* console.log(event.data.object.role, event.data.previous_attributes?.role);
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export type WebhookEvent<Type extends WebhookEventType = WebhookEventType> =
|
|
38
|
+
WebhookEventsByType[Type];
|