@smthrs/triggers 1.0.0-rc.7 → 1.0.0-rc.8
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/README.md +1 -7
- package/dist/cjs/Webhook.d.ts.map +1 -1
- package/dist/cjs/Webhook.js +10 -1
- package/dist/cjs/Webhook.js.map +2 -2
- package/dist/esm/Webhook.d.ts.map +1 -1
- package/dist/esm/Webhook.js +20 -1
- package/dist/esm/Webhook.js.map +1 -1
- package/docs/README.md +6 -4
- package/docs/api.md +2 -2
- package/docs/guides/ingest-a-webhook.md +3 -2
- package/docs/installation.md +7 -12
- package/docs/troubleshooting.md +2 -2
- package/package.json +3 -3
- package/src/Webhook.ts +22 -1
package/README.md
CHANGED
|
@@ -15,14 +15,8 @@ started run gets exactly the authority a person starting it would get.
|
|
|
15
15
|
|
|
16
16
|
## Install
|
|
17
17
|
|
|
18
|
-
`@smthrs/triggers` is not on npm at 1.0.0-rc.0. It ships as a member of the
|
|
19
|
-
[smithers repository](https://github.com/smithersai/smithers) workspace, so
|
|
20
|
-
using it today means working from a checkout:
|
|
21
|
-
|
|
22
18
|
```bash
|
|
23
|
-
|
|
24
|
-
cd smithers
|
|
25
|
-
pnpm install
|
|
19
|
+
npm install @smthrs/triggers@next effect
|
|
26
20
|
```
|
|
27
21
|
|
|
28
22
|
It needs Node.js 26.4.0 or later and `effect` `^4.0.4`. The full
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Webhook.d.ts","sourceRoot":"","sources":["../../src/Webhook.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,eAAe,MAAM,0BAA0B,CAAA;AAC3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAEhE,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAA;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAE/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
|
|
48
48
|
};
|
|
49
49
|
const ownedCopy = (body) => Uint8Array.from(body);
|
|
50
|
+
const headerValue = (headers, name) => {
|
|
51
|
+
const lower = name.toLowerCase();
|
|
52
|
+
const direct = headers[lower] ?? headers[name];
|
|
53
|
+
if (direct !== void 0) return direct;
|
|
54
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
55
|
+
if (value !== void 0 && key.toLowerCase() === lower) return value;
|
|
56
|
+
}
|
|
57
|
+
return void 0;
|
|
58
|
+
};
|
|
50
59
|
const makeSignatureVerifier = (config) => (raw, credential) => {
|
|
51
60
|
const refuse = (cause) => Effect.fail(
|
|
52
61
|
new import_TriggerError.TriggerError({
|
|
@@ -56,7 +65,7 @@ const makeSignatureVerifier = (config) => (raw, credential) => {
|
|
|
56
65
|
})
|
|
57
66
|
);
|
|
58
67
|
return Effect.suspend(() => {
|
|
59
|
-
const supplied = raw.headers
|
|
68
|
+
const supplied = headerValue(raw.headers, config.header);
|
|
60
69
|
if (supplied === void 0 || supplied.length === 0) {
|
|
61
70
|
return refuse();
|
|
62
71
|
}
|
package/dist/cjs/Webhook.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/Webhook.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Verified webhook ingestion through the authoritative Control boundary.\n *\n * @see packages/smithers/agent/triggers/docs/api.md\n * @since 0.1.0\n */\n\nimport * as ControlChannels from \"@smthrs/control/Channels\"\nimport type { ControlError } from \"@smthrs/control/ControlError\"\nimport { InvalidInput, Unauthorized } from \"@smthrs/control/ControlError\"\nimport type { Receipt, RunSummary } from \"@smthrs/control/ControlSchema\"\nimport type { CredentialRef } from \"@smthrs/control/Credential\"\nimport * as ControlWebhook from \"@smthrs/control/WebhookChannel\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Channel from \"./Channel.ts\"\nimport { TriggerError } from \"./TriggerError.ts\"\n\n/**\n * Compares a supplied byte string against the expected one without returning\n * early on a mismatch.\n *\n * The loop runs exactly `expected.length` times, so its iteration count is\n * fixed by the secret side of the comparison and never by the caller's. Reading\n * the longer of the two instead let a caller lengthen its input until the work\n * stopped growing, which reports the expected signature's length. The length\n * difference is folded into the result, so inputs of unequal length always\n * disagree.\n *\n * @category verification\n * @since 0.1.0\n */\nexport const constantTimeEqual = (expected: Uint8Array, supplied: Uint8Array): boolean => {\n let difference = expected.length ^ supplied.length\n for (const [index, byte] of expected.entries()) {\n difference |= byte ^ (supplied[index] ?? 0)\n }\n return difference === 0\n}\n\n/**\n * Configuration for a raw-byte signature verifier.\n *\n * `expected` receives a private copy of the request bytes and the redacted\n * credential reference the channel was declared with, and answers with the\n * signature bytes the request must carry in `header`. It returns an Effect so\n * the secret is resolved through the host's resolver per request rather than\n * captured in a closure at declaration time, and so a resolution or HMAC\n * failure arrives as a typed `verification_failed` instead of a defect that\n * kills the fiber.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface SignatureConfig {\n readonly header: string\n readonly expected: (\n body: Uint8Array,\n credential: Redacted.Redacted<CredentialRef>\n ) => Effect.Effect<Uint8Array, TriggerError>\n}\n\n/**\n * Copies request bytes into memory nobody else holds.\n *\n * `body.slice()` is not enough: a Node `Buffer` is a `Uint8Array` whose\n * `slice` is an alias of `subarray` and answers with a view over the same\n * memory, so a caller that reused its `Buffer` after handing it over changed\n * what got verified, and a verifier that edited the bytes it was handed edited\n * the caller's. `Uint8Array.from` always allocates, and it copies only the\n * viewed range of an offset view and only a snapshot of a `SharedArrayBuffer`.\n */\nconst ownedCopy = (body: Uint8Array): Uint8Array => Uint8Array.from(body)\n\n/**\n * Builds a verifier that compares a signature header in constant time.\n *\n * An absent or empty header is refused before `expected` runs, and an\n * `expected` that answers with zero bytes is refused after it. Neither is a\n * comparison the constant-time equality can decide: it agrees on two empty\n * byte strings, so a request carrying no signature at all would have\n * authenticated against a secret that resolved to the empty string. A\n * zero-length expected signature is a misconfigured credential, never a valid\n * one, so the door stays closed instead of opening for everyone.\n *\n * Every refusal carries the same message, `webhook signature in <header> did\n * not verify`, whatever the reason. A failure raised by `expected` is kept in\n * `cause` only: its message names the credential reference or the resolver\n * that could not produce a secret, which is a host detail, and the refusal\n * that answers a bad signature answers a broken resolver the same way.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const makeSignatureVerifier = (config: SignatureConfig): Channel.Verify => (raw, credential) => {\n const refuse = (cause?: TriggerError) =>\n Effect.fail(\n new TriggerError({\n code: \"verification_failed\",\n message: `webhook signature in ${config.header} did not verify`,\n ...(cause === undefined ? {} : { cause })\n })\n )\n return Effect.suspend(() => {\n const supplied = raw.headers[config.header.toLowerCase()] ?? raw.headers[config.header]\n if (supplied === undefined || supplied.length === 0) {\n return refuse()\n }\n const actual = new TextEncoder().encode(supplied)\n // The verifier gets its own copy: nothing it does to these bytes can reach\n // the buffer that is about to be fingerprinted and decoded.\n return config.expected(ownedCopy(raw.body), credential).pipe(\n Effect.matchEffect({\n onFailure: (error) => refuse(error),\n onSuccess: (expected) =>\n expected.length > 0 && constantTimeEqual(expected, actual)\n ? Effect.void\n : refuse()\n })\n )\n })\n}\n\n/**\n * Webhook declaration configuration.\n *\n * `credential` is required. It used to default to a reference named after the\n * channel, so a webhook declared without one verified against whatever\n * credential happened to share its name instead of being refused, and two\n * declarations differing only in credential verified identically.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Config<Payload, Outbound = never> extends Channel.Config<Payload, RunSummary, Outbound> {\n readonly credential: Redacted.Redacted<CredentialRef>\n}\n\n/**\n * A webhook door that can only ingest through `Channels` and `Control`.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface Webhook {\n readonly name: string\n readonly register: Effect.Effect<void, never, ControlChannels.Channels>\n readonly ingest: (\n raw: Channel.RawInbound\n ) => Effect.Effect<Receipt, ControlError | TriggerError, ControlChannels.Channels>\n}\n\nconst invalidInput = (issue: string): InvalidInput => new InvalidInput({ issue })\n\nconst toControlChannel = <Payload, Outbound>(\n config: Config<Payload, Outbound>\n): ControlChannels.Channel<Payload> => {\n const channel = ControlWebhook.make({\n name: config.name,\n schema: config.schema,\n credential: config.credential,\n // The message is fixed here rather than forwarded from the verifier: a\n // custom `verify` may say why it refused, and that reason travels toward\n // the unauthenticated sender on the same error that answers a bad\n // signature. `Unauthorized` carries no cause, so nothing else survives\n // the crossing.\n verify: (raw, credential) =>\n config.verify(raw, credential).pipe(\n Effect.mapError(() => new Unauthorized({ message: `webhook ${config.name} did not verify the request` }))\n ),\n map: (payload) => {\n const inbound = config.inbound(payload)\n if (\"start\" in inbound) {\n return Effect.succeed({\n _tag: \"Start\" as const,\n flowId: inbound.start.flowId,\n input: inbound.start.input\n })\n }\n return Schema.decodeUnknownEffect(Schema.Json)(inbound.signal.value).pipe(\n Effect.map(\n (value) => ({\n _tag: \"Signal\" as const,\n runId: inbound.signal.runId,\n signal: {\n name: inbound.signal.stepId,\n payload: value\n }\n })\n ),\n Effect.mapError((error) => invalidInput(String(error)))\n )\n },\n project: (run) => {\n if (config.outbound === undefined) {\n return {\n cursor: String(run.updatedAt),\n operation: \"noop\" as const,\n message: null\n }\n }\n return {\n cursor: String(run.updatedAt),\n operation: \"post\" as const,\n message: config.outbound(run)\n }\n }\n })\n return channel\n}\n\n/**\n * Builds a webhook door whose only dispatch path is the Control channel\n * coordinator.\n *\n * Verification occurs inside `Channels.ingest` before the adapter's JSON or\n * schema decoder and before any Control operation.\n *\n * `ingest` does not register: a channel is registered once, deliberately,\n * through {@link Webhook.register}, so traffic to an unregistered channel is\n * reported as unavailable rather than silently self-registering the door it\n * arrived at.\n *\n * `ingest` also copies `body`, `headers`, and `idempotencyKey` before anything\n * reads them. Verification, delivery fingerprinting, and decoding then all see\n * one private snapshot, so a verifier that edits the bytes it was handed, or a\n * caller that mutates its own object between building this Effect and running\n * it, cannot authenticate one payload and have another decoded. A\n * `SharedArrayBuffer`-backed view is copied out of shared memory by the same\n * step.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <Payload, Outbound = never>(\n config: Config<Payload, Outbound>\n): Webhook => {\n const channel = toControlChannel(config)\n const register = Effect.flatMap(ControlChannels.Channels, (channels) => channels.register(channel))\n return {\n name: config.name,\n register,\n ingest: (raw) => {\n // Copied here rather than inside the Effect: the copy has to happen when\n // the caller hands the request over, not when the returned Effect\n // eventually runs, or a caller that reuses its own buffer in between\n // changes what gets authenticated.\n const snapshot: Channel.RawInbound = {\n body: ownedCopy(raw.body),\n headers: { ...raw.headers },\n idempotencyKey: raw.idempotencyKey\n }\n return Effect.gen(function*() {\n const channels = yield* ControlChannels.Channels\n return yield* channels.ingest({ channel: config.name, raw: snapshot })\n }).pipe(\n Effect.mapError((error) =>\n error instanceof Unauthorized\n ? new TriggerError({\n code: \"verification_failed\",\n message: `webhook ${config.name} did not verify the request`,\n cause: error\n })\n : error\n )\n )\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,sBAAiC;AAEjC,0BAA2C;AAG3C,qBAAgC;AAChC,aAAwB;AAExB,aAAwB;AAExB,0BAA6B;AAgBtB,MAAM,oBAAoB,CAAC,UAAsB,aAAkC;AACxF,MAAI,aAAa,SAAS,SAAS,SAAS;AAC5C,aAAW,CAAC,OAAO,IAAI,KAAK,SAAS,QAAQ,GAAG;AAC9C,kBAAc,QAAQ,SAAS,KAAK,KAAK;AAAA,EAC3C;AACA,SAAO,eAAe;AACxB;AAkCA,MAAM,YAAY,CAAC,SAAiC,WAAW,KAAK,IAAI;
|
|
4
|
+
"sourcesContent": ["/**\n * Verified webhook ingestion through the authoritative Control boundary.\n *\n * @see packages/smithers/agent/triggers/docs/api.md\n * @since 0.1.0\n */\n\nimport * as ControlChannels from \"@smthrs/control/Channels\"\nimport type { ControlError } from \"@smthrs/control/ControlError\"\nimport { InvalidInput, Unauthorized } from \"@smthrs/control/ControlError\"\nimport type { Receipt, RunSummary } from \"@smthrs/control/ControlSchema\"\nimport type { CredentialRef } from \"@smthrs/control/Credential\"\nimport * as ControlWebhook from \"@smthrs/control/WebhookChannel\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Channel from \"./Channel.ts\"\nimport { TriggerError } from \"./TriggerError.ts\"\n\n/**\n * Compares a supplied byte string against the expected one without returning\n * early on a mismatch.\n *\n * The loop runs exactly `expected.length` times, so its iteration count is\n * fixed by the secret side of the comparison and never by the caller's. Reading\n * the longer of the two instead let a caller lengthen its input until the work\n * stopped growing, which reports the expected signature's length. The length\n * difference is folded into the result, so inputs of unequal length always\n * disagree.\n *\n * @category verification\n * @since 0.1.0\n */\nexport const constantTimeEqual = (expected: Uint8Array, supplied: Uint8Array): boolean => {\n let difference = expected.length ^ supplied.length\n for (const [index, byte] of expected.entries()) {\n difference |= byte ^ (supplied[index] ?? 0)\n }\n return difference === 0\n}\n\n/**\n * Configuration for a raw-byte signature verifier.\n *\n * `expected` receives a private copy of the request bytes and the redacted\n * credential reference the channel was declared with, and answers with the\n * signature bytes the request must carry in `header`. It returns an Effect so\n * the secret is resolved through the host's resolver per request rather than\n * captured in a closure at declaration time, and so a resolution or HMAC\n * failure arrives as a typed `verification_failed` instead of a defect that\n * kills the fiber.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface SignatureConfig {\n readonly header: string\n readonly expected: (\n body: Uint8Array,\n credential: Redacted.Redacted<CredentialRef>\n ) => Effect.Effect<Uint8Array, TriggerError>\n}\n\n/**\n * Copies request bytes into memory nobody else holds.\n *\n * `body.slice()` is not enough: a Node `Buffer` is a `Uint8Array` whose\n * `slice` is an alias of `subarray` and answers with a view over the same\n * memory, so a caller that reused its `Buffer` after handing it over changed\n * what got verified, and a verifier that edited the bytes it was handed edited\n * the caller's. `Uint8Array.from` always allocates, and it copies only the\n * viewed range of an offset view and only a snapshot of a `SharedArrayBuffer`.\n */\nconst ownedCopy = (body: Uint8Array): Uint8Array => Uint8Array.from(body)\n\n/**\n * Reads a header whose name may be spelled in any case.\n *\n * The lowercase form and the declared spelling are tried first, then every\n * other key whose lowercase form matches. HTTP header names are\n * case-insensitive, and a host that keeps the sender's capitalisation used to\n * fail a lowercase declaration.\n */\nconst headerValue = (\n headers: Channel.RawInbound[\"headers\"],\n name: string\n): string | undefined => {\n const lower = name.toLowerCase()\n const direct = headers[lower] ?? headers[name]\n if (direct !== undefined) return direct\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined && key.toLowerCase() === lower) return value\n }\n return undefined\n}\n\n/**\n * Builds a verifier that compares a signature header in constant time.\n *\n * An absent or empty header is refused before `expected` runs, and an\n * `expected` that answers with zero bytes is refused after it. Neither is a\n * comparison the constant-time equality can decide: it agrees on two empty\n * byte strings, so a request carrying no signature at all would have\n * authenticated against a secret that resolved to the empty string. A\n * zero-length expected signature is a misconfigured credential, never a valid\n * one, so the door stays closed instead of opening for everyone.\n *\n * Every refusal carries the same message, `webhook signature in <header> did\n * not verify`, whatever the reason. A failure raised by `expected` is kept in\n * `cause` only: its message names the credential reference or the resolver\n * that could not produce a secret, which is a host detail, and the refusal\n * that answers a bad signature answers a broken resolver the same way.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const makeSignatureVerifier = (config: SignatureConfig): Channel.Verify => (raw, credential) => {\n const refuse = (cause?: TriggerError) =>\n Effect.fail(\n new TriggerError({\n code: \"verification_failed\",\n message: `webhook signature in ${config.header} did not verify`,\n ...(cause === undefined ? {} : { cause })\n })\n )\n return Effect.suspend(() => {\n const supplied = headerValue(raw.headers, config.header)\n if (supplied === undefined || supplied.length === 0) {\n return refuse()\n }\n const actual = new TextEncoder().encode(supplied)\n // The verifier gets its own copy: nothing it does to these bytes can reach\n // the buffer that is about to be fingerprinted and decoded.\n return config.expected(ownedCopy(raw.body), credential).pipe(\n Effect.matchEffect({\n onFailure: (error) => refuse(error),\n onSuccess: (expected) =>\n expected.length > 0 && constantTimeEqual(expected, actual)\n ? Effect.void\n : refuse()\n })\n )\n })\n}\n\n/**\n * Webhook declaration configuration.\n *\n * `credential` is required. It used to default to a reference named after the\n * channel, so a webhook declared without one verified against whatever\n * credential happened to share its name instead of being refused, and two\n * declarations differing only in credential verified identically.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Config<Payload, Outbound = never> extends Channel.Config<Payload, RunSummary, Outbound> {\n readonly credential: Redacted.Redacted<CredentialRef>\n}\n\n/**\n * A webhook door that can only ingest through `Channels` and `Control`.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface Webhook {\n readonly name: string\n readonly register: Effect.Effect<void, never, ControlChannels.Channels>\n readonly ingest: (\n raw: Channel.RawInbound\n ) => Effect.Effect<Receipt, ControlError | TriggerError, ControlChannels.Channels>\n}\n\nconst invalidInput = (issue: string): InvalidInput => new InvalidInput({ issue })\n\nconst toControlChannel = <Payload, Outbound>(\n config: Config<Payload, Outbound>\n): ControlChannels.Channel<Payload> => {\n const channel = ControlWebhook.make({\n name: config.name,\n schema: config.schema,\n credential: config.credential,\n // The message is fixed here rather than forwarded from the verifier: a\n // custom `verify` may say why it refused, and that reason travels toward\n // the unauthenticated sender on the same error that answers a bad\n // signature. `Unauthorized` carries no cause, so nothing else survives\n // the crossing.\n verify: (raw, credential) =>\n config.verify(raw, credential).pipe(\n Effect.mapError(() => new Unauthorized({ message: `webhook ${config.name} did not verify the request` }))\n ),\n map: (payload) => {\n const inbound = config.inbound(payload)\n if (\"start\" in inbound) {\n return Effect.succeed({\n _tag: \"Start\" as const,\n flowId: inbound.start.flowId,\n input: inbound.start.input\n })\n }\n return Schema.decodeUnknownEffect(Schema.Json)(inbound.signal.value).pipe(\n Effect.map(\n (value) => ({\n _tag: \"Signal\" as const,\n runId: inbound.signal.runId,\n signal: {\n name: inbound.signal.stepId,\n payload: value\n }\n })\n ),\n Effect.mapError((error) => invalidInput(String(error)))\n )\n },\n project: (run) => {\n if (config.outbound === undefined) {\n return {\n cursor: String(run.updatedAt),\n operation: \"noop\" as const,\n message: null\n }\n }\n return {\n cursor: String(run.updatedAt),\n operation: \"post\" as const,\n message: config.outbound(run)\n }\n }\n })\n return channel\n}\n\n/**\n * Builds a webhook door whose only dispatch path is the Control channel\n * coordinator.\n *\n * Verification occurs inside `Channels.ingest` before the adapter's JSON or\n * schema decoder and before any Control operation.\n *\n * `ingest` does not register: a channel is registered once, deliberately,\n * through {@link Webhook.register}, so traffic to an unregistered channel is\n * reported as unavailable rather than silently self-registering the door it\n * arrived at.\n *\n * `ingest` also copies `body`, `headers`, and `idempotencyKey` before anything\n * reads them. Verification, delivery fingerprinting, and decoding then all see\n * one private snapshot, so a verifier that edits the bytes it was handed, or a\n * caller that mutates its own object between building this Effect and running\n * it, cannot authenticate one payload and have another decoded. A\n * `SharedArrayBuffer`-backed view is copied out of shared memory by the same\n * step.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <Payload, Outbound = never>(\n config: Config<Payload, Outbound>\n): Webhook => {\n const channel = toControlChannel(config)\n const register = Effect.flatMap(ControlChannels.Channels, (channels) => channels.register(channel))\n return {\n name: config.name,\n register,\n ingest: (raw) => {\n // Copied here rather than inside the Effect: the copy has to happen when\n // the caller hands the request over, not when the returned Effect\n // eventually runs, or a caller that reuses its own buffer in between\n // changes what gets authenticated.\n const snapshot: Channel.RawInbound = {\n body: ownedCopy(raw.body),\n headers: { ...raw.headers },\n idempotencyKey: raw.idempotencyKey\n }\n return Effect.gen(function*() {\n const channels = yield* ControlChannels.Channels\n return yield* channels.ingest({ channel: config.name, raw: snapshot })\n }).pipe(\n Effect.mapError((error) =>\n error instanceof Unauthorized\n ? new TriggerError({\n code: \"verification_failed\",\n message: `webhook ${config.name} did not verify the request`,\n cause: error\n })\n : error\n )\n )\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAO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ED
|
@@ -42,6 +42,25 @@ export const constantTimeEqual = (expected, supplied) => {
|
|
|
42
42
|
* viewed range of an offset view and only a snapshot of a `SharedArrayBuffer`.
|
|
43
43
|
*/
|
|
44
44
|
const ownedCopy = (body) => Uint8Array.from(body);
|
|
45
|
+
/**
|
|
46
|
+
* Reads a header whose name may be spelled in any case.
|
|
47
|
+
*
|
|
48
|
+
* The lowercase form and the declared spelling are tried first, then every
|
|
49
|
+
* other key whose lowercase form matches. HTTP header names are
|
|
50
|
+
* case-insensitive, and a host that keeps the sender's capitalisation used to
|
|
51
|
+
* fail a lowercase declaration.
|
|
52
|
+
*/
|
|
53
|
+
const headerValue = (headers, name) => {
|
|
54
|
+
const lower = name.toLowerCase();
|
|
55
|
+
const direct = headers[lower] ?? headers[name];
|
|
56
|
+
if (direct !== undefined)
|
|
57
|
+
return direct;
|
|
58
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
59
|
+
if (value !== undefined && key.toLowerCase() === lower)
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
};
|
|
45
64
|
/**
|
|
46
65
|
* Builds a verifier that compares a signature header in constant time.
|
|
47
66
|
*
|
|
@@ -69,7 +88,7 @@ export const makeSignatureVerifier = (config) => (raw, credential) => {
|
|
|
69
88
|
...(cause === undefined ? {} : { cause })
|
|
70
89
|
}));
|
|
71
90
|
return Effect.suspend(() => {
|
|
72
|
-
const supplied = raw.headers
|
|
91
|
+
const supplied = headerValue(raw.headers, config.header);
|
|
73
92
|
if (supplied === undefined || supplied.length === 0) {
|
|
74
93
|
return refuse();
|
|
75
94
|
}
|
package/dist/esm/Webhook.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Webhook.js","sourceRoot":"","sources":["../../src/Webhook.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,eAAe,MAAM,0BAA0B,CAAA;AAE3D,OAAO,EAAE,YAAY,EAAE,YAAY,E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AG,EAAE,QAAQ,EAAE,CAAC,CAAA;YACxE,CAAC,CAAC,CAAC,IAAI,CACL,MAAM,CAAC,QAAQ,CAAC,CAAC,KAAK,EAAE,EAAE,CACxB,KAAK,YAAY,YAAY;gBAC3B,CAAC,CAAC,IAAI,YAAY,CAAC;oBACjB,IAAI,EAAE,qBAAqB;oBAC3B,OAAO,EAAE,WAAW,MAAM,CAAC,IAAI,6BAA6B;oBAC5D,KAAK,EAAE,KAAK;iBACb,CAAC;gBACF,CAAC,CAAC,KAAK,CACV,CACF,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC,CAAA","sourcesContent":["/**\n * Verified webhook ingestion through the authoritative Control boundary.\n *\n * @see packages/smithers/agent/triggers/docs/api.md\n * @since 0.1.0\n */\n\nimport * as ControlChannels from \"@smthrs/control/Channels\"\nimport type { ControlError } from \"@smthrs/control/ControlError\"\nimport { InvalidInput, Unauthorized } from \"@smthrs/control/ControlError\"\nimport type { Receipt, RunSummary } from \"@smthrs/control/ControlSchema\"\nimport type { CredentialRef } from \"@smthrs/control/Credential\"\nimport * as ControlWebhook from \"@smthrs/control/WebhookChannel\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Channel from \"./Channel.ts\"\nimport { TriggerError } from \"./TriggerError.ts\"\n\n/**\n * Compares a supplied byte string against the expected one without returning\n * early on a mismatch.\n *\n * The loop runs exactly `expected.length` times, so its iteration count is\n * fixed by the secret side of the comparison and never by the caller's. Reading\n * the longer of the two instead let a caller lengthen its input until the work\n * stopped growing, which reports the expected signature's length. The length\n * difference is folded into the result, so inputs of unequal length always\n * disagree.\n *\n * @category verification\n * @since 0.1.0\n */\nexport const constantTimeEqual = (expected: Uint8Array, supplied: Uint8Array): boolean => {\n let difference = expected.length ^ supplied.length\n for (const [index, byte] of expected.entries()) {\n difference |= byte ^ (supplied[index] ?? 0)\n }\n return difference === 0\n}\n\n/**\n * Configuration for a raw-byte signature verifier.\n *\n * `expected` receives a private copy of the request bytes and the redacted\n * credential reference the channel was declared with, and answers with the\n * signature bytes the request must carry in `header`. It returns an Effect so\n * the secret is resolved through the host's resolver per request rather than\n * captured in a closure at declaration time, and so a resolution or HMAC\n * failure arrives as a typed `verification_failed` instead of a defect that\n * kills the fiber.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface SignatureConfig {\n readonly header: string\n readonly expected: (\n body: Uint8Array,\n credential: Redacted.Redacted<CredentialRef>\n ) => Effect.Effect<Uint8Array, TriggerError>\n}\n\n/**\n * Copies request bytes into memory nobody else holds.\n *\n * `body.slice()` is not enough: a Node `Buffer` is a `Uint8Array` whose\n * `slice` is an alias of `subarray` and answers with a view over the same\n * memory, so a caller that reused its `Buffer` after handing it over changed\n * what got verified, and a verifier that edited the bytes it was handed edited\n * the caller's. `Uint8Array.from` always allocates, and it copies only the\n * viewed range of an offset view and only a snapshot of a `SharedArrayBuffer`.\n */\nconst ownedCopy = (body: Uint8Array): Uint8Array => Uint8Array.from(body)\n\n/**\n * Builds a verifier that compares a signature header in constant time.\n *\n * An absent or empty header is refused before `expected` runs, and an\n * `expected` that answers with zero bytes is refused after it. Neither is a\n * comparison the constant-time equality can decide: it agrees on two empty\n * byte strings, so a request carrying no signature at all would have\n * authenticated against a secret that resolved to the empty string. A\n * zero-length expected signature is a misconfigured credential, never a valid\n * one, so the door stays closed instead of opening for everyone.\n *\n * Every refusal carries the same message, `webhook signature in <header> did\n * not verify`, whatever the reason. A failure raised by `expected` is kept in\n * `cause` only: its message names the credential reference or the resolver\n * that could not produce a secret, which is a host detail, and the refusal\n * that answers a bad signature answers a broken resolver the same way.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const makeSignatureVerifier = (config: SignatureConfig): Channel.Verify => (raw, credential) => {\n const refuse = (cause?: TriggerError) =>\n Effect.fail(\n new TriggerError({\n code: \"verification_failed\",\n message: `webhook signature in ${config.header} did not verify`,\n ...(cause === undefined ? {} : { cause })\n })\n )\n return Effect.suspend(() => {\n const supplied = raw.headers[config.header.toLowerCase()] ?? raw.headers[config.header]\n if (supplied === undefined || supplied.length === 0) {\n return refuse()\n }\n const actual = new TextEncoder().encode(supplied)\n // The verifier gets its own copy: nothing it does to these bytes can reach\n // the buffer that is about to be fingerprinted and decoded.\n return config.expected(ownedCopy(raw.body), credential).pipe(\n Effect.matchEffect({\n onFailure: (error) => refuse(error),\n onSuccess: (expected) =>\n expected.length > 0 && constantTimeEqual(expected, actual)\n ? Effect.void\n : refuse()\n })\n )\n })\n}\n\n/**\n * Webhook declaration configuration.\n *\n * `credential` is required. It used to default to a reference named after the\n * channel, so a webhook declared without one verified against whatever\n * credential happened to share its name instead of being refused, and two\n * declarations differing only in credential verified identically.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Config<Payload, Outbound = never> extends Channel.Config<Payload, RunSummary, Outbound> {\n readonly credential: Redacted.Redacted<CredentialRef>\n}\n\n/**\n * A webhook door that can only ingest through `Channels` and `Control`.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface Webhook {\n readonly name: string\n readonly register: Effect.Effect<void, never, ControlChannels.Channels>\n readonly ingest: (\n raw: Channel.RawInbound\n ) => Effect.Effect<Receipt, ControlError | TriggerError, ControlChannels.Channels>\n}\n\nconst invalidInput = (issue: string): InvalidInput => new InvalidInput({ issue })\n\nconst toControlChannel = <Payload, Outbound>(\n config: Config<Payload, Outbound>\n): ControlChannels.Channel<Payload> => {\n const channel = ControlWebhook.make({\n name: config.name,\n schema: config.schema,\n credential: config.credential,\n // The message is fixed here rather than forwarded from the verifier: a\n // custom `verify` may say why it refused, and that reason travels toward\n // the unauthenticated sender on the same error that answers a bad\n // signature. `Unauthorized` carries no cause, so nothing else survives\n // the crossing.\n verify: (raw, credential) =>\n config.verify(raw, credential).pipe(\n Effect.mapError(() => new Unauthorized({ message: `webhook ${config.name} did not verify the request` }))\n ),\n map: (payload) => {\n const inbound = config.inbound(payload)\n if (\"start\" in inbound) {\n return Effect.succeed({\n _tag: \"Start\" as const,\n flowId: inbound.start.flowId,\n input: inbound.start.input\n })\n }\n return Schema.decodeUnknownEffect(Schema.Json)(inbound.signal.value).pipe(\n Effect.map(\n (value) => ({\n _tag: \"Signal\" as const,\n runId: inbound.signal.runId,\n signal: {\n name: inbound.signal.stepId,\n payload: value\n }\n })\n ),\n Effect.mapError((error) => invalidInput(String(error)))\n )\n },\n project: (run) => {\n if (config.outbound === undefined) {\n return {\n cursor: String(run.updatedAt),\n operation: \"noop\" as const,\n message: null\n }\n }\n return {\n cursor: String(run.updatedAt),\n operation: \"post\" as const,\n message: config.outbound(run)\n }\n }\n })\n return channel\n}\n\n/**\n * Builds a webhook door whose only dispatch path is the Control channel\n * coordinator.\n *\n * Verification occurs inside `Channels.ingest` before the adapter's JSON or\n * schema decoder and before any Control operation.\n *\n * `ingest` does not register: a channel is registered once, deliberately,\n * through {@link Webhook.register}, so traffic to an unregistered channel is\n * reported as unavailable rather than silently self-registering the door it\n * arrived at.\n *\n * `ingest` also copies `body`, `headers`, and `idempotencyKey` before anything\n * reads them. Verification, delivery fingerprinting, and decoding then all see\n * one private snapshot, so a verifier that edits the bytes it was handed, or a\n * caller that mutates its own object between building this Effect and running\n * it, cannot authenticate one payload and have another decoded. A\n * `SharedArrayBuffer`-backed view is copied out of shared memory by the same\n * step.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <Payload, Outbound = never>(\n config: Config<Payload, Outbound>\n): Webhook => {\n const channel = toControlChannel(config)\n const register = Effect.flatMap(ControlChannels.Channels, (channels) => channels.register(channel))\n return {\n name: config.name,\n register,\n ingest: (raw) => {\n // Copied here rather than inside the Effect: the copy has to happen when\n // the caller hands the request over, not when the returned Effect\n // eventually runs, or a caller that reuses its own buffer in between\n // changes what gets authenticated.\n const snapshot: Channel.RawInbound = {\n body: ownedCopy(raw.body),\n headers: { ...raw.headers },\n idempotencyKey: raw.idempotencyKey\n }\n return Effect.gen(function*() {\n const channels = yield* ControlChannels.Channels\n return yield* channels.ingest({ channel: config.name, raw: snapshot })\n }).pipe(\n Effect.mapError((error) =>\n error instanceof Unauthorized\n ? new TriggerError({\n code: \"verification_failed\",\n message: `webhook ${config.name} did not verify the request`,\n cause: error\n })\n : error\n )\n )\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Webhook.js","sourceRoot":"","sources":["../../src/Webhook.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,eAAe,MAAM,0BAA0B,CAAA;AAE3D,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAGzE,OAAO,KAAK,cAAc,MAAM,gCAAgC,CAAA;AAChE,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,QAAoB,EAAE,QAAoB,EAAW,EAAE;IACvF,IAAI,UAAU,GAAG,QAAQ,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAA;IAClD,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC;QAC/C,UAAU,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;IAC7C,CAAC;IACD,OAAO,UAAU,KAAK,CAAC,CAAA;AACzB,CAAC,CAAA;AAwBD;;;;;;;;;GASG;AACH,MAAM,SAAS,GAAG,CAAC,IAAgB,EAAc,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;AAEzE;;;;;;;GAOG;AACH,MAAM,WAAW,GAAG,CAClB,OAAsC,EACtC,IAAY,EACQ,EAAE;IACtB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;IAChC,MAAM,MAA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ithers/agent/triggers/docs/api.md\n * @since 0.1.0\n */\n\nimport * as ControlChannels from \"@smthrs/control/Channels\"\nimport type { ControlError } from \"@smthrs/control/ControlError\"\nimport { InvalidInput, Unauthorized } from \"@smthrs/control/ControlError\"\nimport type { Receipt, RunSummary } from \"@smthrs/control/ControlSchema\"\nimport type { CredentialRef } from \"@smthrs/control/Credential\"\nimport * as ControlWebhook from \"@smthrs/control/WebhookChannel\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Redacted from \"effect/Redacted\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Channel from \"./Channel.ts\"\nimport { TriggerError } from \"./TriggerError.ts\"\n\n/**\n * Compares a supplied byte string against the expected one without returning\n * early on a mismatch.\n *\n * The loop runs exactly `expected.length` times, so its iteration count is\n * fixed by the secret side of the comparison and never by the caller's. Reading\n * the longer of the two instead let a caller lengthen its input until the work\n * stopped growing, which reports the expected signature's length. The length\n * difference is folded into the result, so inputs of unequal length always\n * disagree.\n *\n * @category verification\n * @since 0.1.0\n */\nexport const constantTimeEqual = (expected: Uint8Array, supplied: Uint8Array): boolean => {\n let difference = expected.length ^ supplied.length\n for (const [index, byte] of expected.entries()) {\n difference |= byte ^ (supplied[index] ?? 0)\n }\n return difference === 0\n}\n\n/**\n * Configuration for a raw-byte signature verifier.\n *\n * `expected` receives a private copy of the request bytes and the redacted\n * credential reference the channel was declared with, and answers with the\n * signature bytes the request must carry in `header`. It returns an Effect so\n * the secret is resolved through the host's resolver per request rather than\n * captured in a closure at declaration time, and so a resolution or HMAC\n * failure arrives as a typed `verification_failed` instead of a defect that\n * kills the fiber.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface SignatureConfig {\n readonly header: string\n readonly expected: (\n body: Uint8Array,\n credential: Redacted.Redacted<CredentialRef>\n ) => Effect.Effect<Uint8Array, TriggerError>\n}\n\n/**\n * Copies request bytes into memory nobody else holds.\n *\n * `body.slice()` is not enough: a Node `Buffer` is a `Uint8Array` whose\n * `slice` is an alias of `subarray` and answers with a view over the same\n * memory, so a caller that reused its `Buffer` after handing it over changed\n * what got verified, and a verifier that edited the bytes it was handed edited\n * the caller's. `Uint8Array.from` always allocates, and it copies only the\n * viewed range of an offset view and only a snapshot of a `SharedArrayBuffer`.\n */\nconst ownedCopy = (body: Uint8Array): Uint8Array => Uint8Array.from(body)\n\n/**\n * Reads a header whose name may be spelled in any case.\n *\n * The lowercase form and the declared spelling are tried first, then every\n * other key whose lowercase form matches. HTTP header names are\n * case-insensitive, and a host that keeps the sender's capitalisation used to\n * fail a lowercase declaration.\n */\nconst headerValue = (\n headers: Channel.RawInbound[\"headers\"],\n name: string\n): string | undefined => {\n const lower = name.toLowerCase()\n const direct = headers[lower] ?? headers[name]\n if (direct !== undefined) return direct\n for (const [key, value] of Object.entries(headers)) {\n if (value !== undefined && key.toLowerCase() === lower) return value\n }\n return undefined\n}\n\n/**\n * Builds a verifier that compares a signature header in constant time.\n *\n * An absent or empty header is refused before `expected` runs, and an\n * `expected` that answers with zero bytes is refused after it. Neither is a\n * comparison the constant-time equality can decide: it agrees on two empty\n * byte strings, so a request carrying no signature at all would have\n * authenticated against a secret that resolved to the empty string. A\n * zero-length expected signature is a misconfigured credential, never a valid\n * one, so the door stays closed instead of opening for everyone.\n *\n * Every refusal carries the same message, `webhook signature in <header> did\n * not verify`, whatever the reason. A failure raised by `expected` is kept in\n * `cause` only: its message names the credential reference or the resolver\n * that could not produce a secret, which is a host detail, and the refusal\n * that answers a bad signature answers a broken resolver the same way.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const makeSignatureVerifier = (config: SignatureConfig): Channel.Verify => (raw, credential) => {\n const refuse = (cause?: TriggerError) =>\n Effect.fail(\n new TriggerError({\n code: \"verification_failed\",\n message: `webhook signature in ${config.header} did not verify`,\n ...(cause === undefined ? {} : { cause })\n })\n )\n return Effect.suspend(() => {\n const supplied = headerValue(raw.headers, config.header)\n if (supplied === undefined || supplied.length === 0) {\n return refuse()\n }\n const actual = new TextEncoder().encode(supplied)\n // The verifier gets its own copy: nothing it does to these bytes can reach\n // the buffer that is about to be fingerprinted and decoded.\n return config.expected(ownedCopy(raw.body), credential).pipe(\n Effect.matchEffect({\n onFailure: (error) => refuse(error),\n onSuccess: (expected) =>\n expected.length > 0 && constantTimeEqual(expected, actual)\n ? Effect.void\n : refuse()\n })\n )\n })\n}\n\n/**\n * Webhook declaration configuration.\n *\n * `credential` is required. It used to default to a reference named after the\n * channel, so a webhook declared without one verified against whatever\n * credential happened to share its name instead of being refused, and two\n * declarations differing only in credential verified identically.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Config<Payload, Outbound = never> extends Channel.Config<Payload, RunSummary, Outbound> {\n readonly credential: Redacted.Redacted<CredentialRef>\n}\n\n/**\n * A webhook door that can only ingest through `Channels` and `Control`.\n *\n * @category services\n * @since 0.1.0\n */\nexport interface Webhook {\n readonly name: string\n readonly register: Effect.Effect<void, never, ControlChannels.Channels>\n readonly ingest: (\n raw: Channel.RawInbound\n ) => Effect.Effect<Receipt, ControlError | TriggerError, ControlChannels.Channels>\n}\n\nconst invalidInput = (issue: string): InvalidInput => new InvalidInput({ issue })\n\nconst toControlChannel = <Payload, Outbound>(\n config: Config<Payload, Outbound>\n): ControlChannels.Channel<Payload> => {\n const channel = ControlWebhook.make({\n name: config.name,\n schema: config.schema,\n credential: config.credential,\n // The message is fixed here rather than forwarded from the verifier: a\n // custom `verify` may say why it refused, and that reason travels toward\n // the unauthenticated sender on the same error that answers a bad\n // signature. `Unauthorized` carries no cause, so nothing else survives\n // the crossing.\n verify: (raw, credential) =>\n config.verify(raw, credential).pipe(\n Effect.mapError(() => new Unauthorized({ message: `webhook ${config.name} did not verify the request` }))\n ),\n map: (payload) => {\n const inbound = config.inbound(payload)\n if (\"start\" in inbound) {\n return Effect.succeed({\n _tag: \"Start\" as const,\n flowId: inbound.start.flowId,\n input: inbound.start.input\n })\n }\n return Schema.decodeUnknownEffect(Schema.Json)(inbound.signal.value).pipe(\n Effect.map(\n (value) => ({\n _tag: \"Signal\" as const,\n runId: inbound.signal.runId,\n signal: {\n name: inbound.signal.stepId,\n payload: value\n }\n })\n ),\n Effect.mapError((error) => invalidInput(String(error)))\n )\n },\n project: (run) => {\n if (config.outbound === undefined) {\n return {\n cursor: String(run.updatedAt),\n operation: \"noop\" as const,\n message: null\n }\n }\n return {\n cursor: String(run.updatedAt),\n operation: \"post\" as const,\n message: config.outbound(run)\n }\n }\n })\n return channel\n}\n\n/**\n * Builds a webhook door whose only dispatch path is the Control channel\n * coordinator.\n *\n * Verification occurs inside `Channels.ingest` before the adapter's JSON or\n * schema decoder and before any Control operation.\n *\n * `ingest` does not register: a channel is registered once, deliberately,\n * through {@link Webhook.register}, so traffic to an unregistered channel is\n * reported as unavailable rather than silently self-registering the door it\n * arrived at.\n *\n * `ingest` also copies `body`, `headers`, and `idempotencyKey` before anything\n * reads them. Verification, delivery fingerprinting, and decoding then all see\n * one private snapshot, so a verifier that edits the bytes it was handed, or a\n * caller that mutates its own object between building this Effect and running\n * it, cannot authenticate one payload and have another decoded. A\n * `SharedArrayBuffer`-backed view is copied out of shared memory by the same\n * step.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <Payload, Outbound = never>(\n config: Config<Payload, Outbound>\n): Webhook => {\n const channel = toControlChannel(config)\n const register = Effect.flatMap(ControlChannels.Channels, (channels) => channels.register(channel))\n return {\n name: config.name,\n register,\n ingest: (raw) => {\n // Copied here rather than inside the Effect: the copy has to happen when\n // the caller hands the request over, not when the returned Effect\n // eventually runs, or a caller that reuses its own buffer in between\n // changes what gets authenticated.\n const snapshot: Channel.RawInbound = {\n body: ownedCopy(raw.body),\n headers: { ...raw.headers },\n idempotencyKey: raw.idempotencyKey\n }\n return Effect.gen(function*() {\n const channels = yield* ControlChannels.Channels\n return yield* channels.ingest({ channel: config.name, raw: snapshot })\n }).pipe(\n Effect.mapError((error) =>\n error instanceof Unauthorized\n ? new TriggerError({\n code: \"verification_failed\",\n message: `webhook ${config.name} did not verify the request`,\n cause: error\n })\n : error\n )\n )\n }\n }\n}\n"]}
|
package/docs/README.md
CHANGED
|
@@ -47,10 +47,12 @@ at a flow by id, and the flow itself never learns that a clock started it.
|
|
|
47
47
|
|
|
48
48
|
## Install
|
|
49
49
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
50
|
+
```bash
|
|
51
|
+
npm install @smthrs/triggers@next effect
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
[Installation](./installation.md) covers what it requires at runtime and which
|
|
55
|
+
packages a running host adds.
|
|
54
56
|
|
|
55
57
|
## The smallest declaration
|
|
56
58
|
|
package/docs/api.md
CHANGED
|
@@ -20,8 +20,8 @@ Effect reads it from context. Launching goes through
|
|
|
20
20
|
[`@smthrs/control`](/api/control), and persistence through the SQL client and
|
|
21
21
|
durable writer of [`@smthrs/database`](/api/database).
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
for
|
|
23
|
+
Install it with `npm install @smthrs/triggers@next effect`. See
|
|
24
|
+
[Installation](./installation.md) for its requirements.
|
|
25
25
|
|
|
26
26
|
## Example
|
|
27
27
|
|
|
@@ -78,8 +78,9 @@ Three properties of that signature are the point of it.
|
|
|
78
78
|
never by the caller's, so a caller cannot lengthen its input until the work
|
|
79
79
|
stops growing and learn the expected signature's length.
|
|
80
80
|
|
|
81
|
-
The verifier looks the header up first in lowercase
|
|
82
|
-
so `x-hub-signature-256` and `X-Hub-Signature-256`
|
|
81
|
+
The verifier looks the header up first in lowercase, then exactly as written,
|
|
82
|
+
then under any other casing, so `x-hub-signature-256` and `X-Hub-Signature-256`
|
|
83
|
+
both resolve whichever spelling the declaration uses. An absent or
|
|
83
84
|
empty header is refused before `expected` runs, and an `expected` that answers
|
|
84
85
|
with zero bytes is refused after it, so a secret that resolves to the empty
|
|
85
86
|
string closes the door instead of opening it for everyone.
|
package/docs/installation.md
CHANGED
|
@@ -1,24 +1,18 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: "Installation"
|
|
3
|
-
description: "
|
|
3
|
+
description: "Install @smthrs/triggers from npm, what it requires at runtime, the import forms it publishes, and the packages a running host adds on top."
|
|
4
4
|
sidebar:
|
|
5
5
|
order: 1
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
## Get the package
|
|
9
9
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
The installed manifest resolves to the synchronized RC:
|
|
13
|
-
|
|
14
|
-
```json
|
|
15
|
-
{
|
|
16
|
-
"dependencies": {
|
|
17
|
-
"@smthrs/triggers": "1.0.0-rc.1"
|
|
18
|
-
}
|
|
19
|
-
}
|
|
10
|
+
```bash
|
|
11
|
+
npm install @smthrs/triggers@next effect
|
|
20
12
|
```
|
|
21
13
|
|
|
14
|
+
The `next` tag carries the 1.0 release candidates.
|
|
15
|
+
|
|
22
16
|
## Requirements
|
|
23
17
|
|
|
24
18
|
- Node.js 26.4.0 or later.
|
|
@@ -29,7 +23,8 @@ The installed manifest resolves to the synchronized RC:
|
|
|
29
23
|
- [`@smthrs/database`](/api/database), for the SQL client and the durable
|
|
30
24
|
writer that `SqlTriggerStore` writes through.
|
|
31
25
|
|
|
32
|
-
|
|
26
|
+
`@smthrs/control` and `@smthrs/database` are ordinary dependencies and install
|
|
27
|
+
with the package. `effect` is a peer dependency, so the install line names it.
|
|
33
28
|
|
|
34
29
|
## Import forms
|
|
35
30
|
|
package/docs/troubleshooting.md
CHANGED
|
@@ -144,8 +144,8 @@ than expecting it in the message a sender receives.
|
|
|
144
144
|
**What to change.** Check three things in order.
|
|
145
145
|
|
|
146
146
|
1. The header name in `SignatureConfig.header`. The verifier looks it up first
|
|
147
|
-
in lowercase
|
|
148
|
-
cause, but a wrong name is.
|
|
147
|
+
in lowercase, then exactly as written, then under any other casing, so a
|
|
148
|
+
casing mismatch is not the cause, but a wrong name is.
|
|
149
149
|
2. The bytes `SignatureConfig.expected` returns. They are compared against the
|
|
150
150
|
UTF-8 encoding of the header value, so an implementation that returns raw
|
|
151
151
|
HMAC bytes where the provider sends hex will never match. Return the encoded
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smthrs/triggers",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.0.0-rc.
|
|
4
|
+
"version": "1.0.0-rc.8",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"smthrs": {
|
|
7
7
|
"group": "agent"
|
|
@@ -206,8 +206,8 @@
|
|
|
206
206
|
"tag": "next"
|
|
207
207
|
},
|
|
208
208
|
"dependencies": {
|
|
209
|
-
"@smthrs/control": "1.0.0-rc.
|
|
210
|
-
"@smthrs/database": "1.0.0-rc.
|
|
209
|
+
"@smthrs/control": "1.0.0-rc.8",
|
|
210
|
+
"@smthrs/database": "1.0.0-rc.8"
|
|
211
211
|
},
|
|
212
212
|
"peerDependencies": {
|
|
213
213
|
"effect": "^4.0.4"
|
package/src/Webhook.ts
CHANGED
|
@@ -73,6 +73,27 @@ export interface SignatureConfig {
|
|
|
73
73
|
*/
|
|
74
74
|
const ownedCopy = (body: Uint8Array): Uint8Array => Uint8Array.from(body)
|
|
75
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Reads a header whose name may be spelled in any case.
|
|
78
|
+
*
|
|
79
|
+
* The lowercase form and the declared spelling are tried first, then every
|
|
80
|
+
* other key whose lowercase form matches. HTTP header names are
|
|
81
|
+
* case-insensitive, and a host that keeps the sender's capitalisation used to
|
|
82
|
+
* fail a lowercase declaration.
|
|
83
|
+
*/
|
|
84
|
+
const headerValue = (
|
|
85
|
+
headers: Channel.RawInbound["headers"],
|
|
86
|
+
name: string
|
|
87
|
+
): string | undefined => {
|
|
88
|
+
const lower = name.toLowerCase()
|
|
89
|
+
const direct = headers[lower] ?? headers[name]
|
|
90
|
+
if (direct !== undefined) return direct
|
|
91
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
92
|
+
if (value !== undefined && key.toLowerCase() === lower) return value
|
|
93
|
+
}
|
|
94
|
+
return undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
76
97
|
/**
|
|
77
98
|
* Builds a verifier that compares a signature header in constant time.
|
|
78
99
|
*
|
|
@@ -103,7 +124,7 @@ export const makeSignatureVerifier = (config: SignatureConfig): Channel.Verify =
|
|
|
103
124
|
})
|
|
104
125
|
)
|
|
105
126
|
return Effect.suspend(() => {
|
|
106
|
-
const supplied = raw.headers
|
|
127
|
+
const supplied = headerValue(raw.headers, config.header)
|
|
107
128
|
if (supplied === undefined || supplied.length === 0) {
|
|
108
129
|
return refuse()
|
|
109
130
|
}
|