@theokit/gateway-line 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,67 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b38172b: **The peer floor on `@theokit/gateway` rises with this release.** Every adapter now implements
8
+ `deliver` over `runHandler`, and neither exists in an older core — an adapter installed against one
9
+ does not build. `dep-check` caught that by building the whole workspace against the floor each
10
+ package claimed, which is the one thing a version range cannot tell you by reading it.
11
+
12
+ The floor is set in the version commit rather than here, because a range cannot name a version that
13
+ does not exist yet: raised in the workspace, the same gate then fails the other way round — every
14
+ adapter declaring a floor above the core installed beside it. That is the shape `fa70153` used when
15
+ these ranges were first written.
16
+
17
+ `deliver(event)` — every adapter can now be handed an event that arrived out of band (#83).
18
+
19
+ `onInbound` was the seam every adapter implemented and it had no public counterpart. Six platforms
20
+ self-deliver once connected — long polling, a gateway socket, Socket Mode, a sync loop, IMAP — so
21
+ the asymmetry stayed invisible: `GatewayRunner` worked for eight platforms and silently did nothing
22
+ for LINE and WhatsApp Cloud, whose payloads arrive on an HTTP route the application owns. Every app
23
+ wired those two by hand, beside the runner rather than through it.
24
+
25
+ ```ts
26
+ const outcome = await adapter.deliver(event); // "ok" | "no_handler" | "handler_threw"
27
+ ```
28
+
29
+ The three outcomes are distinguished because a caller acts on them differently: answering a webhook
30
+ 200 when nobody was subscribed tells the provider to stop retrying a message nothing received.
31
+
32
+ `BasePlatformAdapter.runHandler` holds the containment once, where ten copies of it used to live —
33
+ a handler is user code, its throw is named as the handler's failure rather than the platform's, and
34
+ delivery continues. Each adapter's `deliver` is one line over it.
35
+
36
+ Also: `gateway-sms`'s `createWebhookServer` now signs against the configured `publicUrl` (#90).
37
+ Twilio verifies against the URL it POSTed to, and behind a proxy that rewrites `host` — a tunnel, an
38
+ ingress, a load balancer terminating TLS — the reconstruction from headers yields the internal
39
+ address, so a correct signature fails on every delivery. `publicUrl` is required by all three
40
+ backend option shapes and documented as "used by signature verifier"; until now no source file read
41
+ it. The header reconstruction stays as the fallback for an app served directly.
42
+
43
+ ### Patch Changes
44
+
45
+ - 4b1d4bb: The half of an Express webhook server that is the same everywhere now lives in one place (#89).
46
+
47
+ `gateway-line` and `gateway-sms` each shipped one and shared 101 of ~170 lines: the lazy `express`
48
+ load, the raw-body capture with the hang it documents, and the start/stop lifecycle. What differs —
49
+ signature verification, body parsing, routing — stayed where it belongs.
50
+
51
+ It had already been paid for. A write-once latch made `start()` after `stop()` return without
52
+ creating a listener, which is a port nothing answers on with no error and no log, and the fix had to
53
+ be applied to both files by one commit because the latch lived in the copied half.
54
+
55
+ `@theokit/gateway` now exports `loadPeer`, `rawBodyCapture` and `listenerLifecycle`. **This does not
56
+ make express a dependency of the core**: nothing in that module imports it. Every shape is
57
+ structural — a request is whatever has `readableEnded` and `on`, a listener is whatever has `listen`
58
+ and `close` — so the two packages that use express keep declaring it and the core never learns the
59
+ name.
60
+
61
+ Every adapter README now states how inbound reaches it (#91): a webhook the application must
62
+ authenticate, a WebSocket, a sync loop, or an SDK that owns its own HTTP server. The three that have
63
+ no webhook say so with the reason, because an absence that is a decision should not read as a gap.
64
+
3
65
  ## 0.1.6
4
66
 
5
67
  ### Patch Changes
package/README.md CHANGED
@@ -4,6 +4,19 @@ LINE Messaging API platform adapter for [`@theokit/gateway`](../gateway).
4
4
 
5
5
  APAC consumer dominant — Japan (~85M MAU), Taiwan, Thailand. Webhook-only inbound (LINE doesn't offer a WebSocket gateway). HMAC-SHA256 signature validation on every POST.
6
6
 
7
+
8
+ ## How inbound arrives
9
+
10
+ **HTTP webhook**, and the application must authenticate it: LINE signs every POST with
11
+ HMAC-SHA256 over the raw body, and `verifyLineSignature(channelSecret, rawBody, signature)` is
12
+ exported for that.
13
+
14
+ Two ways to serve it. `createWebhookServer` mounts an Express route for you; or host the route
15
+ yourself and hand the parsed events to `adapter.deliver(event)`, which is what makes `GatewayRunner`
16
+ work for a webhook platform.
17
+
18
+ A validator in the shape `theokit/server/webhook` expects does not ship yet — see
19
+ [usetheokit/theokit#590](https://github.com/usetheokit/theokit/issues/590).
7
20
  ## Install
8
21
 
9
22
  ```bash
package/dist/index.cjs CHANGED
@@ -296,6 +296,15 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
296
296
  _cacheReplyToken(userId, token) {
297
297
  this.replyCache.put(userId, token);
298
298
  }
299
+ /**
300
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
301
+ *
302
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
303
+ * named as the handler's failure rather than the platform's, and delivery continues.
304
+ */
305
+ async deliver(event) {
306
+ return this.runHandler(this.inboundHandler, event);
307
+ }
299
308
  };
300
309
  function mapLineError(err) {
301
310
  const e = err;
@@ -338,39 +347,16 @@ function verifyLineSignature(channelSecret, rawBody, signatureHeader) {
338
347
  return false;
339
348
  }
340
349
  }
341
-
342
- // src/webhook-server.ts
343
350
  async function loadExpress() {
344
- try {
345
- const mod = await import('express');
346
- const fn = mod.default ?? mod;
347
- return { default: fn };
348
- } catch {
349
- throw new ConfigurationError({
350
- code: "express_not_installed",
351
- message: 'gateway-line: peer-dep "express" not installed. Run: pnpm add express'
352
- });
353
- }
354
- }
355
- function rawCapture(req, _res, next) {
356
- if (req.readableEnded || req.complete) {
357
- process.stderr.write(
358
- "[gateway] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash\n"
359
- );
360
- req.rawBody = "";
361
- next();
362
- return;
363
- }
364
- let buf = "";
365
- req.setEncoding("utf8");
366
- req.on("data", (chunk) => {
367
- buf += chunk;
368
- });
369
- req.on("end", () => {
370
- req.rawBody = buf;
371
- next();
372
- });
373
- req.on("error", (err) => next(err));
351
+ return gateway.loadPeer(
352
+ async () => import('express'),
353
+ () => {
354
+ throw new ConfigurationError({
355
+ code: "express_not_installed",
356
+ message: 'gateway-line: peer-dep "express" not installed. Run: pnpm add express'
357
+ });
358
+ }
359
+ );
374
360
  }
375
361
  function handlerFactory(adapter) {
376
362
  return (req, res) => {
@@ -405,37 +391,11 @@ function headerOf(req, name) {
405
391
  return Array.isArray(v) ? v.join(",") : v;
406
392
  }
407
393
  async function createWebhookServer(opts) {
408
- const expressMod = await loadExpress();
409
- const app = opts.app ?? expressMod.default();
394
+ const createApp = await loadExpress();
395
+ const app = opts.app ?? createApp();
410
396
  const path = opts.path ?? "/line";
411
- app.post(path, rawCapture, handlerFactory(opts.adapter));
412
- let server;
413
- let started = false;
414
- let stopped = false;
415
- return {
416
- async start() {
417
- if (started || opts.app !== void 0) {
418
- started = true;
419
- return;
420
- }
421
- stopped = false;
422
- const port = opts.port ?? 3e3;
423
- await new Promise((resolve) => {
424
- server = app.listen(port, () => resolve());
425
- });
426
- started = true;
427
- },
428
- async stop() {
429
- if (stopped) return;
430
- stopped = true;
431
- started = false;
432
- if (server === void 0) return;
433
- await new Promise((resolve) => {
434
- server?.close(() => resolve());
435
- });
436
- server = void 0;
437
- }
438
- };
397
+ app.post(path, gateway.rawBodyCapture("gateway-line"), handlerFactory(opts.adapter));
398
+ return gateway.listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
439
399
  }
440
400
 
441
401
  exports.ConfigurationError = ConfigurationError;
@@ -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;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B;AACF;AASO,IAAM,oBAAA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A,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"]}
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","loadPeer","rawBodyCapture","listenerLifecycle"],"mappings":";;;;;;;;;;AAsBO,IAA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,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F","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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\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 { listenerLifecycle, loadPeer, rawBodyCapture } from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { LineAdapter } from \"./adapter.js\";\n\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<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\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}\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 createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const path = opts.path ?? \"/line\";\n app.post(path, rawBodyCapture(\"gateway-line\"), handlerFactory(opts.adapter));\n\n // The lifecycle — and the latches that make a restart a restart — live in `@theokit/gateway`,\n // written once. They were duplicated here and in gateway-sms, and the same write-once bug had to\n // be fixed in both files by one commit, which is what made the duplication a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -145,6 +145,13 @@ declare class LineAdapter extends BasePlatformAdapter {
145
145
  getChannelSecret(): string;
146
146
  /** Used by tests to seed the reply cache (no other path exposes raw cache). */
147
147
  _cacheReplyToken(userId: string, token: string): void;
148
+ /**
149
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
150
+ *
151
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
152
+ * named as the handler's failure rather than the platform's, and delivery continues.
153
+ */
154
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
148
155
  }
149
156
 
150
157
  /**
package/dist/index.d.ts CHANGED
@@ -145,6 +145,13 @@ declare class LineAdapter extends BasePlatformAdapter {
145
145
  getChannelSecret(): string;
146
146
  /** Used by tests to seed the reply cache (no other path exposes raw cache). */
147
147
  _cacheReplyToken(userId: string, token: string): void;
148
+ /**
149
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
150
+ *
151
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
152
+ * named as the handler's failure rather than the platform's, and delivery continues.
153
+ */
154
+ deliver(event: MessageEvent): Promise<"ok" | "no_handler" | "handler_threw">;
148
155
  }
149
156
 
150
157
  /**
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { GatewayConfigurationError, chunkByGrapheme, BasePlatformAdapter } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, chunkByGrapheme, BasePlatformAdapter, rawBodyCapture, listenerLifecycle, loadPeer } from '@theokit/gateway';
2
2
  import crypto from 'crypto';
3
3
 
4
4
  // src/adapter.ts
@@ -290,6 +290,15 @@ var LineAdapter = class extends BasePlatformAdapter {
290
290
  _cacheReplyToken(userId, token) {
291
291
  this.replyCache.put(userId, token);
292
292
  }
293
+ /**
294
+ * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
295
+ *
296
+ * One line over `runHandler`, which owns the containment: a handler is user code, its throw is
297
+ * named as the handler's failure rather than the platform's, and delivery continues.
298
+ */
299
+ async deliver(event) {
300
+ return this.runHandler(this.inboundHandler, event);
301
+ }
293
302
  };
294
303
  function mapLineError(err) {
295
304
  const e = err;
@@ -332,39 +341,16 @@ function verifyLineSignature(channelSecret, rawBody, signatureHeader) {
332
341
  return false;
333
342
  }
334
343
  }
335
-
336
- // src/webhook-server.ts
337
344
  async function loadExpress() {
338
- try {
339
- const mod = await import('express');
340
- const fn = mod.default ?? mod;
341
- return { default: fn };
342
- } catch {
343
- throw new ConfigurationError({
344
- code: "express_not_installed",
345
- message: 'gateway-line: peer-dep "express" not installed. Run: pnpm add express'
346
- });
347
- }
348
- }
349
- function rawCapture(req, _res, next) {
350
- if (req.readableEnded || req.complete) {
351
- process.stderr.write(
352
- "[gateway] raw body already consumed before signature capture \u2014 mount this router BEFORE any global body parser, or signature verification cannot see the bytes it must hash\n"
353
- );
354
- req.rawBody = "";
355
- next();
356
- return;
357
- }
358
- let buf = "";
359
- req.setEncoding("utf8");
360
- req.on("data", (chunk) => {
361
- buf += chunk;
362
- });
363
- req.on("end", () => {
364
- req.rawBody = buf;
365
- next();
366
- });
367
- req.on("error", (err) => next(err));
345
+ return loadPeer(
346
+ async () => import('express'),
347
+ () => {
348
+ throw new ConfigurationError({
349
+ code: "express_not_installed",
350
+ message: 'gateway-line: peer-dep "express" not installed. Run: pnpm add express'
351
+ });
352
+ }
353
+ );
368
354
  }
369
355
  function handlerFactory(adapter) {
370
356
  return (req, res) => {
@@ -399,37 +385,11 @@ function headerOf(req, name) {
399
385
  return Array.isArray(v) ? v.join(",") : v;
400
386
  }
401
387
  async function createWebhookServer(opts) {
402
- const expressMod = await loadExpress();
403
- const app = opts.app ?? expressMod.default();
388
+ const createApp = await loadExpress();
389
+ const app = opts.app ?? createApp();
404
390
  const path = opts.path ?? "/line";
405
- app.post(path, rawCapture, handlerFactory(opts.adapter));
406
- let server;
407
- let started = false;
408
- let stopped = false;
409
- return {
410
- async start() {
411
- if (started || opts.app !== void 0) {
412
- started = true;
413
- return;
414
- }
415
- stopped = false;
416
- const port = opts.port ?? 3e3;
417
- await new Promise((resolve) => {
418
- server = app.listen(port, () => resolve());
419
- });
420
- started = true;
421
- },
422
- async stop() {
423
- if (stopped) return;
424
- stopped = true;
425
- started = false;
426
- if (server === void 0) return;
427
- await new Promise((resolve) => {
428
- server?.close(() => resolve());
429
- });
430
- server = void 0;
431
- }
432
- };
391
+ app.post(path, rawBodyCapture("gateway-line"), handlerFactory(opts.adapter));
392
+ return listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
433
393
  }
434
394
 
435
395
  export { ConfigurationError, LineAdapter, ReplyTokenCache, SDKNotInstalledError, computeLineSignature, createWebhookServer, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
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,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ACF","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"]}
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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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 /**\n * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).\n *\n * One line over `runHandler`, which owns the containment: a handler is user code, its throw is\n * named as the handler's failure rather than the platform's, and delivery continues.\n */\n override async deliver(\n event: GatewayMessageEvent,\n ): Promise<\"ok\" | \"no_handler\" | \"handler_threw\"> {\n return this.runHandler(this.inboundHandler, event);\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 { listenerLifecycle, loadPeer, rawBodyCapture } from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { LineAdapter } from \"./adapter.js\";\n\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<() => Express> {\n return loadPeer<() => Express>(\n async () => import(\"express\"),\n () => {\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}\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 createApp = await loadExpress();\n const app: Express = opts.app ?? createApp();\n const path = opts.path ?? \"/line\";\n app.post(path, rawBodyCapture(\"gateway-line\"), handlerFactory(opts.adapter));\n\n // The lifecycle — and the latches that make a restart a restart — live in `@theokit/gateway`,\n // written once. They were duplicated here and in gateway-sms, and the same write-once bug had to\n // be fixed in both files by one commit, which is what made the duplication a defect (#89).\n return listenerLifecycle({ app, port: opts.port ?? 3000, injected: opts.app !== undefined });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-line",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "LINE Messaging API platform adapter for @theokit/gateway. ADRs D405-D412.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -57,7 +57,7 @@
57
57
  "typescript": "5.9.3",
58
58
  "vitest": "^4.1.11",
59
59
  "zod": "^4.0.0",
60
- "@theokit/gateway": "0.8.0"
60
+ "@theokit/gateway": "0.9.0"
61
61
  },
62
62
  "publishConfig": {
63
63
  "access": "public",