@theokit/gateway-line 0.3.0 → 0.5.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 +169 -0
- package/README.md +70 -2
- package/dist/index.cjs +149 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +105 -10
- package/dist/index.d.ts +105 -10
- package/dist/index.js +149 -16
- package/dist/index.js.map +1 -1
- package/package.json +19 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,174 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 458c34c: Wire channels from descriptors, and keep the channels that connect when another cannot.
|
|
8
|
+
|
|
9
|
+
`@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
|
|
10
|
+
`ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
|
|
11
|
+
`ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
|
|
12
|
+
entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
|
|
13
|
+
`""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
|
|
14
|
+
keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
|
|
15
|
+
other error propagates. It connects nothing and makes no network call.
|
|
16
|
+
|
|
17
|
+
`GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
|
|
18
|
+
and `StartResult` is exported.
|
|
19
|
+
The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
|
|
20
|
+
connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
|
|
21
|
+
only for the ones that connected, and reports the rest with a redacted reason.
|
|
22
|
+
|
|
23
|
+
`start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
|
|
24
|
+
values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
|
|
25
|
+
but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
|
|
26
|
+
fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
|
|
27
|
+
|
|
28
|
+
`@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
|
|
29
|
+
required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
|
|
30
|
+
`GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
|
|
31
|
+
`telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
|
|
32
|
+
that is not an array of strings; through `createChannels`, an absent or empty token is rejected
|
|
33
|
+
first, as `missing_required_config`.
|
|
34
|
+
|
|
35
|
+
`@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
|
|
36
|
+
`x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
|
|
37
|
+
payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
|
|
38
|
+
`"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
|
|
39
|
+
payload holds a text message for the handler and none is subscribed: before the runner started,
|
|
40
|
+
after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
|
|
41
|
+
`"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
|
|
42
|
+
`lineChannel.create` checks field types before the adapter's constructor.
|
|
43
|
+
|
|
44
|
+
`LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
|
|
45
|
+
`"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
|
|
46
|
+
that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
|
|
47
|
+
answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
|
|
48
|
+
one event still receives the rest of the batch. Code that ignores the value is unaffected; a
|
|
49
|
+
subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
|
|
50
|
+
unchanged and still answers 200 before it dispatches.
|
|
51
|
+
|
|
52
|
+
Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
|
|
53
|
+
range stays `>=0.9.0 <1.0.0`.
|
|
54
|
+
|
|
55
|
+
### Patch Changes
|
|
56
|
+
|
|
57
|
+
- e5a2603: Group messages that do not mention the bot are no longer delivered by default on Discord, Matrix
|
|
58
|
+
and Teams; pass `requireMention: false` to keep the old behaviour.
|
|
59
|
+
|
|
60
|
+
Discord, Matrix and Teams gain a `requireMention` option that defaults to `true`. With it on, a
|
|
61
|
+
group or thread message reaches the handler only when it mentions the bot, and a DM always does.
|
|
62
|
+
Discord reads the bot's id in `mentions.users` (a direct mention or a reply that pings it; not
|
|
63
|
+
`@everyone`, `@here` or roles), and drops group messages with one stderr line until the client is
|
|
64
|
+
ready. Matrix reads `m.mentions.user_ids`, and falls back to the full user id in `body` or
|
|
65
|
+
`formatted_body` when a client sends no `m.mentions`. Teams reads `mention` entities against the
|
|
66
|
+
activity's `recipient.id`, and drops a group activity that names no recipient with one stderr line.
|
|
67
|
+
|
|
68
|
+
LINE's `deliver()` now applies the mention guard its webhook route already applied.
|
|
69
|
+
|
|
70
|
+
On all four adapters `deliver()` and the adapter's own inbound path use one rule, and `deliver()`
|
|
71
|
+
answers `"ok"` for an event the rule drops, with or without a handler subscribed.
|
|
72
|
+
|
|
73
|
+
- 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
|
|
74
|
+
|
|
75
|
+
`@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
|
|
76
|
+
`filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
|
|
77
|
+
carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
|
|
78
|
+
`supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
|
|
79
|
+
field. The runner and the router refuse an outbound carrying attachments as
|
|
80
|
+
`attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
|
|
81
|
+
`supportsAttachments`.
|
|
82
|
+
|
|
83
|
+
`@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
|
|
84
|
+
`sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
|
|
85
|
+
when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
|
|
86
|
+
than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
|
|
87
|
+
|
|
88
|
+
Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
|
|
89
|
+
with `attachments_unsupported` and makes no platform call, instead of sending the text and
|
|
90
|
+
dropping the image.
|
|
91
|
+
|
|
92
|
+
The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
|
|
93
|
+
throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
|
|
94
|
+
as a handler error is. Dispatch still does not throw.
|
|
95
|
+
|
|
96
|
+
- e980fb8: `@theokit/gateway` exports `SeenIds` (a bounded set of delivered ids) and `splitKeepingRows` (a
|
|
97
|
+
grapheme-safe split that keeps Markdown table rows whole). The SMS and LINE adapters import
|
|
98
|
+
`splitKeepingRows` instead of carrying copies; their peer floor is now `>=0.13.0`.
|
|
99
|
+
- e9be726: Keep Markdown table rows intact through translation and splitting.
|
|
100
|
+
|
|
101
|
+
`channelRendering(platform).translate` and `toDialect` now rewrite a table row (a line whose first
|
|
102
|
+
non-blank character is `|`) one cell at a time. Before, an emphasis span could open in one cell
|
|
103
|
+
and close in the next, so `| 2 x *a | b* y |` lost both stars on the ten platforms that rewrite
|
|
104
|
+
markers. Text where no span crosses a row's pipe translates exactly as before. A lone `\r` counts
|
|
105
|
+
as a line ending, as in GFM. Inline code that holds an unescaped pipe inside a row is split at
|
|
106
|
+
that pipe, as GFM splits the cell, so its backticks no longer pair and the platforms that strip
|
|
107
|
+
markers now keep them.
|
|
108
|
+
|
|
109
|
+
`splitForLine` and `splitForSMS` no longer cut a table row in two at a part
|
|
110
|
+
boundary. When a cut would fall inside a row that fits in one part, the part ends before that row
|
|
111
|
+
and the row starts the next part. A row longer than a part is still cut by length. Every
|
|
112
|
+
character is kept, and every part stays within its limit (with the `(i/N) ` prefix counted on
|
|
113
|
+
SMS, whose numbering follows the new part count) except a single grapheme longer than the limit,
|
|
114
|
+
which is emitted whole as its own part, as before. Text with no table row splits exactly as
|
|
115
|
+
before. Two rows that each fill a part exactly arrive as three parts, the second holding only the
|
|
116
|
+
line ending between them.
|
|
117
|
+
|
|
118
|
+
No export, signature, dependency or peer range changes.
|
|
119
|
+
|
|
120
|
+
## 0.4.0
|
|
121
|
+
|
|
122
|
+
### Minor Changes
|
|
123
|
+
|
|
124
|
+
- 39d06f8: Wire channels from descriptors, and keep the channels that connect when another cannot.
|
|
125
|
+
|
|
126
|
+
`@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
|
|
127
|
+
`ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
|
|
128
|
+
`ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
|
|
129
|
+
entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
|
|
130
|
+
`""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
|
|
131
|
+
keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
|
|
132
|
+
other error propagates. It connects nothing and makes no network call.
|
|
133
|
+
|
|
134
|
+
`GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
|
|
135
|
+
and `StartResult` is exported.
|
|
136
|
+
The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
|
|
137
|
+
connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
|
|
138
|
+
only for the ones that connected, and reports the rest with a redacted reason.
|
|
139
|
+
|
|
140
|
+
`start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
|
|
141
|
+
values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
|
|
142
|
+
but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
|
|
143
|
+
fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
|
|
144
|
+
|
|
145
|
+
`@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
|
|
146
|
+
required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
|
|
147
|
+
`GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
|
|
148
|
+
`telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
|
|
149
|
+
that is not an array of strings; through `createChannels`, an absent or empty token is rejected
|
|
150
|
+
first, as `missing_required_config`.
|
|
151
|
+
|
|
152
|
+
`@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
|
|
153
|
+
`x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
|
|
154
|
+
payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
|
|
155
|
+
`"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
|
|
156
|
+
payload holds a text message for the handler and none is subscribed: before the runner started,
|
|
157
|
+
after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
|
|
158
|
+
`"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
|
|
159
|
+
`lineChannel.create` checks field types before the adapter's constructor.
|
|
160
|
+
|
|
161
|
+
`LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
|
|
162
|
+
`"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
|
|
163
|
+
that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
|
|
164
|
+
answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
|
|
165
|
+
one event still receives the rest of the batch. Code that ignores the value is unaffected; a
|
|
166
|
+
subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
|
|
167
|
+
unchanged and still answers 200 before it dispatches.
|
|
168
|
+
|
|
169
|
+
Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
|
|
170
|
+
range stays `>=0.9.0 <1.0.0`.
|
|
171
|
+
|
|
3
172
|
## 0.3.0
|
|
4
173
|
|
|
5
174
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -15,8 +15,13 @@ Two ways to serve it. `createWebhookServer` mounts an Express route for you; or
|
|
|
15
15
|
yourself and hand the parsed events to `adapter.deliver(event)`, which is what makes `GatewayRunner`
|
|
16
16
|
work for a webhook platform.
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
`lineWebhookVerifier(adapter)` is a validator in the shape `theokit/server/webhook` expects
|
|
19
|
+
(`(request) => Promise<{ ok: true } | { ok: false; reason }>`), for the framework's `validators`
|
|
20
|
+
map: `validators: { line: lineWebhookVerifier(adapter) }`. It reads the raw body and the
|
|
21
|
+
`x-line-signature` header. The framework does not ship a LINE validator of its own
|
|
22
|
+
([usetheokit/theokit#590](https://github.com/usetheokit/theokit/issues/590)), so this package
|
|
23
|
+
provides it.
|
|
24
|
+
|
|
20
25
|
## Install
|
|
21
26
|
|
|
22
27
|
```bash
|
|
@@ -63,6 +68,69 @@ await server.start();
|
|
|
63
68
|
|
|
64
69
|
For local dev: `ngrok http 3000` and use the https URL.
|
|
65
70
|
|
|
71
|
+
## Channel descriptor
|
|
72
|
+
|
|
73
|
+
`lineChannel` describes this channel as data, for `createChannels` in `@theokit/gateway`: a
|
|
74
|
+
`webhook` channel whose config has a required, secret `channelSecret` and `channelAccessToken`
|
|
75
|
+
and an optional `botUserId` and `requireMention`. Its `webhook` part is how an app with its own
|
|
76
|
+
HTTP route verifies and ingests a request, in process:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
import { createChannels, GatewayRunner } from "@theokit/gateway";
|
|
80
|
+
import { LineAdapter, lineChannel } from "@theokit/gateway-line";
|
|
81
|
+
|
|
82
|
+
const { adapters, rejected } = createChannels([
|
|
83
|
+
{
|
|
84
|
+
descriptor: lineChannel,
|
|
85
|
+
config: {
|
|
86
|
+
channelSecret: process.env.LINE_CHANNEL_SECRET,
|
|
87
|
+
channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN,
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
]);
|
|
91
|
+
const [line] = adapters;
|
|
92
|
+
if (!(line instanceof LineAdapter)) throw new Error(`LINE refused: ${rejected[0]?.error.message}`);
|
|
93
|
+
|
|
94
|
+
// Ingest dispatches to the handler the runner subscribes, and a reply needs a connected adapter.
|
|
95
|
+
const runner = new GatewayRunner({
|
|
96
|
+
adapters,
|
|
97
|
+
handler: async (event, ctx) => {
|
|
98
|
+
await ctx.reply(`Echo: ${event.text}`);
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
await runner.start();
|
|
102
|
+
|
|
103
|
+
// Inside your route, with the raw body as text and the request headers:
|
|
104
|
+
async function onLineWebhook(rawBody: string, headers: Record<string, string | undefined>) {
|
|
105
|
+
if (!lineChannel.webhook.verify(line, { rawBody, headers })) return 401;
|
|
106
|
+
let payload: unknown;
|
|
107
|
+
try {
|
|
108
|
+
payload = JSON.parse(rawBody);
|
|
109
|
+
} catch {
|
|
110
|
+
return 400;
|
|
111
|
+
}
|
|
112
|
+
const outcome = await lineChannel.webhook.ingest(line, payload);
|
|
113
|
+
if (outcome === "delivered") return 200;
|
|
114
|
+
return outcome === "no_handler" ? 503 : 400;
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
- `webhook.verify` reads the `x-line-signature` header in any case and checks it against the raw
|
|
119
|
+
body with the adapter's channel secret.
|
|
120
|
+
- `webhook.ingest` answers `"malformed"` for a payload with no `events` array, or with an event
|
|
121
|
+
that is not an object, and dispatches nothing. Otherwise it dispatches through
|
|
122
|
+
`dispatchWebhookBody`, which caches each event's reply token, so the handler's `ctx.reply` uses
|
|
123
|
+
the reply API. A follow or other non-text event is skipped and still answers `"delivered"`, and
|
|
124
|
+
so does an empty `events` array (the console's webhook verification).
|
|
125
|
+
- `webhook.ingest` answers `"no_handler"`, and dispatches nothing, when the payload holds a text
|
|
126
|
+
message for the handler and no handler is subscribed: before `runner.start()` resolves, after
|
|
127
|
+
`runner.stop()`, or when LINE's connect failed under `connectFailure: "isolate"`. Do not answer
|
|
128
|
+
it with 200: LINE redelivers only a request that was not acknowledged, and only when webhook
|
|
129
|
+
redelivery is turned on for the channel. `createWebhookServer` answers 200 before it dispatches,
|
|
130
|
+
so it acknowledges such a request; route through `lineChannel.webhook` when that matters.
|
|
131
|
+
- `lineChannel.create` refuses a field of the wrong type with `ConfigurationError` coded
|
|
132
|
+
`invalid_config`, the key in `detail`; the adapter still refuses an empty secret or token.
|
|
133
|
+
|
|
66
134
|
## Reply token vs Push (D407)
|
|
67
135
|
|
|
68
136
|
LINE distinguishes two outbound APIs:
|
package/dist/index.cjs
CHANGED
|
@@ -59,10 +59,10 @@ function mapSourceType(sourceType) {
|
|
|
59
59
|
}
|
|
60
60
|
function lineEventToMessageEvent(event) {
|
|
61
61
|
if (event.type !== "message") return void 0;
|
|
62
|
-
if (event.message
|
|
62
|
+
if (event.message == null) return void 0;
|
|
63
63
|
if (event.message.type !== "text") return void 0;
|
|
64
64
|
const source = event.source;
|
|
65
|
-
if (source
|
|
65
|
+
if (source == null) return void 0;
|
|
66
66
|
const sourceId = source.userId ?? source.groupId ?? source.roomId;
|
|
67
67
|
const sourceType = source.type;
|
|
68
68
|
if (sourceId === void 0 || sourceId.length === 0) return void 0;
|
|
@@ -90,6 +90,15 @@ function lineEventToMessageEvent(event) {
|
|
|
90
90
|
};
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
// src/refuse-attachments.ts
|
|
94
|
+
function refuseAttachments(out) {
|
|
95
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
96
|
+
return {
|
|
97
|
+
ok: false,
|
|
98
|
+
error: { code: "attachments_unsupported", message: "line adapter cannot send attachments" }
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
93
102
|
// src/reply-cache.ts
|
|
94
103
|
var DEFAULT_TTL_MS = 6e4;
|
|
95
104
|
var DEFAULT_CAPACITY = 1e3;
|
|
@@ -124,7 +133,9 @@ var ReplyTokenCache = class {
|
|
|
124
133
|
}
|
|
125
134
|
};
|
|
126
135
|
function splitForLine(text, limit = 5e3) {
|
|
127
|
-
return gateway.chunkByGrapheme(text, { limit });
|
|
136
|
+
if (text.length <= limit) return gateway.chunkByGrapheme(text, { limit });
|
|
137
|
+
gateway.chunkByGrapheme("", { limit });
|
|
138
|
+
return gateway.splitKeepingRows(text, limit);
|
|
128
139
|
}
|
|
129
140
|
|
|
130
141
|
// src/adapter.ts
|
|
@@ -180,8 +191,11 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
180
191
|
this.inboundHandler = void 0;
|
|
181
192
|
this.replyCache.clear();
|
|
182
193
|
}
|
|
183
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.
|
|
184
194
|
async sendMessage(out) {
|
|
195
|
+
return refuseAttachments(out) ?? this.sendText(out);
|
|
196
|
+
}
|
|
197
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.
|
|
198
|
+
async sendText(out) {
|
|
185
199
|
if (out.text.length === 0) {
|
|
186
200
|
return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
|
|
187
201
|
}
|
|
@@ -256,24 +270,38 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
256
270
|
return this.client;
|
|
257
271
|
}
|
|
258
272
|
/**
|
|
259
|
-
* Webhook entrypoint — called
|
|
260
|
-
*
|
|
273
|
+
* Webhook entrypoint — called AFTER signature validation. Iterates LINE's batch envelope and
|
|
274
|
+
* dispatches each event.
|
|
275
|
+
*
|
|
276
|
+
* Answers `"no_handler"`, dispatching nothing and caching no reply token, when the batch holds an
|
|
277
|
+
* event the handler would receive (a text message that passes the mention guard) and no handler
|
|
278
|
+
* is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired
|
|
279
|
+
* because its connect failed. A webhook route must not acknowledge that answer, or LINE does not
|
|
280
|
+
* redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's
|
|
281
|
+
* console verification, or only follow and media events) answers `"ok"` either way. The handler is
|
|
282
|
+
* read once per batch, so one that unsubscribes while handling an event still gets the rest.
|
|
261
283
|
*/
|
|
262
284
|
async dispatchWebhookBody(envelope) {
|
|
263
|
-
|
|
264
|
-
|
|
285
|
+
const handler = this.inboundHandler;
|
|
286
|
+
const events = envelope.events.map((ev) => ({ ev, normalized: lineEventToMessageEvent(ev) }));
|
|
287
|
+
const deliverable = events.some(
|
|
288
|
+
({ normalized }) => normalized !== void 0 && this.passesMentionGuard(normalized)
|
|
289
|
+
);
|
|
290
|
+
if (handler === void 0 && deliverable) return "no_handler";
|
|
291
|
+
for (const { ev, normalized } of events) {
|
|
292
|
+
await this.dispatchSingleEvent(ev, normalized, handler);
|
|
265
293
|
}
|
|
294
|
+
return "ok";
|
|
266
295
|
}
|
|
267
|
-
async dispatchSingleEvent(ev) {
|
|
268
|
-
const normalized = lineEventToMessageEvent(ev);
|
|
296
|
+
async dispatchSingleEvent(ev, normalized, handler) {
|
|
269
297
|
if (normalized === void 0) return;
|
|
270
298
|
if (ev.replyToken !== void 0 && normalized.sender.id.length > 0) {
|
|
271
299
|
this.replyCache.put(normalized.sender.id, ev.replyToken);
|
|
272
300
|
}
|
|
273
301
|
if (!this.passesMentionGuard(normalized)) return;
|
|
274
|
-
if (
|
|
302
|
+
if (handler === void 0) return;
|
|
275
303
|
try {
|
|
276
|
-
await
|
|
304
|
+
await handler(normalized);
|
|
277
305
|
} catch (err) {
|
|
278
306
|
const msg = err instanceof Error ? err.message : String(err);
|
|
279
307
|
process.stderr.write(`[gateway-line] handler threw: ${msg}
|
|
@@ -303,6 +331,7 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
303
331
|
* named as the handler's failure rather than the platform's, and delivery continues.
|
|
304
332
|
*/
|
|
305
333
|
async deliver(event) {
|
|
334
|
+
if (!this.passesMentionGuard(event)) return "ok";
|
|
306
335
|
return this.runHandler(this.inboundHandler, event);
|
|
307
336
|
}
|
|
308
337
|
};
|
|
@@ -332,6 +361,13 @@ function mapLineError(err) {
|
|
|
332
361
|
}
|
|
333
362
|
};
|
|
334
363
|
}
|
|
364
|
+
|
|
365
|
+
// src/envelope.ts
|
|
366
|
+
function isEnvelope(payload) {
|
|
367
|
+
if (typeof payload !== "object" || payload === null) return false;
|
|
368
|
+
const events = payload.events;
|
|
369
|
+
return Array.isArray(events) && events.every((event) => typeof event === "object" && event !== null);
|
|
370
|
+
}
|
|
335
371
|
function computeLineSignature(channelSecret, rawBody) {
|
|
336
372
|
return crypto__default.default.createHmac("sha256", channelSecret).update(rawBody, "utf8").digest("base64");
|
|
337
373
|
}
|
|
@@ -347,6 +383,92 @@ function verifyLineSignature(channelSecret, rawBody, signatureHeader) {
|
|
|
347
383
|
return false;
|
|
348
384
|
}
|
|
349
385
|
}
|
|
386
|
+
|
|
387
|
+
// src/channel.ts
|
|
388
|
+
var SIGNATURE_HEADER = "x-line-signature";
|
|
389
|
+
function invalid(key, expected) {
|
|
390
|
+
return new ConfigurationError({
|
|
391
|
+
code: "invalid_config",
|
|
392
|
+
message: `gateway-line: config.${key} must be ${expected}`,
|
|
393
|
+
detail: key
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
function requiredString(config, key) {
|
|
397
|
+
const value = config[key];
|
|
398
|
+
if (typeof value !== "string") throw invalid(key, "a string");
|
|
399
|
+
return value;
|
|
400
|
+
}
|
|
401
|
+
function optional(config, key, check, expected) {
|
|
402
|
+
const value = config[key];
|
|
403
|
+
if (value === void 0 || value === null || value === "") return void 0;
|
|
404
|
+
if (!check(value)) throw invalid(key, expected);
|
|
405
|
+
return value;
|
|
406
|
+
}
|
|
407
|
+
var isString = (value) => typeof value === "string";
|
|
408
|
+
var isBoolean = (value) => typeof value === "boolean";
|
|
409
|
+
function buildOptions(config) {
|
|
410
|
+
const channelSecret = requiredString(config, "channelSecret");
|
|
411
|
+
const channelAccessToken = requiredString(config, "channelAccessToken");
|
|
412
|
+
const botUserId = optional(config, "botUserId", isString, "a string");
|
|
413
|
+
const requireMention = optional(config, "requireMention", isBoolean, "a boolean");
|
|
414
|
+
return {
|
|
415
|
+
channelSecret,
|
|
416
|
+
channelAccessToken,
|
|
417
|
+
...botUserId !== void 0 ? { botUserId } : {},
|
|
418
|
+
...requireMention !== void 0 ? { requireMention } : {}
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
function headerValue(headers, name) {
|
|
422
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
423
|
+
if (key.toLowerCase() === name) return value;
|
|
424
|
+
}
|
|
425
|
+
return void 0;
|
|
426
|
+
}
|
|
427
|
+
var CONFIG = [
|
|
428
|
+
{
|
|
429
|
+
key: "channelSecret",
|
|
430
|
+
required: true,
|
|
431
|
+
secret: true,
|
|
432
|
+
description: "The channel secret that signs inbound webhooks (LINE Developers Console)."
|
|
433
|
+
},
|
|
434
|
+
{
|
|
435
|
+
key: "channelAccessToken",
|
|
436
|
+
required: true,
|
|
437
|
+
secret: true,
|
|
438
|
+
description: "The channel's long-lived access token (LINE Developers Console)."
|
|
439
|
+
},
|
|
440
|
+
{
|
|
441
|
+
key: "botUserId",
|
|
442
|
+
required: false,
|
|
443
|
+
secret: false,
|
|
444
|
+
description: "The bot's own user id; with requireMention, group messages must mention it."
|
|
445
|
+
},
|
|
446
|
+
{
|
|
447
|
+
key: "requireMention",
|
|
448
|
+
required: false,
|
|
449
|
+
secret: false,
|
|
450
|
+
description: "Whether group messages must mention the bot. Default true."
|
|
451
|
+
}
|
|
452
|
+
];
|
|
453
|
+
var lineChannel = {
|
|
454
|
+
platform: "line",
|
|
455
|
+
transport: "webhook",
|
|
456
|
+
config: CONFIG,
|
|
457
|
+
create(config) {
|
|
458
|
+
return new LineAdapter(buildOptions(config));
|
|
459
|
+
},
|
|
460
|
+
webhook: {
|
|
461
|
+
verify(adapter, request) {
|
|
462
|
+
const signature = headerValue(request.headers, SIGNATURE_HEADER);
|
|
463
|
+
return verifyLineSignature(adapter.getChannelSecret(), request.rawBody, signature);
|
|
464
|
+
},
|
|
465
|
+
async ingest(adapter, payload) {
|
|
466
|
+
if (!isEnvelope(payload)) return "malformed";
|
|
467
|
+
const outcome = await adapter.dispatchWebhookBody(payload);
|
|
468
|
+
return outcome === "no_handler" ? "no_handler" : "delivered";
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
};
|
|
350
472
|
async function loadExpress() {
|
|
351
473
|
return gateway.loadPeer(
|
|
352
474
|
async () => import('express'),
|
|
@@ -373,8 +495,8 @@ function handlerFactory(adapter) {
|
|
|
373
495
|
res.status(400).type("text/plain").send("invalid JSON body");
|
|
374
496
|
return;
|
|
375
497
|
}
|
|
376
|
-
if (!
|
|
377
|
-
res.status(400).type("text/plain").send("missing 'events' array");
|
|
498
|
+
if (!isEnvelope(envelope)) {
|
|
499
|
+
res.status(400).type("text/plain").send("missing 'events' array of objects");
|
|
378
500
|
return;
|
|
379
501
|
}
|
|
380
502
|
void adapter.dispatchWebhookBody(envelope).catch((err) => {
|
|
@@ -398,13 +520,26 @@ async function createWebhookServer(opts) {
|
|
|
398
520
|
return gateway.listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
|
|
399
521
|
}
|
|
400
522
|
|
|
523
|
+
// src/webhook-verifier.ts
|
|
524
|
+
function lineWebhookVerifier(source) {
|
|
525
|
+
return async (request) => {
|
|
526
|
+
const rawBody = await request.text();
|
|
527
|
+
const signature = request.headers.get("x-line-signature") ?? void 0;
|
|
528
|
+
if (signature === void 0) return { ok: false, reason: "missing x-line-signature header" };
|
|
529
|
+
const secret = typeof source === "string" ? source : source.getChannelSecret();
|
|
530
|
+
return verifyLineSignature(secret, rawBody, signature) ? { ok: true } : { ok: false, reason: "signature mismatch" };
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
|
|
401
534
|
exports.ConfigurationError = ConfigurationError;
|
|
402
535
|
exports.LineAdapter = LineAdapter;
|
|
403
536
|
exports.ReplyTokenCache = ReplyTokenCache;
|
|
404
537
|
exports.SDKNotInstalledError = SDKNotInstalledError;
|
|
405
538
|
exports.computeLineSignature = computeLineSignature;
|
|
406
539
|
exports.createWebhookServer = createWebhookServer;
|
|
540
|
+
exports.lineChannel = lineChannel;
|
|
407
541
|
exports.lineEventToMessageEvent = lineEventToMessageEvent;
|
|
542
|
+
exports.lineWebhookVerifier = lineWebhookVerifier;
|
|
408
543
|
exports.mapSourceType = mapSourceType;
|
|
409
544
|
exports.splitForLine = splitForLine;
|
|
410
545
|
exports.verifyLineSignature = verifyLineSignature;
|