@theokit/gateway 0.7.1 → 0.9.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 +121 -0
- package/README.md +82 -0
- package/dist/index.cjs +212 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +177 -8
- package/dist/index.d.ts +177 -8
- package/dist/index.js +207 -6
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,126 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.9.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- b38172b: **The peer floor on `@theokit/gateway` rises with this release.** Every adapter now implements
|
|
8
|
+
`deliver` over `runHandler`, and neither exists in an older core — an adapter installed against one
|
|
9
|
+
does not build. `dep-check` caught that by building the whole workspace against the floor each
|
|
10
|
+
package claimed, which is the one thing a version range cannot tell you by reading it.
|
|
11
|
+
|
|
12
|
+
The floor is set in the version commit rather than here, because a range cannot name a version that
|
|
13
|
+
does not exist yet: raised in the workspace, the same gate then fails the other way round — every
|
|
14
|
+
adapter declaring a floor above the core installed beside it. That is the shape `fa70153` used when
|
|
15
|
+
these ranges were first written.
|
|
16
|
+
|
|
17
|
+
`deliver(event)` — every adapter can now be handed an event that arrived out of band (#83).
|
|
18
|
+
|
|
19
|
+
`onInbound` was the seam every adapter implemented and it had no public counterpart. Six platforms
|
|
20
|
+
self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync loop, IMAP — so
|
|
21
|
+
the asymmetry stayed invisible: `GatewayRunner` worked for eight platforms and silently did nothing
|
|
22
|
+
for LINE and WhatsApp Cloud, whose payloads arrive on an HTTP route the application owns. Every app
|
|
23
|
+
wired those two by hand, beside the runner rather than through it.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
const outcome = await adapter.deliver(event); // "ok" | "no_handler" | "handler_threw"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The three outcomes are distinguished because a caller acts on them differently: answering a webhook
|
|
30
|
+
200 when nobody was subscribed tells the provider to stop retrying a message nothing received.
|
|
31
|
+
|
|
32
|
+
`BasePlatformAdapter.runHandler` holds the containment once, where ten copies of it used to live —
|
|
33
|
+
a handler is user code, its throw is named as the handler's failure rather than the platform's, and
|
|
34
|
+
delivery continues. Each adapter's `deliver` is one line over it.
|
|
35
|
+
|
|
36
|
+
Also: `gateway-sms`'s `createWebhookServer` now signs against the configured `publicUrl` (#90).
|
|
37
|
+
Twilio verifies against the URL it POSTed to, and behind a proxy that rewrites `host` — a tunnel, an
|
|
38
|
+
ingress, a load balancer terminating TLS — the reconstruction from headers yields the internal
|
|
39
|
+
address, so a correct signature fails on every delivery. `publicUrl` is required by all three
|
|
40
|
+
backend option shapes and documented as "used by signature verifier"; until now no source file read
|
|
41
|
+
it. The header reconstruction stays as the fallback for an app served directly.
|
|
42
|
+
|
|
43
|
+
- 4b1d4bb: The half of an Express webhook server that is the same everywhere now lives in one place (#89).
|
|
44
|
+
|
|
45
|
+
`gateway-line` and `gateway-sms` each shipped one and shared 101 of ~170 lines: the lazy `express`
|
|
46
|
+
load, the raw-body capture with the hang it documents, and the start/stop lifecycle. What differs —
|
|
47
|
+
signature verification, body parsing, routing — stayed where it belongs.
|
|
48
|
+
|
|
49
|
+
It had already been paid for. A write-once latch made `start()` after `stop()` return without
|
|
50
|
+
creating a listener, which is a port nothing answers on with no error and no log, and the fix had to
|
|
51
|
+
be applied to both files by one commit because the latch lived in the copied half.
|
|
52
|
+
|
|
53
|
+
`@theokit/gateway` now exports `loadPeer`, `rawBodyCapture` and `listenerLifecycle`. **This does not
|
|
54
|
+
make express a dependency of the core**: nothing in that module imports it. Every shape is
|
|
55
|
+
structural — a request is whatever has `readableEnded` and `on`, a listener is whatever has `listen`
|
|
56
|
+
and `close` — so the two packages that use express keep declaring it and the core never learns the
|
|
57
|
+
name.
|
|
58
|
+
|
|
59
|
+
Every adapter README now states how inbound reaches it (#91): a webhook the application must
|
|
60
|
+
authenticate, a WebSocket, a sync loop, or an SDK that owns its own HTTP server. The three that have
|
|
61
|
+
no webhook say so with the reason, because an absence that is a decision should not read as a gap.
|
|
62
|
+
|
|
63
|
+
- 348bc02: WhatsApp: send to the address that routes, and answer where the message came from (#82, #84).
|
|
64
|
+
|
|
65
|
+
**A send that WhatsApp discards no longer reports success.** Baileys hands back a
|
|
66
|
+
locally-generated `wamid` whether or not the JID routes anywhere, and the backend treated that id
|
|
67
|
+
as proof of delivery — so a message nobody received was recorded as a success by the caller's log,
|
|
68
|
+
its metrics and its retry logic. Measured on a real account: `5535998838687` and `553598838687` are
|
|
69
|
+
the same Brazilian line, both answered `ok: true`, and only the second arrived.
|
|
70
|
+
|
|
71
|
+
`send` now asks WhatsApp which form it routes to before sending, and refuses a number the server
|
|
72
|
+
does not know with `undeliverable` naming the number. That fixes the Brazilian ninth digit without a
|
|
73
|
+
Brazil-specific rule anywhere in this package — the answer is whatever the server says, for any
|
|
74
|
+
country. The lookup is cached for the life of the session, so it costs one round-trip per recipient.
|
|
75
|
+
|
|
76
|
+
**An inbound event now carries the address it arrived on**, as `whatsapp.channelJid`. `channel.id`
|
|
77
|
+
is normalised to digits — which is what an allowlist compares — and that normalisation strips the
|
|
78
|
+
domain, the part that says whether an address is a phone, a group, or an account's linked identity.
|
|
79
|
+
A note-to-self arrives addressed by LID, so replying to `channel.id` rebuilt `…@s.whatsapp.net`, an
|
|
80
|
+
address that does not exist.
|
|
81
|
+
|
|
82
|
+
**`send` accepts a qualified JID verbatim.** A `to` containing `@` is already an address and is
|
|
83
|
+
passed through untouched, where it used to become `231116569108705@lid@s.whatsapp.net`. So
|
|
84
|
+
answering an inbound event is now:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
await adapter.sendMessage({
|
|
88
|
+
channel: { id: event.whatsapp.channelJid ?? event.channel.id, type: "dm" },
|
|
89
|
+
text,
|
|
90
|
+
});
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Not affected: the Cloud backend. Meta rejects an unroutable recipient with an error code, so the
|
|
94
|
+
same mistake surfaces there instead of vanishing.
|
|
95
|
+
|
|
96
|
+
## 0.8.0
|
|
97
|
+
|
|
98
|
+
### Minor Changes
|
|
99
|
+
|
|
100
|
+
- 9729ab3: The redactor covers this domain's credentials, and says which it does not.
|
|
101
|
+
|
|
102
|
+
`Security.redact` ships patterns for AI and cloud provider keys. Measured across the sixteen
|
|
103
|
+
credential fields these ten adapters declare, it masked one: Slack's `xoxb-`, which is one of its
|
|
104
|
+
built-ins. On a Telegram token it was worse than absent — a token is `<bot_id>:<secret>`, the numeric
|
|
105
|
+
prefix is the bot's PUBLIC user id, and the SDK's `key=value` matcher stops at the colon, so
|
|
106
|
+
`token=8123456789:AAF…` came out as `token=***:AAF…`.
|
|
107
|
+
|
|
108
|
+
Six shapes with a distinctive structure — Telegram, Discord, Slack's app token, Matrix, WhatsApp,
|
|
109
|
+
Teams — are now replaced entirely before the text reaches the SDK. Entirely rather than the SDK's
|
|
110
|
+
`first6…last4`, because the six leading characters of a token identify the account it belongs to.
|
|
111
|
+
|
|
112
|
+
Ten fields are recorded as deliberately uncovered, each with its reason. 32 lowercase hex is also an
|
|
113
|
+
md5 digest and a dashless UUID; 26 lowercase alphanumerics is a ULID; a passphrase is
|
|
114
|
+
indistinguishable from prose. A pattern wide enough to catch those eats the correlation ids and
|
|
115
|
+
trace ids a developer reads an error log to find, and losing one costs a debugging session.
|
|
116
|
+
|
|
117
|
+
`redactSecrets` masks locally rather than registering with `Security.addPattern`. Registering did two
|
|
118
|
+
things wrong: the SDK applies extra patterns before its own `key=value` rule, so claiming a value
|
|
119
|
+
there DOWNGRADED `password=***` to `password=hunter…aple`; and it mutates module state inside the
|
|
120
|
+
SDK, so an app importing this package inherited these shapes in its own unrelated redaction.
|
|
121
|
+
|
|
122
|
+
New exports: `redactSecrets`, `maskShapes`, `CREDENTIAL_SHAPES`.
|
|
123
|
+
|
|
3
124
|
## 0.7.1
|
|
4
125
|
|
|
5
126
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -13,6 +13,31 @@ pnpm add @theokit/gateway-telegram grammy
|
|
|
13
13
|
pnpm add @theokit/gateway-discord discord.js
|
|
14
14
|
```
|
|
15
15
|
|
|
16
|
+
|
|
17
|
+
## How each adapter treats `OutboundMessage.format`
|
|
18
|
+
|
|
19
|
+
**All ten honour it** — they read the field and let it decide what the platform receives. What they can DO with it differs by platform, and a consumer should not have
|
|
20
|
+
to read ten packages to learn which — so the classes are stated here.
|
|
21
|
+
|
|
22
|
+
| Platform | What it does with `format` |
|
|
23
|
+
|---|---|
|
|
24
|
+
| telegram | sets `parse_mode` |
|
|
25
|
+
| slack | sets `mrkdwn` |
|
|
26
|
+
| matrix | `html` only: sends `formatted_body` + `format: org.matrix.custom.html`, retrying as plain text if the homeserver refuses it. **`markdown` is dropped with a warning** — `formatted_body` promises HTML, and putting markdown there renders literal asterisks AND silently eats any `<tag>` in the text |
|
|
27
|
+
| teams | sets `textFormat` on the activity |
|
|
28
|
+
| email | sends an `html` part **alongside** `text`, never instead of it. `html` passes through verbatim (the caller owns that trust boundary); `markdown` is HTML-escaped into a `<pre>` block, so it is preserved and readable, not parsed |
|
|
29
|
+
| discord, mattermost | markdown is native, so `markdown` needs no flag; **`plain` escapes** `*_\`~` so a user's literal asterisks stay literal |
|
|
30
|
+
| line, sms, whatsapp | the platform carries no formatting on this message type — the adapter logs once that the declared format was dropped, rather than discarding it in silence |
|
|
31
|
+
|
|
32
|
+
**What none of them does is convert markdown to a platform's dialect.** `format` states the
|
|
33
|
+
caller's INTENT and lets the transport act on it; translating `**bold**` into WhatsApp's
|
|
34
|
+
`*bold*` is a presentation concern and is tracked separately.
|
|
35
|
+
|
|
36
|
+
Measured 2026-08-30: before this, two of ten read the field. An agent answered
|
|
37
|
+
`**Bom Sucesso (MG)**` and LINE and WhatsApp delivered literal asterisks, which is what a
|
|
38
|
+
declared-and-ignored field costs at the far end.
|
|
39
|
+
|
|
40
|
+
|
|
16
41
|
## Architecture (5 pieces)
|
|
17
42
|
|
|
18
43
|
| Module | Responsibility |
|
|
@@ -74,6 +99,63 @@ on an unparseable payload means the 200 is never built. Mounted in a TheoKit rou
|
|
|
74
99
|
reaches that route's error boundary and is answered **500**: the platform sees a failed delivery
|
|
75
100
|
where it expected an acknowledgement.
|
|
76
101
|
|
|
102
|
+
### WhatsApp, since `theokit@0.60.0`
|
|
103
|
+
|
|
104
|
+
Until that release this was impossible rather than undocumented: `theokit/server/webhook`
|
|
105
|
+
exported no `whatsapp` validator, so the `validators` map could not carry one and the path
|
|
106
|
+
answered 404 by construction. Meta's subscribe handshake had no seam at all
|
|
107
|
+
([usetheokit/theokit#556](https://github.com/usetheokit/theokit/issues/556), filed from
|
|
108
|
+
here). Both halves exist now, and the wiring needs three things that are easy to miss:
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import { handleChannelWebhook } from "theokit/server/agent";
|
|
112
|
+
import { route } from "theokit/server/define";
|
|
113
|
+
import { whatsapp, whatsappSubscribe } from "theokit/server/webhook";
|
|
114
|
+
import { normalizeInboundMessages, parseWebhookPayload } from "@theokit/gateway-whatsapp";
|
|
115
|
+
|
|
116
|
+
const handle = ({ request }: { request: Request }) =>
|
|
117
|
+
handleChannelWebhook(request, new URL(request.url).pathname, {
|
|
118
|
+
validators: { whatsapp: whatsapp({ appSecret: process.env.META_APP_SECRET! }) },
|
|
119
|
+
subscribe: { whatsapp: whatsappSubscribe({ verifyToken: process.env.META_VERIFY_TOKEN! }) },
|
|
120
|
+
onMessage: async ({ payload }) => {
|
|
121
|
+
const envelope = parseWebhookPayload(payload);
|
|
122
|
+
if (envelope === null) return; // not a shape we know — answer normally
|
|
123
|
+
for (const event of normalizeInboundMessages(envelope)) {
|
|
124
|
+
console.log(`${event.from}: ${event.text}`);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// BOTH verbs, and `.csrf(false)` on each.
|
|
130
|
+
export const GET = route().csrf(false).policy("public").handler(handle).build();
|
|
131
|
+
export const POST = route().csrf(false).policy("public").handler(handle).build();
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- **`GET` as well as `POST`.** Meta calls the endpoint once with
|
|
135
|
+
`?hub.mode=subscribe&hub.verify_token=…&hub.challenge=…` and expects the challenge echoed as
|
|
136
|
+
`text/plain` before it delivers anything. That is what `subscribe` answers. A `GET` on a
|
|
137
|
+
platform that has a validator and no `subscribe` entry is **405**, not 404 — configured, but
|
|
138
|
+
it does not do handshakes.
|
|
139
|
+
- **`.csrf(false)` on both.** Without it the route answers `403 CSRF_INVALID: Missing
|
|
140
|
+
X-Theo-Action header` before the signature is ever checked, and Meta will never send that
|
|
141
|
+
header. `policy("public")` answers a different question — may an unauthenticated caller reach
|
|
142
|
+
this — and does not lift the CSRF gate. The HMAC is strictly stronger than the header it
|
|
143
|
+
replaces, and Meta carries no session for a third-party page to ride.
|
|
144
|
+
- **`appSecret` is the Meta *app secret*,** not the access token. It accepts an array so a
|
|
145
|
+
rotation can verify against either.
|
|
146
|
+
|
|
147
|
+
This package also exports `verifyWebhookSignature` and `verifyWebhookSubscription`, which do
|
|
148
|
+
the same two jobs. Use theokit's when you are on this seam; ours exist for an app that is not,
|
|
149
|
+
and they are what `gateway-sms` uses through its own `createWebhookServer`.
|
|
150
|
+
|
|
151
|
+
Not verified here: the `theokit` behaviour above was measured by the session that shipped
|
|
152
|
+
0.60.0, driving a scaffolded app over HTTP. What this repository checked is narrower and
|
|
153
|
+
stated as such — that `theokit@0.60.0` does export `whatsapp` and `whatsappSubscribe` from
|
|
154
|
+
`theokit/server/webhook`, that `route` lives on `theokit/server/define` rather than on the
|
|
155
|
+
`theokit/server` umbrella that warns it is deprecated, and that `parseWebhookPayload` takes the
|
|
156
|
+
`unknown` payload `onMessage` hands over. A real delivery from Meta needs an approved app and a public URL, and
|
|
157
|
+
has not happened on either side.
|
|
158
|
+
|
|
77
159
|
`parseInbound` under that name exists on `@theokit/gateway-telegram` and `@theokit/gateway-sms`,
|
|
78
160
|
with different arguments: SMS takes `(options, ctx)` because the `SignatureContext` it needs carries
|
|
79
161
|
the raw body, the headers and the URL, and `ChannelMessage` provides none of the three — so it is wired through its
|
package/dist/index.cjs
CHANGED
|
@@ -4,6 +4,30 @@ var sdk = require('@theokit/sdk');
|
|
|
4
4
|
|
|
5
5
|
// src/adapter/base.ts
|
|
6
6
|
var BasePlatformAdapter = class {
|
|
7
|
+
/**
|
|
8
|
+
* Run a subscribed handler and contain its failure. The body of {@link deliver}, written once.
|
|
9
|
+
*
|
|
10
|
+
* A handler is USER code and may throw. An adapter must contain that throw, name it as the
|
|
11
|
+
* handler's failure rather than the platform's, and keep delivering — one bad message ends
|
|
12
|
+
* neither the process nor the connection. Two adapters once discarded the rejection with `void`,
|
|
13
|
+
* which under Node's default ends the process; two more reported it as a platform-client error,
|
|
14
|
+
* sending whoever debugged their own handler to the wrong repository (#41).
|
|
15
|
+
*
|
|
16
|
+
* Ten copies of that knowledge is ten chances to get it wrong, so it lives here. The platform tag
|
|
17
|
+
* is taken from `this.platform`, which is the only part that differed between them.
|
|
18
|
+
*/
|
|
19
|
+
async runHandler(handler, event) {
|
|
20
|
+
if (handler === void 0) return "no_handler";
|
|
21
|
+
try {
|
|
22
|
+
await handler(event);
|
|
23
|
+
} catch (err) {
|
|
24
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
25
|
+
process.stderr.write(`[${this.platform}] handler threw: ${message}
|
|
26
|
+
`);
|
|
27
|
+
return "handler_threw";
|
|
28
|
+
}
|
|
29
|
+
return "ok";
|
|
30
|
+
}
|
|
7
31
|
/** Lifecycle: emit a typing indicator. Default: noop. */
|
|
8
32
|
async startTyping(_channelId) {
|
|
9
33
|
}
|
|
@@ -61,9 +85,114 @@ var GatewayLifecycleError = class extends Error {
|
|
|
61
85
|
this.code = opts.code;
|
|
62
86
|
}
|
|
63
87
|
};
|
|
88
|
+
var CREDENTIAL_SHAPES = {
|
|
89
|
+
covered: [
|
|
90
|
+
{
|
|
91
|
+
field: "gateway-telegram `token`",
|
|
92
|
+
pattern: /(?<![A-Za-z0-9])\d{8,10}:[A-Za-z0-9_-]{35}(?![A-Za-z0-9_-])/g,
|
|
93
|
+
alsoMatches: "an 8-10 digit number joined by a colon to exactly 35 url-safe characters \u2014 a timestamped identifier of that exact width would be masked"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
field: "gateway-discord `token`",
|
|
97
|
+
pattern: /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6,7}\.[A-Za-z0-9_-]{27,}(?![A-Za-z0-9_-])/g,
|
|
98
|
+
alsoMatches: "a three-part dotted identifier of those widths; a JWT's middle part is longer"
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
field: "gateway-slack `appToken`",
|
|
102
|
+
pattern: /(?<![A-Za-z0-9-])xapp-\d-[A-Z0-9]+-\d+-[a-f0-9]{32,}(?![a-f0-9])/g,
|
|
103
|
+
alsoMatches: "nothing plausible \u2014 the `xapp-` prefix and the shape are Slack's"
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
field: "gateway-matrix `accessToken`",
|
|
107
|
+
pattern: /(?<![A-Za-z0-9_])syt_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+_[A-Za-z0-9]+(?![A-Za-z0-9_-])/g,
|
|
108
|
+
alsoMatches: "nothing plausible \u2014 `syt_` is Matrix's own prefix"
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
field: "gateway-whatsapp `accessToken`",
|
|
112
|
+
pattern: /(?<![A-Za-z0-9])EAA[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
|
|
113
|
+
alsoMatches: "any identifier beginning EAA followed by 20 or more alphanumerics"
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
field: "gateway-teams `clientSecret`",
|
|
117
|
+
pattern: /(?<![A-Za-z0-9~])[A-Za-z0-9]{3}\d[A-Za-z0-9]?~[A-Za-z0-9._~-]{30,}(?![A-Za-z0-9._~-])/g,
|
|
118
|
+
alsoMatches: "an Entra-style secret is the only common value with a tilde in that position"
|
|
119
|
+
}
|
|
120
|
+
],
|
|
121
|
+
uncovered: [
|
|
122
|
+
{
|
|
123
|
+
field: "gateway-sms `authToken` (Twilio), gateway-line `channelSecret`",
|
|
124
|
+
why: "32 lowercase hex characters, which is also an md5 digest, a dashless UUID and half a git tree hash. Masking it would eat the correlation id a developer reads the log to find."
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
field: "gateway-mattermost `accessToken`",
|
|
128
|
+
why: "26 lowercase alphanumerics, which is exactly a lowercase ULID \u2014 the shape of most trace ids."
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
field: "gateway-email `password`, gateway-sms `apiSecret` and `signatureSecret` (Vonage)",
|
|
132
|
+
why: "no format of their own; a passphrase is indistinguishable from prose. The SDK's own `key=value` rule already masks these fully wherever they appear as `field=value`, and adding a pattern here made that WORSE by claiming the value first \u2014 it was masked as first6\u2026last4 instead of removed."
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
field: "gateway-slack `botToken`",
|
|
136
|
+
why: "already masked by one of the SDK's own twelve built-in patterns \u2014 `xoxb-` is Slack's and the SDK knows it. A pattern here would be a second one doing the first's work, and the field-level gate flagged its absence, which is the gate working."
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
field: "gateway-whatsapp `appSecret`",
|
|
140
|
+
why: "32 lowercase hex, the same shape as the Twilio auth token above and as every md5 and dashless UUID. Masking it would eat the correlation ids in a log."
|
|
141
|
+
},
|
|
142
|
+
{
|
|
143
|
+
field: "gateway-line `channelAccessToken`, gateway-sms `authToken` (Plivo)",
|
|
144
|
+
why: "long base64 runs with no prefix, indistinguishable from any encoded blob a platform library puts in an error message."
|
|
145
|
+
}
|
|
146
|
+
]
|
|
147
|
+
};
|
|
148
|
+
function maskShapes(text) {
|
|
149
|
+
let out = text;
|
|
150
|
+
for (const { pattern } of CREDENTIAL_SHAPES.covered) out = out.replace(pattern, "***");
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
153
|
+
function redactSecrets(value) {
|
|
154
|
+
return sdk.Security.redact(maskShapes(typeof value === "string" ? value : String(value)));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/hooks/executor.ts
|
|
158
|
+
var HOOK_PHASES = ["pre_inbound", "post_outbound", "on_error"];
|
|
159
|
+
function malformedHook(index, why) {
|
|
160
|
+
return new GatewayConfigurationError("gateway", {
|
|
161
|
+
code: "malformed_hook",
|
|
162
|
+
message: `gateway: hooks[${index}] ${why}`,
|
|
163
|
+
detail: `hooks[${index}]`
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
function assertHook(entry, index) {
|
|
167
|
+
if (typeof entry !== "object" || entry === null) {
|
|
168
|
+
throw malformedHook(index, `is ${entry === null ? "null" : typeof entry}, not a hook object`);
|
|
169
|
+
}
|
|
170
|
+
const hook = entry;
|
|
171
|
+
if (typeof hook.name !== "string" || hook.name.length === 0) {
|
|
172
|
+
throw malformedHook(
|
|
173
|
+
index,
|
|
174
|
+
"has no name \u2014 every hook is named so a log can say which one acted"
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
const declared = HOOK_PHASES.filter((phase) => hook[phase] !== void 0);
|
|
178
|
+
if (declared.length === 0) {
|
|
179
|
+
throw malformedHook(
|
|
180
|
+
index,
|
|
181
|
+
`("${hook.name}") declares none of ${HOOK_PHASES.join(", ")} \u2014 it would never run`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
for (const phase of declared) {
|
|
185
|
+
if (typeof hook[phase] !== "function") {
|
|
186
|
+
throw malformedHook(index, `("${hook.name}") declares ${phase}, which is not callable`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
64
190
|
var HookExecutor = class {
|
|
65
191
|
constructor(hooks) {
|
|
66
192
|
this.hooks = hooks;
|
|
193
|
+
hooks.forEach((hook, index) => {
|
|
194
|
+
assertHook(hook, index);
|
|
195
|
+
});
|
|
67
196
|
}
|
|
68
197
|
hooks;
|
|
69
198
|
/**
|
|
@@ -78,7 +207,7 @@ var HookExecutor = class {
|
|
|
78
207
|
decision = await h.pre_inbound(ctx);
|
|
79
208
|
} catch (err) {
|
|
80
209
|
process.stderr.write(
|
|
81
|
-
`[gateway] pre_inbound hook "${h.name}" threw: ${
|
|
210
|
+
`[gateway] pre_inbound hook "${h.name}" threw: ${redactSecrets(err.message)}
|
|
82
211
|
`
|
|
83
212
|
);
|
|
84
213
|
return {
|
|
@@ -121,6 +250,8 @@ var HookExecutor = class {
|
|
|
121
250
|
}
|
|
122
251
|
}
|
|
123
252
|
};
|
|
253
|
+
|
|
254
|
+
// src/runner/gateway-runner.ts
|
|
124
255
|
var DEFAULT_DRAIN_MS = 1e4;
|
|
125
256
|
var DEFAULT_COMMAND_PREFIXES = ["/"];
|
|
126
257
|
var GatewayRunner = class {
|
|
@@ -217,6 +348,15 @@ var GatewayRunner = class {
|
|
|
217
348
|
);
|
|
218
349
|
this.connected = false;
|
|
219
350
|
}
|
|
351
|
+
/**
|
|
352
|
+
* @internal Test seam, following `EmailAdapter._threadStoreSize`. The drain set must SHRINK: a
|
|
353
|
+
* settled dispatch that is never removed is a leak that grows for the life of the process, and it
|
|
354
|
+
* is invisible from the outside — `stop()` drains correctly either way, because settled promises
|
|
355
|
+
* resolve immediately whether or not anyone deleted them.
|
|
356
|
+
*/
|
|
357
|
+
get _inflightSize() {
|
|
358
|
+
return this.inflight.size;
|
|
359
|
+
}
|
|
220
360
|
/** @internal */
|
|
221
361
|
async dispatch(event) {
|
|
222
362
|
const ctx = this.buildContext(event);
|
|
@@ -234,10 +374,8 @@ var GatewayRunner = class {
|
|
|
234
374
|
await handler(event, ctx);
|
|
235
375
|
} catch (err) {
|
|
236
376
|
await this.hookExecutor.fireOnError({ event, error: err });
|
|
237
|
-
process.stderr.write(
|
|
238
|
-
|
|
239
|
-
`
|
|
240
|
-
);
|
|
377
|
+
process.stderr.write(`[gateway] handler error: ${redactSecrets(err.message)}
|
|
378
|
+
`);
|
|
241
379
|
}
|
|
242
380
|
})();
|
|
243
381
|
this.inflight.add(work);
|
|
@@ -409,7 +547,71 @@ function chunkByGrapheme(text, options) {
|
|
|
409
547
|
return parts;
|
|
410
548
|
}
|
|
411
549
|
|
|
550
|
+
// src/webhook/express-server.ts
|
|
551
|
+
async function loadPeer(load, onMissing) {
|
|
552
|
+
try {
|
|
553
|
+
const mod = await load();
|
|
554
|
+
return mod.default ?? mod;
|
|
555
|
+
} catch {
|
|
556
|
+
onMissing();
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
function rawBodyCapture(tag) {
|
|
560
|
+
return (rawReq, _res, next) => {
|
|
561
|
+
const req = rawReq;
|
|
562
|
+
if (req.readableEnded === true || req.complete === true) {
|
|
563
|
+
process.stderr.write(
|
|
564
|
+
`[${tag}] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash
|
|
565
|
+
`
|
|
566
|
+
);
|
|
567
|
+
req.rawBody = "";
|
|
568
|
+
next();
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
let buf = "";
|
|
572
|
+
req.setEncoding("utf8");
|
|
573
|
+
req.on("data", (chunk) => {
|
|
574
|
+
buf += chunk;
|
|
575
|
+
});
|
|
576
|
+
req.on("end", () => {
|
|
577
|
+
req.rawBody = buf;
|
|
578
|
+
next();
|
|
579
|
+
});
|
|
580
|
+
req.on("error", (err) => next(err));
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
function listenerLifecycle(opts) {
|
|
584
|
+
let started = false;
|
|
585
|
+
let stopped = false;
|
|
586
|
+
let listener;
|
|
587
|
+
return {
|
|
588
|
+
async start() {
|
|
589
|
+
if (started || opts.injected) {
|
|
590
|
+
started = true;
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
stopped = false;
|
|
594
|
+
await new Promise((resolve) => {
|
|
595
|
+
listener = opts.app.listen(opts.port, () => resolve());
|
|
596
|
+
});
|
|
597
|
+
started = true;
|
|
598
|
+
},
|
|
599
|
+
async stop() {
|
|
600
|
+
if (stopped) return;
|
|
601
|
+
stopped = true;
|
|
602
|
+
started = false;
|
|
603
|
+
const current = listener;
|
|
604
|
+
listener = void 0;
|
|
605
|
+
if (current === void 0) return;
|
|
606
|
+
await new Promise((resolve) => {
|
|
607
|
+
current.close(() => resolve());
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
|
|
412
613
|
exports.BasePlatformAdapter = BasePlatformAdapter;
|
|
614
|
+
exports.CREDENTIAL_SHAPES = CREDENTIAL_SHAPES;
|
|
413
615
|
exports.DeliveryRouter = DeliveryRouter;
|
|
414
616
|
exports.GatewayConfigurationError = GatewayConfigurationError;
|
|
415
617
|
exports.GatewayLifecycleError = GatewayLifecycleError;
|
|
@@ -419,5 +621,10 @@ exports.SessionRouter = SessionRouter;
|
|
|
419
621
|
exports.chunkByGrapheme = chunkByGrapheme;
|
|
420
622
|
exports.chunkText = chunkText;
|
|
421
623
|
exports.defaultStrategy = defaultStrategy;
|
|
624
|
+
exports.listenerLifecycle = listenerLifecycle;
|
|
625
|
+
exports.loadPeer = loadPeer;
|
|
626
|
+
exports.maskShapes = maskShapes;
|
|
627
|
+
exports.rawBodyCapture = rawBodyCapture;
|
|
628
|
+
exports.redactSecrets = redactSecrets;
|
|
422
629
|
//# sourceMappingURL=index.cjs.map
|
|
423
630
|
//# sourceMappingURL=index.cjs.map
|