@theokit/gateway-line 0.1.4 → 0.1.6
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 +38 -0
- package/dist/index.cjs +27 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -2
- package/dist/index.d.ts +16 -2
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -1
- package/package.json +12 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,43 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.6
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 5e346e1: The webhook server can be started again after being stopped.
|
|
8
|
+
|
|
9
|
+
`started` and `stopped` were write-once. After a `stop()`, `start()` hit `if (started)` and returned
|
|
10
|
+
without creating a listener — so the server was silently dead: no error, no log, just a port nothing
|
|
11
|
+
answers on. The next `stop()` was a no-op for the same reason, in the other direction.
|
|
12
|
+
|
|
13
|
+
Anything that restarts a gateway — a config reload, a reconnect after a network fault, a supervisor
|
|
14
|
+
cycling the process in-band — got a server that reported success and served nothing.
|
|
15
|
+
|
|
16
|
+
Fixed in commit 11000cc on 2026-08-29; this changeset was missing, so the fix would have stayed
|
|
17
|
+
unreleased and npm would have gone on serving the broken code.
|
|
18
|
+
|
|
19
|
+
## 0.1.5
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- Every credential field now says what the platform calls it and where it is issued.
|
|
24
|
+
|
|
25
|
+
Measured: a developer who wires one adapter and carries its field name to the next gets
|
|
26
|
+
`error TS2353: … 'token' does not exist in type 'SlackAdapterOptions'`. That names the wrong field
|
|
27
|
+
and the type, and never the right one — so the answer was always one file away.
|
|
28
|
+
|
|
29
|
+
These docblocks are on published option types, so an editor now shows the answer on hover and
|
|
30
|
+
completion. All 15 credential-bearing fields across the ten packages are covered, including the ones
|
|
31
|
+
beyond each adapter's primary token: Slack's `appToken`, LINE's `channelSecret`, Vonage's
|
|
32
|
+
`apiSecret` and `signatureSecret`, WhatsApp's `appSecret`.
|
|
33
|
+
|
|
34
|
+
**Nothing was renamed.** Six of the ten primary names are the platform's own key, pinned against the
|
|
35
|
+
SDK's own declaration — `channelAccessToken` in `@line/bot-sdk`, `clientSecret` in
|
|
36
|
+
`@microsoft/teams.apps`, `accessToken` in `matrix-js-sdk`, `token` in `grammy` and `discord.js`,
|
|
37
|
+
`authToken` in `twilio`. Where ours diverges, the docblock says so rather than implying otherwise:
|
|
38
|
+
`botToken` (deliberate — the adapter also takes an `appToken`), Mattermost's `accessToken` against
|
|
39
|
+
its client's `token`, and `password` against nodemailer's `pass`.
|
|
40
|
+
|
|
3
41
|
## 0.1.4
|
|
4
42
|
|
|
5
43
|
### Patch Changes
|
package/dist/index.cjs
CHANGED
|
@@ -192,6 +192,7 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
192
192
|
};
|
|
193
193
|
}
|
|
194
194
|
const targetId = out.channel.id;
|
|
195
|
+
this.warnFormatUnsupported(out.format);
|
|
195
196
|
const parts = splitForLine(out.text);
|
|
196
197
|
const token = this.replyCache.take(targetId);
|
|
197
198
|
let lastErr;
|
|
@@ -220,6 +221,30 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
220
221
|
if (lastErr !== void 0) return lastErr;
|
|
221
222
|
return { ok: true, ...messageId !== void 0 ? { messageId } : {} };
|
|
222
223
|
}
|
|
224
|
+
/** Whether the "this platform has no text formatting" warning has already been emitted. */
|
|
225
|
+
warnedAboutFormat = false;
|
|
226
|
+
/**
|
|
227
|
+
* Say, once, that a declared `format` has nowhere to go on this platform.
|
|
228
|
+
*
|
|
229
|
+
* A LINE text message carries `{ type: "text", text }` and nothing else — no markup field,
|
|
230
|
+
* no parse flag, no alternative part. Flex Messages can render styled content, but they are a
|
|
231
|
+
* different message type with a different payload, not a flag on this one.
|
|
232
|
+
*
|
|
233
|
+
* This is the platform whose silence was OBSERVED: an agent answered
|
|
234
|
+
* `**Bom Sucesso (MG)**` and the person read literal asterisks, because the adapter dropped
|
|
235
|
+
* the caller's declared intent without saying so.
|
|
236
|
+
*
|
|
237
|
+
* @internal
|
|
238
|
+
*/
|
|
239
|
+
warnFormatUnsupported(format) {
|
|
240
|
+
if (format === void 0 || format === "plain") return;
|
|
241
|
+
if (this.warnedAboutFormat) return;
|
|
242
|
+
this.warnedAboutFormat = true;
|
|
243
|
+
process.stderr.write(
|
|
244
|
+
`[gateway-line] format="${format}" was declared, and a LINE text message cannot carry it \u2014 there is no markup field on this message type. Sending as-is; this is logged once.
|
|
245
|
+
`
|
|
246
|
+
);
|
|
247
|
+
}
|
|
223
248
|
onInbound(handler) {
|
|
224
249
|
this.inboundHandler = handler;
|
|
225
250
|
return () => {
|
|
@@ -393,6 +418,7 @@ async function createWebhookServer(opts) {
|
|
|
393
418
|
started = true;
|
|
394
419
|
return;
|
|
395
420
|
}
|
|
421
|
+
stopped = false;
|
|
396
422
|
const port = opts.port ?? 3e3;
|
|
397
423
|
await new Promise((resolve) => {
|
|
398
424
|
server = app.listen(port, () => resolve());
|
|
@@ -402,6 +428,7 @@ async function createWebhookServer(opts) {
|
|
|
402
428
|
async stop() {
|
|
403
429
|
if (stopped) return;
|
|
404
430
|
stopped = true;
|
|
431
|
+
started = false;
|
|
405
432
|
if (server === void 0) return;
|
|
406
433
|
await new Promise((resolve) => {
|
|
407
434
|
server?.close(() => resolve());
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":["GatewayConfigurationError","chunkByGrapheme","BasePlatformAdapter","crypto"],"mappings":";;;;;;;;;;AAsBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AA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OAAO,CAAC,CAAA;AAEvD,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,IAAI,OAAA,GAAU,KAAA;AAEd,EAAA,OAAO;AAAA,IACL,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,OAAA,IAAW,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW;AACrC,QAAA,OAAA,GAAU,IAAA;AACV,QAAA;AAAA,MACF;AACA,MAAA,MAAM,IAAA,GAAO,KAAK,IAAA,IAAQ,GAAA;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,MAAM,SAAS,CAAA;AAAA,MAC3C,CAAC,CAAA;AACD,MAAA,OAAA,GAAU,IAAA;AAAA,IACZ,CAAA;AAAA,IACA,MAAM,IAAA,GAAsB;AAC1B,MAAA,IAAI,OAAA,EAAS;AACb,MAAA,OAAA,GAAU,IAAA;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. Thin wrapper over core\n * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme\n * walk so emoji, regional indicators, and combining sequences are never severed.\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n return chunkByGrapheme(text, { limit });\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const factory = this.opts.__clientFactory;\n if (factory === undefined) {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n } else {\n this.client = factory() as LineSdkClient;\n }\n // Validate the credential before reporting success. Building the client\n // performs NO network I/O, so without this connect() answered true for any\n // string and the failure surfaced only at the first send — as a 401 that\n // looks like a send bug rather than a bad token.\n await this.client.getBotInfo();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // 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.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify LINE's `x-line-signature` header against the raw request body.\n *\n * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile\n * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any\n * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.\n */\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response at\n // all: the provider times out and retries, and no error is logged anywhere.\n // Failing loudly and continuing is strictly better — verification then\n // refuses the empty body with a 401, which is at least a visible symptom that\n // points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n // Answered before dispatch, on purpose: LINE retries a webhook it did not see a 200 for,\n // and waiting on the handler turns a slow one into a duplicate delivery. What that costs is\n // that the dispatch is floated — and a floated rejection is an unhandled one, which ends the\n // process (the defect fixed across the other adapters in #41). The catch is what makes the\n // early answer safe rather than merely fast.\n void adapter.dispatchWebhookBody(envelope).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}\\n`);\n });\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\n/**\n * Build the HTTP listener that receives LINE's webhook deliveries.\n *\n * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE\n * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`\n * is loaded lazily, so a project that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":["GatewayConfigurationError","chunkByGrapheme","BasePlatformAdapter","crypto"],"mappings":";;;;;;;;;;AAsBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oB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Ac,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. Thin wrapper over core\n * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme\n * walk so emoji, regional indicators, and combining sequences are never severed.\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n return chunkByGrapheme(text, { limit });\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const factory = this.opts.__clientFactory;\n if (factory === undefined) {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n } else {\n this.client = factory() as LineSdkClient;\n }\n // Validate the credential before reporting success. Building the client\n // performs NO network I/O, so without this connect() answered true for any\n // string and the failure surfaced only at the first send — as a 401 that\n // looks like a send bug rather than a bad token.\n await this.client.getBotInfo();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // 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.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n // A LINE text message has no markup field. Reading the field is what makes the\n // discard visible — this is the platform where the silence was observed.\n this.warnFormatUnsupported(out.format);\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n /** Whether the \"this platform has no text formatting\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `format` has nowhere to go on this platform.\n *\n * A LINE text message carries `{ type: \"text\", text }` and nothing else — no markup field,\n * no parse flag, no alternative part. Flex Messages can render styled content, but they are a\n * different message type with a different payload, not a flag on this one.\n *\n * This is the platform whose silence was OBSERVED: an agent answered\n * `**Bom Sucesso (MG)**` and the person read literal asterisks, because the adapter dropped\n * the caller's declared intent without saying so.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-line] format=\"${format}\" was declared, and a LINE text message cannot carry it — ` +\n \"there is no markup field on this message type. Sending as-is; this is logged once.\\n\",\n );\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify LINE's `x-line-signature` header against the raw request body.\n *\n * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile\n * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any\n * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.\n */\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response at\n // all: the provider times out and retries, and no error is logged anywhere.\n // Failing loudly and continuing is strictly better — verification then\n // refuses the empty body with a 401, which is at least a visible symptom that\n // points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n // Answered before dispatch, on purpose: LINE retries a webhook it did not see a 200 for,\n // and waiting on the handler turns a slow one into a duplicate delivery. What that costs is\n // that the dispatch is floated — and a floated rejection is an unhandled one, which ends the\n // process (the defect fixed across the other adapters in #41). The catch is what makes the\n // early answer safe rather than merely fast.\n void adapter.dispatchWebhookBody(envelope).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}\\n`);\n });\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\n/**\n * Build the HTTP listener that receives LINE's webhook deliveries.\n *\n * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE\n * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`\n * is loaded lazily, so a project that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n // Cleared here, not in stop(): a server that was stopped and is starting again is no longer\n // stopped, and leaving the flag latched made the NEXT stop() a no-op that left the listener up.\n stopped = false;\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n // The pair of latches used to be write-once, so `start()` after a `stop()` returned without\n // creating a listener and the server was silently dead — no error, no log, just a port nothing\n // answers on. Resetting `started` is what makes a restart a restart.\n started = false;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -38,9 +38,21 @@ interface LineSdkClient {
|
|
|
38
38
|
* @public
|
|
39
39
|
*/
|
|
40
40
|
interface LineAdapterOptions {
|
|
41
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
* The LINE channel secret, used to verify the `x-line-signature` header on inbound webhooks.
|
|
43
|
+
*
|
|
44
|
+
* @platform-term LINE calls this a **channel secret** — its own word, and distinct from the
|
|
45
|
+
* channel access token above: this one signs, that one authenticates.
|
|
46
|
+
* @issued-at The LINE Developers Console, on the channel's Basic settings tab.
|
|
47
|
+
*/
|
|
42
48
|
readonly channelSecret: string;
|
|
43
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* The LINE channel's long-lived access token.
|
|
51
|
+
*
|
|
52
|
+
* @platform-term LINE calls this a **channel access token** — the same word `@line/bot-sdk` uses
|
|
53
|
+
* for this field, so the name here is theirs and not ours.
|
|
54
|
+
* @issued-at The LINE Developers Console, under the channel's Messaging API tab.
|
|
55
|
+
*/
|
|
44
56
|
readonly channelAccessToken: string;
|
|
45
57
|
/**
|
|
46
58
|
* Bot's own LINE user id (`Uxxx...`). When set + `requireMention: true`,
|
|
@@ -117,6 +129,8 @@ declare class LineAdapter extends BasePlatformAdapter {
|
|
|
117
129
|
connect(): Promise<boolean>;
|
|
118
130
|
disconnect(): Promise<void>;
|
|
119
131
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
132
|
+
/** Whether the "this platform has no text formatting" warning has already been emitted. */
|
|
133
|
+
private warnedAboutFormat;
|
|
120
134
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
121
135
|
/** Escape hatch: caller drives Flex/Carousel/etc directly. */
|
|
122
136
|
getClient(): LineSdkClient | undefined;
|
package/dist/index.d.ts
CHANGED
|
@@ -38,9 +38,21 @@ interface LineSdkClient {
|
|
|
38
38
|
* @public
|
|
39
39
|
*/
|
|
40
40
|
interface LineAdapterOptions {
|
|
41
|
-
/**
|
|
41
|
+
/**
|
|
42
|
+
* The LINE channel secret, used to verify the `x-line-signature` header on inbound webhooks.
|
|
43
|
+
*
|
|
44
|
+
* @platform-term LINE calls this a **channel secret** — its own word, and distinct from the
|
|
45
|
+
* channel access token above: this one signs, that one authenticates.
|
|
46
|
+
* @issued-at The LINE Developers Console, on the channel's Basic settings tab.
|
|
47
|
+
*/
|
|
42
48
|
readonly channelSecret: string;
|
|
43
|
-
/**
|
|
49
|
+
/**
|
|
50
|
+
* The LINE channel's long-lived access token.
|
|
51
|
+
*
|
|
52
|
+
* @platform-term LINE calls this a **channel access token** — the same word `@line/bot-sdk` uses
|
|
53
|
+
* for this field, so the name here is theirs and not ours.
|
|
54
|
+
* @issued-at The LINE Developers Console, under the channel's Messaging API tab.
|
|
55
|
+
*/
|
|
44
56
|
readonly channelAccessToken: string;
|
|
45
57
|
/**
|
|
46
58
|
* Bot's own LINE user id (`Uxxx...`). When set + `requireMention: true`,
|
|
@@ -117,6 +129,8 @@ declare class LineAdapter extends BasePlatformAdapter {
|
|
|
117
129
|
connect(): Promise<boolean>;
|
|
118
130
|
disconnect(): Promise<void>;
|
|
119
131
|
sendMessage(out: OutboundMessage): Promise<SendResult>;
|
|
132
|
+
/** Whether the "this platform has no text formatting" warning has already been emitted. */
|
|
133
|
+
private warnedAboutFormat;
|
|
120
134
|
onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
|
|
121
135
|
/** Escape hatch: caller drives Flex/Carousel/etc directly. */
|
|
122
136
|
getClient(): LineSdkClient | undefined;
|
package/dist/index.js
CHANGED
|
@@ -186,6 +186,7 @@ var LineAdapter = class extends BasePlatformAdapter {
|
|
|
186
186
|
};
|
|
187
187
|
}
|
|
188
188
|
const targetId = out.channel.id;
|
|
189
|
+
this.warnFormatUnsupported(out.format);
|
|
189
190
|
const parts = splitForLine(out.text);
|
|
190
191
|
const token = this.replyCache.take(targetId);
|
|
191
192
|
let lastErr;
|
|
@@ -214,6 +215,30 @@ var LineAdapter = class extends BasePlatformAdapter {
|
|
|
214
215
|
if (lastErr !== void 0) return lastErr;
|
|
215
216
|
return { ok: true, ...messageId !== void 0 ? { messageId } : {} };
|
|
216
217
|
}
|
|
218
|
+
/** Whether the "this platform has no text formatting" warning has already been emitted. */
|
|
219
|
+
warnedAboutFormat = false;
|
|
220
|
+
/**
|
|
221
|
+
* Say, once, that a declared `format` has nowhere to go on this platform.
|
|
222
|
+
*
|
|
223
|
+
* A LINE text message carries `{ type: "text", text }` and nothing else — no markup field,
|
|
224
|
+
* no parse flag, no alternative part. Flex Messages can render styled content, but they are a
|
|
225
|
+
* different message type with a different payload, not a flag on this one.
|
|
226
|
+
*
|
|
227
|
+
* This is the platform whose silence was OBSERVED: an agent answered
|
|
228
|
+
* `**Bom Sucesso (MG)**` and the person read literal asterisks, because the adapter dropped
|
|
229
|
+
* the caller's declared intent without saying so.
|
|
230
|
+
*
|
|
231
|
+
* @internal
|
|
232
|
+
*/
|
|
233
|
+
warnFormatUnsupported(format) {
|
|
234
|
+
if (format === void 0 || format === "plain") return;
|
|
235
|
+
if (this.warnedAboutFormat) return;
|
|
236
|
+
this.warnedAboutFormat = true;
|
|
237
|
+
process.stderr.write(
|
|
238
|
+
`[gateway-line] format="${format}" was declared, and a LINE text message cannot carry it \u2014 there is no markup field on this message type. Sending as-is; this is logged once.
|
|
239
|
+
`
|
|
240
|
+
);
|
|
241
|
+
}
|
|
217
242
|
onInbound(handler) {
|
|
218
243
|
this.inboundHandler = handler;
|
|
219
244
|
return () => {
|
|
@@ -387,6 +412,7 @@ async function createWebhookServer(opts) {
|
|
|
387
412
|
started = true;
|
|
388
413
|
return;
|
|
389
414
|
}
|
|
415
|
+
stopped = false;
|
|
390
416
|
const port = opts.port ?? 3e3;
|
|
391
417
|
await new Promise((resolve) => {
|
|
392
418
|
server = app.listen(port, () => resolve());
|
|
@@ -396,6 +422,7 @@ async function createWebhookServer(opts) {
|
|
|
396
422
|
async stop() {
|
|
397
423
|
if (stopped) return;
|
|
398
424
|
stopped = true;
|
|
425
|
+
started = false;
|
|
399
426
|
if (server === void 0) return;
|
|
400
427
|
await new Promise((resolve) => {
|
|
401
428
|
server?.close(() => resolve());
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":[],"mappings":";;;;AAsBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACKA,eAAsB,WAAA,GAAsC;AAC1D,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,eAAe,CAAA;AACxC,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,eAAe,CAAA;AAAA,EAChD;AACF;AAeO,SAAS,UAAA,CACd,KACA,GAAA,EACe;AACf,EAAA,MAAM,EAAA,GAAK,IAAI,YAAA,EAAc,kBAAA;AAC7B,EAAA,IAAI,OAAO,MAAA,EAAW;AACpB,IAAA,MAAM,SAAS,IAAI,EAAA,CAAG,EAAE,kBAAA,EAAoB,GAAA,CAAI,oBAAoB,CAAA;AACpE,IAAA,OAAO;AAAA,MACL,MAAM,YAAA,CAAa,UAAA,EAAY,QAAA,EAAU;AACvC,QAAA,OAAO,MAAA,CAAO,YAAA,CAAa,EAAE,UAAA,EAAY,UAAU,CAAA;AAAA,MACrD,CAAA;AAAA,MACA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,UAAA,GAAa,MAAM,WAAA,EAAY;AACrC,EAAA,MAAM,GAAA,GAAe,IAAA,CAAK,GAAA,IAAO,UAAA,CAAW,OAAA,EAAQ;AACpD,EAAA,MAAM,IAAA,GAAO,KAAK,IAAA,IAAQ,OAAA;AAC1B,EAAA,GAAA,CAAI,KAAK,IAAA,EAAM,UAAA,EAAY,cAAA,CAAe,IAAA,CAAK,OAAO,CAAC,CAAA;AAEvD,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,IAAI,OAAA,GAAU,KAAA;AAEd,EAAA,OAAO;AAAA,IACL,MAAM,KAAA,GAAuB;AAC3B,MAAA,IAAI,OAAA,IAAW,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW;AACrC,QAAA,OAAA,GAAU,IAAA;AACV,QAAA;AAAA,MACF;AACA,MAAA,MAAM,IAAA,GAAO,KAAK,IAAA,IAAQ,GAAA;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,MAAM,SAAS,CAAA;AAAA,MAC3C,CAAC,CAAA;AACD,MAAA,OAAA,GAAU,IAAA;AAAA,IACZ,CAAA;AAAA,IACA,MAAM,IAAA,GAAsB;AAC1B,MAAA,IAAI,OAAA,EAAS;AACb,MAAA,OAAA,GAAU,IAAA;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. Thin wrapper over core\n * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme\n * walk so emoji, regional indicators, and combining sequences are never severed.\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n return chunkByGrapheme(text, { limit });\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const factory = this.opts.__clientFactory;\n if (factory === undefined) {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n } else {\n this.client = factory() as LineSdkClient;\n }\n // Validate the credential before reporting success. Building the client\n // performs NO network I/O, so without this connect() answered true for any\n // string and the failure surfaced only at the first send — as a 401 that\n // looks like a send bug rather than a bad token.\n await this.client.getBotInfo();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // 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.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify LINE's `x-line-signature` header against the raw request body.\n *\n * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile\n * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any\n * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.\n */\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response at\n // all: the provider times out and retries, and no error is logged anywhere.\n // Failing loudly and continuing is strictly better — verification then\n // refuses the empty body with a 401, which is at least a visible symptom that\n // points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n // Answered before dispatch, on purpose: LINE retries a webhook it did not see a 200 for,\n // and waiting on the handler turns a slow one into a duplicate delivery. What that costs is\n // that the dispatch is floated — and a floated rejection is an unhandled one, which ends the\n // process (the defect fixed across the other adapters in #41). The catch is what makes the\n // early answer safe rather than merely fast.\n void adapter.dispatchWebhookBody(envelope).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}\\n`);\n });\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\n/**\n * Build the HTTP listener that receives LINE's webhook deliveries.\n *\n * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE\n * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`\n * is loaded lazily, so a project that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/signature.ts","../src/webhook-server.ts"],"names":[],"mappings":";;;;AAsBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACKA,eAAsB,WAAA,GAAsC;AAC1D,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO,eAAe,CAAA;AACxC,IAAA,OAAO,GAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,qBAAqB,eAAe,CAAA;AAAA,EAChD;AACF;AAeO,SAAS,UAAA,CACd,KACA,GAAA,EACe;AACf,EAAA,MAAM,EAAA,GAAK,IAAI,YAAA,EAAc,kBAAA;AAC7B,EAAA,IAAI,OAAO,MAAA,EAAW;AACpB,IAAA,MAAM,SAAS,IAAI,EAAA,CAAG,EAAE,kBAAA,EAAoB,GAAA,CAAI,oBAAoB,CAAA;AACpE,IAAA,OAAO;AAAA,MACL,MAAM,YAAA,CAAa,UAAA,EAAY,QAAA,EAAU;AACvC,QAAA,OAAO,MAAA,CAAO,YAAA,CAAa,EAAE,UAAA,EAAY,UAAU,CAAA;AAAA,MACrD,CAAA;AAAA,MACA,MAAM,WAAA,CAAY,EAAA,EAAI,QAAA,EAAU;AAC9B,QAAA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IACA,MAAM,IAAA,GAAsB;AAC1B,MAAA,IAAI,OAAA,EAAS;AACb,MAAA,OAAA,GAAU,IAAA;AAIV,MAAA,OAAA,GAAU,KAAA;AACV,MAAA,IAAI,WAAW,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,OAAA,CAAc,CAAC,OAAA,KAAY;AACnC,QAAA,MAAA,EAAQ,KAAA,CAAM,MAAM,OAAA,EAAS,CAAA;AAAA,MAC/B,CAAC,CAAA;AACD,MAAA,MAAA,GAAS,MAAA;AAAA,IACX;AAAA,GACF;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message === undefined) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source === undefined) return undefined;\n\n const sourceId = source.userId ?? source.groupId ?? source.roomId;\n const sourceType = source.type as \"user\" | \"group\" | \"room\";\n if (sourceId === undefined || sourceId.length === 0) return undefined;\n\n const channelId = source.groupId ?? source.roomId ?? source.userId ?? sourceId;\n const channelType = mapSourceType(sourceType);\n\n const mentionees: string[] = [];\n for (const m of event.message.mentionees ?? []) {\n if (m.userId !== undefined && m.userId.length > 0) mentionees.push(m.userId);\n }\n\n return {\n id: event.message.id ?? `line-${event.timestamp ?? Date.now()}`,\n platform: \"line\",\n sender: source.userId !== undefined ? { id: source.userId } : { id: sourceId },\n channel: { id: channelId, type: channelType },\n text: event.message.text ?? \"\",\n receivedAt: event.timestamp ?? Date.now(),\n line: {\n sourceType,\n sourceId,\n messageId: event.message.id ?? \"\",\n mentionees,\n ...(event.replyToken !== undefined ? { replyToken: event.replyToken } : {}),\n raw: event,\n },\n };\n}\n","/**\n * Reply-token LRU cache (D407).\n *\n * `put(userId, token)` — store with 60s TTL.\n * `take(userId)` — atomic one-shot consume; second call returns undefined.\n * `evictExpired()` — periodic GC; called internally before each take.\n *\n * Capacity 1000; oldest dropped when full.\n */\n\nconst DEFAULT_TTL_MS = 60_000;\nconst DEFAULT_CAPACITY = 1000;\n\ninterface Entry {\n token: string;\n expiresAt: number;\n}\n\nexport class ReplyTokenCache {\n private readonly cache = new Map<string, Entry>();\n private readonly ttlMs: number;\n private readonly capacity: number;\n\n constructor(opts?: { ttlMs?: number; capacity?: number }) {\n this.ttlMs = opts?.ttlMs ?? DEFAULT_TTL_MS;\n this.capacity = opts?.capacity ?? DEFAULT_CAPACITY;\n }\n\n put(userId: string, token: string): void {\n if (this.cache.size >= this.capacity) this.evictOldest();\n this.cache.set(userId, { token, expiresAt: Date.now() + this.ttlMs });\n }\n\n take(userId: string): string | undefined {\n const entry = this.cache.get(userId);\n if (entry === undefined) return undefined;\n this.cache.delete(userId);\n if (Date.now() >= entry.expiresAt) return undefined;\n return entry.token;\n }\n\n size(): number {\n return this.cache.size;\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n private evictOldest(): void {\n const firstKey = this.cache.keys().next().value;\n if (firstKey !== undefined) this.cache.delete(firstKey);\n }\n}\n","/**\n * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).\n *\n * LINE limits text messages to 5000 chars. Thin wrapper over core\n * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme\n * walk so emoji, regional indicators, and combining sequences are never severed.\n * Output is byte-identical to the previous implementation (pinned by\n * `tests/split.test.ts`).\n */\n\nimport { chunkByGrapheme } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n return chunkByGrapheme(text, { limit });\n}\n","/**\n * `LineAdapter` — implements BasePlatformAdapter over LINE Messaging API.\n * ADRs D405-D412.\n *\n * @public\n */\n\nimport {\n BasePlatformAdapter,\n type MessageEvent as GatewayMessageEvent,\n type OutboundMessage,\n type SendResult,\n} from \"@theokit/gateway\";\n\nimport { type LineSdkClient, loadLineSdk, makeClient } from \"./client.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { lineEventToMessageEvent } from \"./normalize.js\";\nimport { ReplyTokenCache } from \"./reply-cache.js\";\nimport { splitForLine } from \"./split.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope, LineWebhookEvent } from \"./types.js\";\n\nexport class LineAdapter extends BasePlatformAdapter {\n readonly platform = \"line\" as const;\n private readonly opts: LineAdapterOptions;\n private readonly replyCache = new ReplyTokenCache();\n private client: LineSdkClient | undefined;\n private inboundHandler: ((event: GatewayMessageEvent) => Promise<void>) | undefined;\n private connected = false;\n\n constructor(opts: LineAdapterOptions) {\n super();\n if (opts.channelSecret.length === 0) {\n throw new ConfigurationError({\n code: \"channel_secret_required\",\n message:\n \"gateway-line: opts.channelSecret is empty (D408 requires signing — no insecure mode)\",\n });\n }\n if (opts.channelAccessToken.length === 0) {\n throw new ConfigurationError({\n code: \"access_token_required\",\n message: \"gateway-line: opts.channelAccessToken is empty\",\n });\n }\n this.opts = opts;\n }\n\n async connect(): Promise<boolean> {\n if (this.connected) return true;\n try {\n const factory = this.opts.__clientFactory;\n if (factory === undefined) {\n const mod = await loadLineSdk();\n this.client = makeClient(mod, {\n channelAccessToken: this.opts.channelAccessToken,\n channelSecret: this.opts.channelSecret,\n });\n } else {\n this.client = factory() as LineSdkClient;\n }\n // Validate the credential before reporting success. Building the client\n // performs NO network I/O, so without this connect() answered true for any\n // string and the failure surfaced only at the first send — as a 401 that\n // looks like a send bug rather than a bad token.\n await this.client.getBotInfo();\n this.connected = true;\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] connect failed: ${msg}\\n`);\n return false;\n }\n }\n\n async disconnect(): Promise<void> {\n this.connected = false;\n this.client = undefined;\n this.inboundHandler = undefined;\n this.replyCache.clear();\n }\n\n // 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.\n async sendMessage(out: OutboundMessage): Promise<SendResult> {\n if (out.text.length === 0) {\n return { ok: false, error: { code: \"empty_text\", message: \"outbound text is empty\" } };\n }\n if (this.client === undefined) {\n return {\n ok: false,\n error: { code: \"not_connected\", message: \"LineAdapter.connect() not called\" },\n };\n }\n // For DMs: channel.id IS the userId. For groups/rooms: channel.id is groupId/roomId — push API still uses the channel id.\n const targetId = out.channel.id;\n // A LINE text message has no markup field. Reading the field is what makes the\n // discard visible — this is the platform where the silence was observed.\n this.warnFormatUnsupported(out.format);\n const parts = splitForLine(out.text);\n // Reply API: only the FIRST batch can use the one-shot replyToken; subsequent calls fall back to push.\n const token = this.replyCache.take(targetId);\n let lastErr: SendResult | undefined;\n let messageId: string | undefined;\n for (let i = 0; i < parts.length; i++) {\n const messages = [{ type: \"text\" as const, text: parts[i] ?? \"\" }];\n const isFirst = i === 0;\n try {\n if (isFirst && token !== undefined) {\n await this.client.replyMessage(token, messages);\n } else {\n if (isFirst && token === undefined) {\n process.stderr.write(\n `[gateway-line] no reply token for ${targetId} — using push API\\n`,\n );\n }\n await this.client.pushMessage(targetId, messages);\n }\n messageId = `line-${Date.now()}-${i}`;\n } catch (err) {\n lastErr = mapLineError(err);\n break;\n }\n }\n if (lastErr !== undefined) return lastErr;\n return { ok: true, ...(messageId !== undefined ? { messageId } : {}) };\n }\n\n /** Whether the \"this platform has no text formatting\" warning has already been emitted. */\n private warnedAboutFormat = false;\n\n /**\n * Say, once, that a declared `format` has nowhere to go on this platform.\n *\n * A LINE text message carries `{ type: \"text\", text }` and nothing else — no markup field,\n * no parse flag, no alternative part. Flex Messages can render styled content, but they are a\n * different message type with a different payload, not a flag on this one.\n *\n * This is the platform whose silence was OBSERVED: an agent answered\n * `**Bom Sucesso (MG)**` and the person read literal asterisks, because the adapter dropped\n * the caller's declared intent without saying so.\n *\n * @internal\n */\n private warnFormatUnsupported(format: string | undefined): void {\n // The \"is there anything to say\" question lives here rather than at the call site: a\n // `sendMessage` already at its complexity limit should ask one thing, not three.\n if (format === undefined || format === \"plain\") return;\n if (this.warnedAboutFormat) return;\n this.warnedAboutFormat = true;\n process.stderr.write(\n `[gateway-line] format=\"${format}\" was declared, and a LINE text message cannot carry it — ` +\n \"there is no markup field on this message type. Sending as-is; this is logged once.\\n\",\n );\n }\n\n onInbound(handler: (event: GatewayMessageEvent) => Promise<void>): () => void {\n // EC-H: replace, not stack.\n this.inboundHandler = handler;\n return () => {\n if (this.inboundHandler === handler) this.inboundHandler = undefined;\n };\n }\n\n /** Escape hatch: caller drives Flex/Carousel/etc directly. */\n getClient(): LineSdkClient | undefined {\n return this.client;\n }\n\n /**\n * Webhook entrypoint — called by `createWebhookServer` AFTER signature\n * validation. Iterates LINE's batch envelope and dispatches each event.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<void> {\n for (const ev of envelope.events) {\n await this.dispatchSingleEvent(ev);\n }\n }\n\n private async dispatchSingleEvent(ev: LineWebhookEvent): Promise<void> {\n const normalized = lineEventToMessageEvent(ev);\n if (normalized === undefined) return; // EC-4: silently skip non-message / non-text\n // Cache the reply token (one-shot, 60s TTL) keyed by SENDER userId (replies go to whoever spoke).\n if (ev.replyToken !== undefined && normalized.sender.id.length > 0) {\n this.replyCache.put(normalized.sender.id, ev.replyToken);\n }\n // Mention guard (D409).\n if (!this.passesMentionGuard(normalized)) return;\n if (this.inboundHandler === undefined) return;\n try {\n await this.inboundHandler(normalized);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] handler threw: ${msg}\\n`);\n }\n }\n\n private passesMentionGuard(event: GatewayMessageEvent): boolean {\n if (event.platform !== \"line\") return true;\n const requireMention = this.opts.requireMention ?? true;\n if (!requireMention) return true;\n if (event.channel.type === \"dm\") return true;\n if (this.opts.botUserId === undefined) return true; // guard disabled\n return event.line.mentionees.includes(this.opts.botUserId);\n }\n\n /** Expose channel secret for the webhook server (signature middleware). */\n getChannelSecret(): string {\n return this.opts.channelSecret;\n }\n\n /** Used by tests to seed the reply cache (no other path exposes raw cache). */\n _cacheReplyToken(userId: string, token: string): void {\n this.replyCache.put(userId, token);\n }\n}\n\ninterface LineRestError {\n statusCode?: number;\n status?: number;\n message?: string;\n originalError?: { response?: { status?: number } };\n}\n\nfunction mapLineError(err: unknown): SendResult {\n const e = err as LineRestError;\n const status = e.statusCode ?? e.status ?? e.originalError?.response?.status ?? 0;\n if (status === 429) {\n return { ok: false, error: { code: \"rate_limit\", message: e.message ?? \"LINE rate limit\" } };\n }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n error: { code: \"permission_denied\", message: e.message ?? \"LINE auth error\" },\n };\n }\n if (status === 400) {\n return {\n ok: false,\n error: { code: \"invalid_request\", message: e.message ?? \"LINE rejected request\" },\n };\n }\n return {\n ok: false,\n error: {\n code: \"send_failed\",\n message: e.message ?? (err instanceof Error ? err.message : String(err)),\n },\n };\n}\n\n// `computeLineSignature` is already re-exported at the package root via `index.ts`;\n// no need to duplicate here.\n","/**\n * LINE HMAC-SHA256 signature verification (D408).\n *\n * Per LINE Developers docs:\n * signature = base64(hmac_sha256(channelSecret, rawBody))\n *\n * Carried in header `X-Line-Signature`.\n *\n * Always uses `crypto.timingSafeEqual` to prevent timing attacks.\n */\n\nimport crypto from \"node:crypto\";\n\nexport function computeLineSignature(channelSecret: string, rawBody: string): string {\n return crypto.createHmac(\"sha256\", channelSecret).update(rawBody, \"utf8\").digest(\"base64\");\n}\n\n/**\n * Verify LINE's `x-line-signature` header against the raw request body.\n *\n * Returns `false` for a missing, malformed or mismatched signature — never throws, so a hostile\n * header cannot become an unhandled error on the webhook path. Compare against the RAW body: any\n * re-serialisation of the parsed JSON changes the bytes and invalidates the signature.\n */\nexport function verifyLineSignature(\n channelSecret: string,\n rawBody: string,\n signatureHeader: string | undefined,\n): boolean {\n if (signatureHeader === undefined || signatureHeader.length === 0) return false;\n const expected = computeLineSignature(channelSecret, rawBody);\n const a = Buffer.from(expected);\n const b = Buffer.from(signatureHeader);\n if (a.length !== b.length) return false;\n try {\n return crypto.timingSafeEqual(a, b);\n } catch {\n return false;\n }\n}\n","/**\n * Express webhook server for LINE inbound.\n *\n * Validates `X-Line-Signature` (HMAC-SHA256 over raw body) BEFORE\n * parsing/dispatch — 401 on missing or invalid (D408).\n *\n * @public\n */\n\nimport type { Express, NextFunction, Request, Response } from \"express\";\n\nimport type { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineWebhookEnvelope } from \"./types.js\";\n\nexport interface WebhookServerOptions {\n readonly adapter: LineAdapter;\n /** Mount path; default `/line`. */\n readonly path?: string;\n /** Port to listen on when creating own Express app. Default 3000. */\n readonly port?: number;\n /** Inject an existing Express app. */\n readonly app?: Express;\n}\n\n/** A started HTTP listener, with the handle needed to shut it down again. */\nexport interface WebhookServer {\n start(): Promise<void>;\n stop(): Promise<void>;\n}\n\nasync function loadExpress(): Promise<{ default: () => Express }> {\n try {\n const mod = await import(\"express\");\n const fn = (mod as { default?: () => Express }).default ?? (mod as unknown as () => Express);\n return { default: fn };\n } catch {\n throw new ConfigurationError({\n code: \"express_not_installed\",\n message: 'gateway-line: peer-dep \"express\" not installed. Run: pnpm add express',\n });\n }\n}\n\nfunction rawCapture(req: Request, _res: Response, next: NextFunction): void {\n // Someone else already drained the stream — a global `express.json()` or\n // `express.urlencoded()` mounted ahead of this router is the usual cause.\n // Without this branch, `req.on(\"end\")` never fires for a stream that already\n // ended, `next()` is never called, and the request HANGS with no response at\n // all: the provider times out and retries, and no error is logged anywhere.\n // Failing loudly and continuing is strictly better — verification then\n // refuses the empty body with a 401, which is at least a visible symptom that\n // points at the real cause.\n if (req.readableEnded || req.complete) {\n process.stderr.write(\n \"[gateway] raw body already consumed before signature capture — mount this router \" +\n \"BEFORE any global body parser, or signature verification cannot see the bytes it \" +\n \"must hash\\n\",\n );\n (req as Request & { rawBody: string }).rawBody = \"\";\n next();\n return;\n }\n let buf = \"\";\n req.setEncoding(\"utf8\");\n req.on(\"data\", (chunk: string) => {\n buf += chunk;\n });\n req.on(\"end\", () => {\n (req as Request & { rawBody: string }).rawBody = buf;\n next();\n });\n req.on(\"error\", (err) => next(err));\n}\n\nfunction handlerFactory(adapter: LineAdapter) {\n return (req: Request, res: Response): void => {\n const rawBody = (req as Request & { rawBody?: string }).rawBody ?? \"\";\n const signature = headerOf(req, \"x-line-signature\");\n if (!verifyLineSignature(adapter.getChannelSecret(), rawBody, signature)) {\n res.status(401).type(\"text/plain\").send(\"invalid signature\");\n return;\n }\n let envelope: LineWebhookEnvelope;\n try {\n envelope = JSON.parse(rawBody) as LineWebhookEnvelope;\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!Array.isArray(envelope.events)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array\");\n return;\n }\n // Answered before dispatch, on purpose: LINE retries a webhook it did not see a 200 for,\n // and waiting on the handler turns a slow one into a duplicate delivery. What that costs is\n // that the dispatch is floated — and a floated rejection is an unhandled one, which ends the\n // process (the defect fixed across the other adapters in #41). The catch is what makes the\n // early answer safe rather than merely fast.\n void adapter.dispatchWebhookBody(envelope).catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n process.stderr.write(`[gateway-line] webhook dispatch failed: ${message}\\n`);\n });\n // LINE expects a 200 OK quickly to ack the webhook.\n res.status(200).end();\n };\n}\n\nfunction headerOf(req: Request, name: string): string | undefined {\n const v = req.headers[name.toLowerCase()];\n if (v === undefined) return undefined;\n return Array.isArray(v) ? v.join(\",\") : v;\n}\n\n/**\n * Build the HTTP listener that receives LINE's webhook deliveries.\n *\n * LINE dials in, so this endpoint must be reachable over public HTTPS and registered in the LINE\n * console — unlike the connection-based adapters, inbound cannot work behind a firewall. `express`\n * is loaded lazily, so a project that only sends messages never pays for it.\n */\nexport async function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer> {\n const expressMod = await loadExpress();\n const app: Express = opts.app ?? expressMod.default();\n const path = opts.path ?? \"/line\";\n app.post(path, rawCapture, handlerFactory(opts.adapter));\n\n let server: import(\"node:http\").Server | undefined;\n let started = false;\n let stopped = false;\n\n return {\n async start(): Promise<void> {\n if (started || opts.app !== undefined) {\n started = true;\n return;\n }\n // Cleared here, not in stop(): a server that was stopped and is starting again is no longer\n // stopped, and leaving the flag latched made the NEXT stop() a no-op that left the listener up.\n stopped = false;\n const port = opts.port ?? 3000;\n await new Promise<void>((resolve) => {\n server = app.listen(port, () => resolve());\n });\n started = true;\n },\n async stop(): Promise<void> {\n if (stopped) return;\n stopped = true;\n // The pair of latches used to be write-once, so `start()` after a `stop()` returned without\n // creating a listener and the server was silently dead — no error, no log, just a port nothing\n // answers on. Resetting `started` is what makes a restart a restart.\n started = false;\n if (server === undefined) return;\n await new Promise<void>((resolve) => {\n server?.close(() => resolve());\n });\n server = undefined;\n },\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theokit/gateway-line",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "LINE Messaging API platform adapter for @theokit/gateway. ADRs D405-D412.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"peerDependencies": {
|
|
38
38
|
"@line/bot-sdk": "^9.0.0",
|
|
39
39
|
"@theokit/gateway": ">=0.6.0 <1.0.0",
|
|
40
|
-
"express": "^4.18.0"
|
|
40
|
+
"express": "^4.18.0 || ^5.0.0"
|
|
41
41
|
},
|
|
42
42
|
"peerDependenciesMeta": {
|
|
43
43
|
"@line/bot-sdk": {
|
|
@@ -48,14 +48,16 @@
|
|
|
48
48
|
}
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
|
-
"@
|
|
52
|
-
"@
|
|
53
|
-
"
|
|
51
|
+
"@stryker-mutator/core": "10",
|
|
52
|
+
"@stryker-mutator/vitest-runner": "10",
|
|
53
|
+
"@theokit/sdk": "^4.62.0",
|
|
54
|
+
"@types/express": "^5.0.6",
|
|
55
|
+
"express": "^5.2.1",
|
|
54
56
|
"tsup": "^8.5.0",
|
|
55
|
-
"typescript": "
|
|
56
|
-
"vitest": "^4.1.
|
|
57
|
+
"typescript": "5.9.3",
|
|
58
|
+
"vitest": "^4.1.11",
|
|
57
59
|
"zod": "^4.0.0",
|
|
58
|
-
"@theokit/gateway": "0.
|
|
60
|
+
"@theokit/gateway": "0.8.0"
|
|
59
61
|
},
|
|
60
62
|
"publishConfig": {
|
|
61
63
|
"access": "public",
|
|
@@ -64,6 +66,7 @@
|
|
|
64
66
|
"scripts": {
|
|
65
67
|
"build": "tsup",
|
|
66
68
|
"typecheck": "tsc --noEmit",
|
|
67
|
-
"test": "vitest run"
|
|
69
|
+
"test": "vitest run",
|
|
70
|
+
"test:mutation": "stryker run"
|
|
68
71
|
}
|
|
69
72
|
}
|