@theokit/gateway-line 0.4.0 → 0.5.1

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,129 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 6329554: The LINE and SMS webhook routes answer 413 to a request body over 1 MiB instead of buffering it without limit before the signature check.
8
+ - bca7cfd: Raise the `@theokit/gateway` peer floor to the core version that ships the APIs this adapter imports, so npm no longer installs it next to a core it cannot load.
9
+
10
+ ## 0.5.0
11
+
12
+ ### Minor Changes
13
+
14
+ - 458c34c: Wire channels from descriptors, and keep the channels that connect when another cannot.
15
+
16
+ `@theokit/gateway` exports `createChannels` and the types `ChannelDescriptor`,
17
+ `ChannelConfigField`, `ChannelWebhook`, `WebhookRequest`, `IngestResult`, `ChannelEntry`,
18
+ `ChannelRejection` and `CreateChannelsResult`. `createChannels(entries)` builds an adapter per
19
+ entry and returns `{ adapters, rejected }`: an entry whose required field is absent, `null` or
20
+ `""` is rejected with a `GatewayConfigurationError` coded `missing_required_config` naming the
21
+ keys, and a configuration error thrown by the descriptor's `create` is rejected the same way. Any
22
+ other error propagates. It connects nothing and makes no network call.
23
+
24
+ `GatewayRunner` accepts `connectFailure: "rollback" | "isolate"` (exported as `ConnectFailure`),
25
+ and `StartResult` is exported.
26
+ The default, `"rollback"`, is unchanged: one failed connect disconnects the adapters that did
27
+ connect and rejects `start()`. Under `"isolate"`, `start()` connects every adapter, wires inbound
28
+ only for the ones that connected, and reports the rest with a redacted reason.
29
+
30
+ `start()` now resolves a `StartResult` (`{ connected, failed }`) instead of `void`, under both
31
+ values. This is a type change: code that awaits `start()` and ignores the value is unaffected,
32
+ but a structural type declaring `start(): Promise<void>` that a `GatewayRunner` is assigned to
33
+ fails with TS2322, and a subclass overriding `start()` with that signature fails with TS2416.
34
+
35
+ `@theokit/gateway-telegram` exports `telegramChannel`, a socket channel whose config has a
36
+ required, secret `token` and an optional `allowedUsers`, and a `ConfigurationError` (a
37
+ `GatewayConfigurationError` with the `gateway-telegram` prefix). Called directly,
38
+ `telegramChannel.create` refuses a token that is not a string or is empty, and an `allowedUsers`
39
+ that is not an array of strings; through `createChannels`, an absent or empty token is rejected
40
+ first, as `missing_required_config`.
41
+
42
+ `@theokit/gateway-line` exports `lineChannel`, a webhook channel whose `webhook.verify` checks the
43
+ `x-line-signature` header against the raw body and whose `webhook.ingest` dispatches a verified
44
+ payload through `dispatchWebhookBody`, so a reply uses the cached reply token, or answers
45
+ `"malformed"` without dispatching. It answers `"no_handler"` (a member of `IngestResult`) when the
46
+ payload holds a text message for the handler and none is subscribed: before the runner started,
47
+ after it stopped, or when LINE's connect failed under `"isolate"`. Before, such a request answered
48
+ `"delivered"`, a route acknowledged it, and LINE did not redeliver the lost message.
49
+ `lineChannel.create` checks field types before the adapter's constructor.
50
+
51
+ `LineAdapter.dispatchWebhookBody` now resolves `"ok" | "no_handler"` instead of `void`. It answers
52
+ `"no_handler"`, dispatching nothing and caching no reply token, for a batch holding a text message
53
+ that passes the mention guard while no handler is subscribed; an empty or follow-only batch still
54
+ answers `"ok"`. It reads the handler once per batch, so a handler that unsubscribes while handling
55
+ one event still receives the rest of the batch. Code that ignores the value is unaffected; a
56
+ subclass overriding the method with `Promise<void>` fails with TS2416. `createWebhookServer` is
57
+ unchanged and still answers 200 before it dispatches.
58
+
59
+ Both descriptors are typed locally and import nothing `@theokit/gateway` 0.9.0 lacks, so the peer
60
+ range stays `>=0.9.0 <1.0.0`.
61
+
62
+ ### Patch Changes
63
+
64
+ - e5a2603: Group messages that do not mention the bot are no longer delivered by default on Discord, Matrix
65
+ and Teams; pass `requireMention: false` to keep the old behaviour.
66
+
67
+ Discord, Matrix and Teams gain a `requireMention` option that defaults to `true`. With it on, a
68
+ group or thread message reaches the handler only when it mentions the bot, and a DM always does.
69
+ Discord reads the bot's id in `mentions.users` (a direct mention or a reply that pings it; not
70
+ `@everyone`, `@here` or roles), and drops group messages with one stderr line until the client is
71
+ ready. Matrix reads `m.mentions.user_ids`, and falls back to the full user id in `body` or
72
+ `formatted_body` when a client sends no `m.mentions`. Teams reads `mention` entities against the
73
+ activity's `recipient.id`, and drops a group activity that names no recipient with one stderr line.
74
+
75
+ LINE's `deliver()` now applies the mention guard its webhook route already applied.
76
+
77
+ On all four adapters `deliver()` and the adapter's own inbound path use one rule, and `deliver()`
78
+ answers `"ok"` for an event the rule drops, with or without a handler subscribed.
79
+
80
+ - 3f1788d: Send an image from a gateway handler, and refuse it wherever a platform cannot show one.
81
+
82
+ `@theokit/gateway` exports `OutboundAttachment` (`kind: "image"`, `mediaType`, `data`, optional
83
+ `filename`). `OutboundMessage` gains an optional `attachments` list, `ctx.reply(text, { attachments })`
84
+ carries it to the adapter (an empty list is left out), and `BasePlatformAdapter` declares
85
+ `supportsAttachments`, `false` by default. `DeliveryRouter.send` takes the same `attachments`
86
+ field. The runner and the router refuse an outbound carrying attachments as
87
+ `attachments_unsupported`, with no `sendMessage` call, when the adapter does not declare
88
+ `supportsAttachments`.
89
+
90
+ `@theokit/gateway-telegram` reports `supportsAttachments: true` and sends each image through
91
+ `sendPhoto`, the text as the first photo's caption up to 1024 UTF-16 units and after the photos
92
+ when longer. A non-image kind is refused as `attachments_unsupported`; a missing image, more
93
+ than 10 images or an image over 10 MiB as `invalid_attachment`; all with no request.
94
+
95
+ Every other adapter, and every adapter's `editMessage`, refuses an outbound carrying attachments
96
+ with `attachments_unsupported` and makes no platform call, instead of sending the text and
97
+ dropping the image.
98
+
99
+ The runner's auto-reply to a blocking `pre_inbound` hook no longer discards a `sendMessage` that
100
+ throws: the error reaches the `on_error` hooks with the event and is written to stderr, redacted,
101
+ as a handler error is. Dispatch still does not throw.
102
+
103
+ - e980fb8: `@theokit/gateway` exports `SeenIds` (a bounded set of delivered ids) and `splitKeepingRows` (a
104
+ grapheme-safe split that keeps Markdown table rows whole). The SMS and LINE adapters import
105
+ `splitKeepingRows` instead of carrying copies; their peer floor is now `>=0.13.0`.
106
+ - e9be726: Keep Markdown table rows intact through translation and splitting.
107
+
108
+ `channelRendering(platform).translate` and `toDialect` now rewrite a table row (a line whose first
109
+ non-blank character is `|`) one cell at a time. Before, an emphasis span could open in one cell
110
+ and close in the next, so `| 2 x *a | b* y |` lost both stars on the ten platforms that rewrite
111
+ markers. Text where no span crosses a row's pipe translates exactly as before. A lone `\r` counts
112
+ as a line ending, as in GFM. Inline code that holds an unescaped pipe inside a row is split at
113
+ that pipe, as GFM splits the cell, so its backticks no longer pair and the platforms that strip
114
+ markers now keep them.
115
+
116
+ `splitForLine` and `splitForSMS` no longer cut a table row in two at a part
117
+ boundary. When a cut would fall inside a row that fits in one part, the part ends before that row
118
+ and the row starts the next part. A row longer than a part is still cut by length. Every
119
+ character is kept, and every part stays within its limit (with the `(i/N) ` prefix counted on
120
+ SMS, whose numbering follows the new part count) except a single grapheme longer than the limit,
121
+ which is emitted whole as its own part, as before. Text with no table row splits exactly as
122
+ before. Two rows that each fill a part exactly arrive as three parts, the second holding only the
123
+ line ending between them.
124
+
125
+ No export, signature, dependency or peer range changes.
126
+
3
127
  ## 0.4.0
4
128
 
5
129
  ### Minor Changes
package/README.md CHANGED
@@ -15,8 +15,13 @@ Two ways to serve it. `createWebhookServer` mounts an Express route for you; or
15
15
  yourself and hand the parsed events to `adapter.deliver(event)`, which is what makes `GatewayRunner`
16
16
  work for a webhook platform.
17
17
 
18
- 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).
18
+ `lineWebhookVerifier(adapter)` is a validator in the shape `theokit/server/webhook` expects
19
+ (`(request) => Promise<{ ok: true } | { ok: false; reason }>`), for the framework's `validators`
20
+ map: `validators: { line: lineWebhookVerifier(adapter) }`. It reads the raw body and the
21
+ `x-line-signature` header. The framework does not ship a LINE validator of its own
22
+ ([usetheokit/theokit#590](https://github.com/usetheokit/theokit/issues/590)), so this package
23
+ provides it.
24
+
20
25
  ## Install
21
26
 
22
27
  ```bash
package/dist/index.cjs CHANGED
@@ -59,10 +59,10 @@ function mapSourceType(sourceType) {
59
59
  }
60
60
  function lineEventToMessageEvent(event) {
61
61
  if (event.type !== "message") return void 0;
62
- if (event.message === void 0) return void 0;
62
+ if (event.message == null) return void 0;
63
63
  if (event.message.type !== "text") return void 0;
64
64
  const source = event.source;
65
- if (source === void 0) return void 0;
65
+ if (source == null) return void 0;
66
66
  const sourceId = source.userId ?? source.groupId ?? source.roomId;
67
67
  const sourceType = source.type;
68
68
  if (sourceId === void 0 || sourceId.length === 0) return void 0;
@@ -90,6 +90,15 @@ function lineEventToMessageEvent(event) {
90
90
  };
91
91
  }
92
92
 
93
+ // src/refuse-attachments.ts
94
+ function refuseAttachments(out) {
95
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
96
+ return {
97
+ ok: false,
98
+ error: { code: "attachments_unsupported", message: "line adapter cannot send attachments" }
99
+ };
100
+ }
101
+
93
102
  // src/reply-cache.ts
94
103
  var DEFAULT_TTL_MS = 6e4;
95
104
  var DEFAULT_CAPACITY = 1e3;
@@ -124,7 +133,9 @@ var ReplyTokenCache = class {
124
133
  }
125
134
  };
126
135
  function splitForLine(text, limit = 5e3) {
127
- return gateway.chunkByGrapheme(text, { limit });
136
+ if (text.length <= limit) return gateway.chunkByGrapheme(text, { limit });
137
+ gateway.chunkByGrapheme("", { limit });
138
+ return gateway.splitKeepingRows(text, limit);
128
139
  }
129
140
 
130
141
  // src/adapter.ts
@@ -180,8 +191,11 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
180
191
  this.inboundHandler = void 0;
181
192
  this.replyCache.clear();
182
193
  }
183
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.
184
194
  async sendMessage(out) {
195
+ return refuseAttachments(out) ?? this.sendText(out);
196
+ }
197
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: reply-token-vs-push selection + multipart loop + per-part error mapping is one cohesive send pipeline (D407 + D411); splitting hurts traceability.
198
+ async sendText(out) {
185
199
  if (out.text.length === 0) {
186
200
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
187
201
  }
@@ -317,6 +331,7 @@ var LineAdapter = class extends gateway.BasePlatformAdapter {
317
331
  * named as the handler's failure rather than the platform's, and delivery continues.
318
332
  */
319
333
  async deliver(event) {
334
+ if (!this.passesMentionGuard(event)) return "ok";
320
335
  return this.runHandler(this.inboundHandler, event);
321
336
  }
322
337
  };
@@ -346,6 +361,13 @@ function mapLineError(err) {
346
361
  }
347
362
  };
348
363
  }
364
+
365
+ // src/envelope.ts
366
+ function isEnvelope(payload) {
367
+ if (typeof payload !== "object" || payload === null) return false;
368
+ const events = payload.events;
369
+ return Array.isArray(events) && events.every((event) => typeof event === "object" && event !== null);
370
+ }
349
371
  function computeLineSignature(channelSecret, rawBody) {
350
372
  return crypto__default.default.createHmac("sha256", channelSecret).update(rawBody, "utf8").digest("base64");
351
373
  }
@@ -402,11 +424,6 @@ function headerValue(headers, name) {
402
424
  }
403
425
  return void 0;
404
426
  }
405
- function isEnvelope(payload) {
406
- if (typeof payload !== "object" || payload === null) return false;
407
- const events = payload.events;
408
- return Array.isArray(events) && events.every((event) => typeof event === "object" && event !== null);
409
- }
410
427
  var CONFIG = [
411
428
  {
412
429
  key: "channelSecret",
@@ -478,8 +495,8 @@ function handlerFactory(adapter) {
478
495
  res.status(400).type("text/plain").send("invalid JSON body");
479
496
  return;
480
497
  }
481
- if (!Array.isArray(envelope.events)) {
482
- res.status(400).type("text/plain").send("missing 'events' array");
498
+ if (!isEnvelope(envelope)) {
499
+ res.status(400).type("text/plain").send("missing 'events' array of objects");
483
500
  return;
484
501
  }
485
502
  void adapter.dispatchWebhookBody(envelope).catch((err) => {
@@ -499,10 +516,25 @@ async function createWebhookServer(opts) {
499
516
  const createApp = await loadExpress();
500
517
  const app = opts.app ?? createApp();
501
518
  const path = opts.path ?? "/line";
502
- app.post(path, gateway.rawBodyCapture("gateway-line"), handlerFactory(opts.adapter));
519
+ app.post(
520
+ path,
521
+ gateway.rawBodyCapture("gateway-line", { maxBytes: gateway.DEFAULT_WEBHOOK_MAX_BYTES }),
522
+ handlerFactory(opts.adapter)
523
+ );
503
524
  return gateway.listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
504
525
  }
505
526
 
527
+ // src/webhook-verifier.ts
528
+ function lineWebhookVerifier(source) {
529
+ return async (request) => {
530
+ const rawBody = await request.text();
531
+ const signature = request.headers.get("x-line-signature") ?? void 0;
532
+ if (signature === void 0) return { ok: false, reason: "missing x-line-signature header" };
533
+ const secret = typeof source === "string" ? source : source.getChannelSecret();
534
+ return verifyLineSignature(secret, rawBody, signature) ? { ok: true } : { ok: false, reason: "signature mismatch" };
535
+ };
536
+ }
537
+
506
538
  exports.ConfigurationError = ConfigurationError;
507
539
  exports.LineAdapter = LineAdapter;
508
540
  exports.ReplyTokenCache = ReplyTokenCache;
@@ -511,6 +543,7 @@ exports.computeLineSignature = computeLineSignature;
511
543
  exports.createWebhookServer = createWebhookServer;
512
544
  exports.lineChannel = lineChannel;
513
545
  exports.lineEventToMessageEvent = lineEventToMessageEvent;
546
+ exports.lineWebhookVerifier = lineWebhookVerifier;
514
547
  exports.mapSourceType = mapSourceType;
515
548
  exports.splitForLine = splitForLine;
516
549
  exports.verifyLineSignature = verifyLineSignature;
@@ -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/channel.ts","../src/webhook-server.ts"],"names":["GatewayConfigurationError","chunkByGrapheme","BasePlatformAdapter","crypto","loadPeer","rawBodyCapture","listenerLifecycle"],"mappings":";;;;;;;;;;AAsBO,IAAM,kBAAA,GAAN,cAAiCA,iCAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;A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CAAA;AAK3E,EAAA,OAAOC,yBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,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 AFTER signature validation. Iterates LINE's batch envelope and\n * dispatches each event.\n *\n * Answers `\"no_handler\"`, dispatching nothing and caching no reply token, when the batch holds an\n * event the handler would receive (a text message that passes the mention guard) and no handler\n * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired\n * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not\n * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's\n * console verification, or only follow and media events) answers `\"ok\"` either way. The handler is\n * read once per batch, so one that unsubscribes while handling an event still gets the rest.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<\"ok\" | \"no_handler\"> {\n const handler = this.inboundHandler;\n const events = envelope.events.map((ev) => ({ ev, normalized: lineEventToMessageEvent(ev) }));\n const deliverable = events.some(\n ({ normalized }) => normalized !== undefined && this.passesMentionGuard(normalized),\n );\n if (handler === undefined && deliverable) return \"no_handler\";\n for (const { ev, normalized } of events) {\n await this.dispatchSingleEvent(ev, normalized, handler);\n }\n return \"ok\";\n }\n\n private async dispatchSingleEvent(\n ev: LineWebhookEvent,\n normalized: GatewayMessageEvent | undefined,\n handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined,\n ): Promise<void> {\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 (handler === undefined) return;\n try {\n await handler(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 * `lineChannel` — the LINE channel described as data (FR-005 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope } from \"./types.js\";\n\nconst SIGNATURE_HEADER = \"x-line-signature\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-line: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\n/** A required string; an empty one is left for the adapter's own check, which names it. */\nfunction requiredString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n}\n\n/** An optional value: `undefined`, `null` and `\"\"` are absent, anything else must pass `check`. */\nfunction optional<T>(\n config: Readonly<Record<string, unknown>>,\n key: string,\n check: (value: unknown) => value is T,\n expected: string,\n): T | undefined {\n const value = config[key];\n if (value === undefined || value === null || value === \"\") return undefined;\n if (!check(value)) throw invalid(key, expected);\n return value;\n}\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction buildOptions(config: Readonly<Record<string, unknown>>): LineAdapterOptions {\n // Types are checked here, before the constructor: a numeric secret passes the constructor's\n // length check (`adapter.ts:32`) and would throw later, inside the signature HMAC, on the request\n // path. An empty secret or token is then refused by the constructor's own ConfigurationError.\n const channelSecret = requiredString(config, \"channelSecret\");\n const channelAccessToken = requiredString(config, \"channelAccessToken\");\n const botUserId = optional(config, \"botUserId\", isString, \"a string\");\n const requireMention = optional(config, \"requireMention\", isBoolean, \"a boolean\");\n return {\n channelSecret,\n channelAccessToken,\n ...(botUserId !== undefined ? { botUserId } : {}),\n ...(requireMention !== undefined ? { requireMention } : {}),\n };\n}\n\nfunction headerValue(\n headers: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) return value;\n }\n return undefined;\n}\n\n/** A LINE webhook envelope: an object whose `events` is an array of objects. */\nfunction isEnvelope(payload: unknown): payload is LineWebhookEnvelope {\n if (typeof payload !== \"object\" || payload === null) return false;\n const events = (payload as { events?: unknown }).events;\n return (\n Array.isArray(events) && events.every((event) => typeof event === \"object\" && event !== null)\n );\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"channelSecret\",\n required: true,\n secret: true,\n description: \"The channel secret that signs inbound webhooks (LINE Developers Console).\",\n },\n {\n key: \"channelAccessToken\",\n required: true,\n secret: true,\n description: \"The channel's long-lived access token (LINE Developers Console).\",\n },\n {\n key: \"botUserId\",\n required: false,\n secret: false,\n description: \"The bot's own user id; with requireMention, group messages must mention it.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"Whether group messages must mention the bot. Default true.\",\n },\n];\n\n/**\n * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to\n * `webhook.verify` and then `webhook.ingest`.\n *\n * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's\n * channel secret. `ingest` reports `\"malformed\"` for a payload with no `events` array or with an\n * event that is not an object, dispatching nothing; otherwise it dispatches through\n * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply\n * uses the reply API. A follow or other non-text event is skipped and still reports `\"delivered\"`.\n * It reports `\"no_handler\"`, dispatching nothing, when the payload holds a text message for the\n * handler and none is subscribed (before the runner started, after it stopped, or when this\n * adapter's connect failed under `connectFailure: \"isolate\"`). Only `\"delivered\"` should be\n * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered\n * otherwise.\n * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,\n * both with this package's `ConfigurationError`.\n *\n * @public\n */\nexport const lineChannel = {\n platform: \"line\" as const,\n transport: \"webhook\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): LineAdapter {\n return new LineAdapter(buildOptions(config));\n },\n webhook: {\n verify(\n adapter: LineAdapter,\n request: {\n readonly rawBody: string;\n readonly headers: Readonly<Record<string, string | undefined>>;\n },\n ): boolean {\n const signature = headerValue(request.headers, SIGNATURE_HEADER);\n return verifyLineSignature(adapter.getChannelSecret(), request.rawBody, signature);\n },\n async ingest(\n adapter: LineAdapter,\n payload: unknown,\n ): Promise<\"delivered\" | \"malformed\" | \"no_handler\"> {\n if (!isEnvelope(payload)) return \"malformed\";\n const outcome = await adapter.dispatchWebhookBody(payload);\n return outcome === \"no_handler\" ? \"no_handler\" : \"delivered\";\n },\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"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/envelope.ts","../src/signature.ts","../src/channel.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":["GatewayConfigurationError","chunkByGrapheme","splitKeepingRows","BasePlatformAdapter","crypto","loadPeer","rawBodyCapture","DEFAULT_WEBHOOK_MAX_BYTES","listenerLifecycle"],"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,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACKA,eAAsB,WAAA,GAAsC;AAC1D,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAA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AA,GAAO,KAAK,IAAA,IAAQ,OAAA;AAC1B,EAAA,GAAA,CAAI,IAAA;AAAA,IACF,IAAA;AAAA,IACAC,sBAAA,CAAe,cAAA,EAAgB,EAAE,QAAA,EAAUC,mCAA2B,CAAA;AAAA,IACtE,cAAA,CAAe,KAAK,OAAO;AAAA,GAC7B;AAKA,EAAA,OAAOC,yBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F;;;ACjFO,SAAS,oBACd,MAAA,EACwD;AACxD,EAAA,OAAO,OAAO,OAAA,KAAuD;AACnE,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,IAAA,EAAK;AACnC,IAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAA,IAAK,MAAA;AAC7D,IAAA,IAAI,cAAc,MAAA,EAAW,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,QAAQ,iCAAA,EAAkC;AAC3F,IAAA,MAAM,SAAS,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,GAAS,OAAO,gBAAA,EAAiB;AAC7E,IAAA,OAAO,mBAAA,CAAoB,MAAA,EAAQ,OAAA,EAAS,SAAS,CAAA,GACjD,EAAE,EAAA,EAAI,IAAA,EAAK,GACX,EAAE,EAAA,EAAI,KAAA,EAAO,QAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;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 == null) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source == null) 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 * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"line adapter cannot send attachments\" },\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), keeping table rows whole.\n *\n * LINE limits text messages to 5000 chars. A text within the limit goes through core\n * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,\n * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and\n * combining sequences are never severed and text with no table row splits exactly as it did\n * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in\n * `tests/split-tables.test.ts`).\n *\n * A cut that falls inside a Markdown table row which fits in a part moves back to the start of\n * that row, so the row arrives whole in the next message (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-sms.\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit });\n return splitKeepingRows(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 { refuseAttachments } from \"./refuse-attachments.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 async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\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 private async sendText(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 AFTER signature validation. Iterates LINE's batch envelope and\n * dispatches each event.\n *\n * Answers `\"no_handler\"`, dispatching nothing and caching no reply token, when the batch holds an\n * event the handler would receive (a text message that passes the mention guard) and no handler\n * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired\n * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not\n * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's\n * console verification, or only follow and media events) answers `\"ok\"` either way. The handler is\n * read once per batch, so one that unsubscribes while handling an event still gets the rest.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<\"ok\" | \"no_handler\"> {\n const handler = this.inboundHandler;\n const events = envelope.events.map((ev) => ({ ev, normalized: lineEventToMessageEvent(ev) }));\n const deliverable = events.some(\n ({ normalized }) => normalized !== undefined && this.passesMentionGuard(normalized),\n );\n if (handler === undefined && deliverable) return \"no_handler\";\n for (const { ev, normalized } of events) {\n await this.dispatchSingleEvent(ev, normalized, handler);\n }\n return \"ok\";\n }\n\n private async dispatchSingleEvent(\n ev: LineWebhookEvent,\n normalized: GatewayMessageEvent | undefined,\n handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined,\n ): Promise<void> {\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 (handler === undefined) return;\n try {\n await handler(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 // The webhook path applies the same guard (D409); a dropped event is acknowledged, not delivered.\n if (!this.passesMentionGuard(event)) return \"ok\";\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","import type { LineWebhookEnvelope } from \"./types.js\";\n\n/** A LINE webhook envelope: an object whose `events` is an array of objects. */\nexport function isEnvelope(payload: unknown): payload is LineWebhookEnvelope {\n if (typeof payload !== \"object\" || payload === null) return false;\n const events = (payload as { events?: unknown }).events;\n return (\n Array.isArray(events) && events.every((event) => typeof event === \"object\" && event !== null)\n );\n}\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 * `lineChannel` — the LINE channel described as data (FR-005 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { LineAdapter } from \"./adapter.js\";\nimport { isEnvelope } from \"./envelope.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineAdapterOptions } from \"./types.js\";\n\nconst SIGNATURE_HEADER = \"x-line-signature\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-line: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\n/** A required string; an empty one is left for the adapter's own check, which names it. */\nfunction requiredString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n}\n\n/** An optional value: `undefined`, `null` and `\"\"` are absent, anything else must pass `check`. */\nfunction optional<T>(\n config: Readonly<Record<string, unknown>>,\n key: string,\n check: (value: unknown) => value is T,\n expected: string,\n): T | undefined {\n const value = config[key];\n if (value === undefined || value === null || value === \"\") return undefined;\n if (!check(value)) throw invalid(key, expected);\n return value;\n}\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction buildOptions(config: Readonly<Record<string, unknown>>): LineAdapterOptions {\n // Types are checked here, before the constructor: a numeric secret passes the constructor's\n // length check (`adapter.ts:32`) and would throw later, inside the signature HMAC, on the request\n // path. An empty secret or token is then refused by the constructor's own ConfigurationError.\n const channelSecret = requiredString(config, \"channelSecret\");\n const channelAccessToken = requiredString(config, \"channelAccessToken\");\n const botUserId = optional(config, \"botUserId\", isString, \"a string\");\n const requireMention = optional(config, \"requireMention\", isBoolean, \"a boolean\");\n return {\n channelSecret,\n channelAccessToken,\n ...(botUserId !== undefined ? { botUserId } : {}),\n ...(requireMention !== undefined ? { requireMention } : {}),\n };\n}\n\nfunction headerValue(\n headers: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) return value;\n }\n return undefined;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"channelSecret\",\n required: true,\n secret: true,\n description: \"The channel secret that signs inbound webhooks (LINE Developers Console).\",\n },\n {\n key: \"channelAccessToken\",\n required: true,\n secret: true,\n description: \"The channel's long-lived access token (LINE Developers Console).\",\n },\n {\n key: \"botUserId\",\n required: false,\n secret: false,\n description: \"The bot's own user id; with requireMention, group messages must mention it.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"Whether group messages must mention the bot. Default true.\",\n },\n];\n\n/**\n * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to\n * `webhook.verify` and then `webhook.ingest`.\n *\n * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's\n * channel secret. `ingest` reports `\"malformed\"` for a payload with no `events` array or with an\n * event that is not an object, dispatching nothing; otherwise it dispatches through\n * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply\n * uses the reply API. A follow or other non-text event is skipped and still reports `\"delivered\"`.\n * It reports `\"no_handler\"`, dispatching nothing, when the payload holds a text message for the\n * handler and none is subscribed (before the runner started, after it stopped, or when this\n * adapter's connect failed under `connectFailure: \"isolate\"`). Only `\"delivered\"` should be\n * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered\n * otherwise.\n * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,\n * both with this package's `ConfigurationError`.\n *\n * @public\n */\nexport const lineChannel = {\n platform: \"line\" as const,\n transport: \"webhook\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): LineAdapter {\n return new LineAdapter(buildOptions(config));\n },\n webhook: {\n verify(\n adapter: LineAdapter,\n request: {\n readonly rawBody: string;\n readonly headers: Readonly<Record<string, string | undefined>>;\n },\n ): boolean {\n const signature = headerValue(request.headers, SIGNATURE_HEADER);\n return verifyLineSignature(adapter.getChannelSecret(), request.rawBody, signature);\n },\n async ingest(\n adapter: LineAdapter,\n payload: unknown,\n ): Promise<\"delivered\" | \"malformed\" | \"no_handler\"> {\n if (!isEnvelope(payload)) return \"malformed\";\n const outcome = await adapter.dispatchWebhookBody(payload);\n return outcome === \"no_handler\" ? \"no_handler\" : \"delivered\";\n },\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 {\n DEFAULT_WEBHOOK_MAX_BYTES,\n listenerLifecycle,\n loadPeer,\n rawBodyCapture,\n} from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { LineAdapter } from \"./adapter.js\";\n\nimport { isEnvelope } from \"./envelope.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.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: unknown;\n try {\n envelope = JSON.parse(rawBody);\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!isEnvelope(envelope)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array of objects\");\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(\n path,\n rawBodyCapture(\"gateway-line\", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),\n handlerFactory(opts.adapter),\n );\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","/**\n * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators\n * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so\n * this package imports nothing from the framework.\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { line: lineWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport { verifyLineSignature } from \"./signature.js\";\n\n/** What a verifier answers. @public */\nexport type LineWebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).\n *\n * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the\n * body is needed afterwards.\n *\n * @public\n */\nexport function lineWebhookVerifier(\n source: string | { getChannelSecret(): string },\n): (request: Request) => Promise<LineWebhookVerifyResult> {\n return async (request: Request): Promise<LineWebhookVerifyResult> => {\n const rawBody = await request.text();\n const signature = request.headers.get(\"x-line-signature\") ?? undefined;\n if (signature === undefined) return { ok: false, reason: \"missing x-line-signature header\" };\n const secret = typeof source === \"string\" ? source : source.getChannelSecret();\n return verifyLineSignature(secret, rawBody, signature)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -129,6 +129,7 @@ declare class LineAdapter extends BasePlatformAdapter {
129
129
  connect(): Promise<boolean>;
130
130
  disconnect(): Promise<void>;
131
131
  sendMessage(out: OutboundMessage): Promise<SendResult>;
132
+ private sendText;
132
133
  /** Whether the "this platform has no text formatting" warning has already been emitted. */
133
134
  private warnedAboutFormat;
134
135
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
@@ -311,13 +312,18 @@ declare function computeLineSignature(channelSecret: string, rawBody: string): s
311
312
  declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
312
313
 
313
314
  /**
314
- * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
315
+ * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7), keeping table rows whole.
315
316
  *
316
- * LINE limits text messages to 5000 chars. Thin wrapper over core
317
- * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme
318
- * walk so emoji, regional indicators, and combining sequences are never severed.
319
- * Output is byte-identical to the previous implementation (pinned by
320
- * `tests/split.test.ts`).
317
+ * LINE limits text messages to 5000 chars. A text within the limit goes through core
318
+ * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,
319
+ * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and
320
+ * combining sequences are never severed and text with no table row splits exactly as it did
321
+ * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in
322
+ * `tests/split-tables.test.ts`).
323
+ *
324
+ * A cut that falls inside a Markdown table row which fits in a part moves back to the start of
325
+ * that row, so the row arrives whole in the next message (B-556). The rule is core
326
+ * `splitKeepingRows`, shared with gateway-sms.
321
327
  */
322
328
  declare function splitForLine(text: string, limit?: number): string[];
323
329
 
@@ -353,4 +359,36 @@ interface WebhookServer {
353
359
  */
354
360
  declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
355
361
 
356
- export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
362
+ /**
363
+ * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators
364
+ * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so
365
+ * this package imports nothing from the framework.
366
+ *
367
+ * ```ts
368
+ * await handleChannelWebhook(request, pathname, {
369
+ * validators: { line: lineWebhookVerifier(adapter) },
370
+ * })
371
+ * ```
372
+ *
373
+ * @public
374
+ */
375
+ /** What a verifier answers. @public */
376
+ type LineWebhookVerifyResult = {
377
+ readonly ok: true;
378
+ } | {
379
+ readonly ok: false;
380
+ readonly reason: string;
381
+ };
382
+ /**
383
+ * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).
384
+ *
385
+ * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the
386
+ * body is needed afterwards.
387
+ *
388
+ * @public
389
+ */
390
+ declare function lineWebhookVerifier(source: string | {
391
+ getChannelSecret(): string;
392
+ }): (request: Request) => Promise<LineWebhookVerifyResult>;
393
+
394
+ export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, type LineWebhookVerifyResult, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, lineWebhookVerifier, mapSourceType, splitForLine, verifyLineSignature };
package/dist/index.d.ts CHANGED
@@ -129,6 +129,7 @@ declare class LineAdapter extends BasePlatformAdapter {
129
129
  connect(): Promise<boolean>;
130
130
  disconnect(): Promise<void>;
131
131
  sendMessage(out: OutboundMessage): Promise<SendResult>;
132
+ private sendText;
132
133
  /** Whether the "this platform has no text formatting" warning has already been emitted. */
133
134
  private warnedAboutFormat;
134
135
  onInbound(handler: (event: MessageEvent) => Promise<void>): () => void;
@@ -311,13 +312,18 @@ declare function computeLineSignature(channelSecret: string, rawBody: string): s
311
312
  declare function verifyLineSignature(channelSecret: string, rawBody: string, signatureHeader: string | undefined): boolean;
312
313
 
313
314
  /**
314
- * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7).
315
+ * Grapheme-cluster-safe split for LINE outbound text (D411, EC-7), keeping table rows whole.
315
316
  *
316
- * LINE limits text messages to 5000 chars. Thin wrapper over core
317
- * `chunkByGrapheme` (roadmap M1) — single-sources the `Intl.Segmenter` grapheme
318
- * walk so emoji, regional indicators, and combining sequences are never severed.
319
- * Output is byte-identical to the previous implementation (pinned by
320
- * `tests/split.test.ts`).
317
+ * LINE limits text messages to 5000 chars. A text within the limit goes through core
318
+ * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,
319
+ * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and
320
+ * combining sequences are never severed and text with no table row splits exactly as it did
321
+ * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in
322
+ * `tests/split-tables.test.ts`).
323
+ *
324
+ * A cut that falls inside a Markdown table row which fits in a part moves back to the start of
325
+ * that row, so the row arrives whole in the next message (B-556). The rule is core
326
+ * `splitKeepingRows`, shared with gateway-sms.
321
327
  */
322
328
  declare function splitForLine(text: string, limit?: number): string[];
323
329
 
@@ -353,4 +359,36 @@ interface WebhookServer {
353
359
  */
354
360
  declare function createWebhookServer(opts: WebhookServerOptions): Promise<WebhookServer>;
355
361
 
356
- export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
362
+ /**
363
+ * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators
364
+ * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so
365
+ * this package imports nothing from the framework.
366
+ *
367
+ * ```ts
368
+ * await handleChannelWebhook(request, pathname, {
369
+ * validators: { line: lineWebhookVerifier(adapter) },
370
+ * })
371
+ * ```
372
+ *
373
+ * @public
374
+ */
375
+ /** What a verifier answers. @public */
376
+ type LineWebhookVerifyResult = {
377
+ readonly ok: true;
378
+ } | {
379
+ readonly ok: false;
380
+ readonly reason: string;
381
+ };
382
+ /**
383
+ * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).
384
+ *
385
+ * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the
386
+ * body is needed afterwards.
387
+ *
388
+ * @public
389
+ */
390
+ declare function lineWebhookVerifier(source: string | {
391
+ getChannelSecret(): string;
392
+ }): (request: Request) => Promise<LineWebhookVerifyResult>;
393
+
394
+ export { ConfigurationError, LineAdapter, type LineAdapterOptions, type LineMessage, type LineSource, type LineWebhookEnvelope, type LineWebhookEvent, type LineWebhookVerifyResult, ReplyTokenCache, SDKNotInstalledError, type WebhookServer, type WebhookServerOptions, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, lineWebhookVerifier, mapSourceType, splitForLine, verifyLineSignature };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { GatewayConfigurationError, chunkByGrapheme, BasePlatformAdapter, rawBodyCapture, listenerLifecycle, loadPeer } from '@theokit/gateway';
1
+ import { GatewayConfigurationError, chunkByGrapheme, splitKeepingRows, BasePlatformAdapter, rawBodyCapture, DEFAULT_WEBHOOK_MAX_BYTES, listenerLifecycle, loadPeer } from '@theokit/gateway';
2
2
  import crypto from 'crypto';
3
3
 
4
4
  // src/adapter.ts
@@ -53,10 +53,10 @@ function mapSourceType(sourceType) {
53
53
  }
54
54
  function lineEventToMessageEvent(event) {
55
55
  if (event.type !== "message") return void 0;
56
- if (event.message === void 0) return void 0;
56
+ if (event.message == null) return void 0;
57
57
  if (event.message.type !== "text") return void 0;
58
58
  const source = event.source;
59
- if (source === void 0) return void 0;
59
+ if (source == null) return void 0;
60
60
  const sourceId = source.userId ?? source.groupId ?? source.roomId;
61
61
  const sourceType = source.type;
62
62
  if (sourceId === void 0 || sourceId.length === 0) return void 0;
@@ -84,6 +84,15 @@ function lineEventToMessageEvent(event) {
84
84
  };
85
85
  }
86
86
 
87
+ // src/refuse-attachments.ts
88
+ function refuseAttachments(out) {
89
+ if (out.attachments == null || out.attachments.length === 0) return void 0;
90
+ return {
91
+ ok: false,
92
+ error: { code: "attachments_unsupported", message: "line adapter cannot send attachments" }
93
+ };
94
+ }
95
+
87
96
  // src/reply-cache.ts
88
97
  var DEFAULT_TTL_MS = 6e4;
89
98
  var DEFAULT_CAPACITY = 1e3;
@@ -118,7 +127,9 @@ var ReplyTokenCache = class {
118
127
  }
119
128
  };
120
129
  function splitForLine(text, limit = 5e3) {
121
- return chunkByGrapheme(text, { limit });
130
+ if (text.length <= limit) return chunkByGrapheme(text, { limit });
131
+ chunkByGrapheme("", { limit });
132
+ return splitKeepingRows(text, limit);
122
133
  }
123
134
 
124
135
  // src/adapter.ts
@@ -174,8 +185,11 @@ var LineAdapter = class extends BasePlatformAdapter {
174
185
  this.inboundHandler = void 0;
175
186
  this.replyCache.clear();
176
187
  }
177
- // 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.
178
188
  async sendMessage(out) {
189
+ return refuseAttachments(out) ?? this.sendText(out);
190
+ }
191
+ // 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.
192
+ async sendText(out) {
179
193
  if (out.text.length === 0) {
180
194
  return { ok: false, error: { code: "empty_text", message: "outbound text is empty" } };
181
195
  }
@@ -311,6 +325,7 @@ var LineAdapter = class extends BasePlatformAdapter {
311
325
  * named as the handler's failure rather than the platform's, and delivery continues.
312
326
  */
313
327
  async deliver(event) {
328
+ if (!this.passesMentionGuard(event)) return "ok";
314
329
  return this.runHandler(this.inboundHandler, event);
315
330
  }
316
331
  };
@@ -340,6 +355,13 @@ function mapLineError(err) {
340
355
  }
341
356
  };
342
357
  }
358
+
359
+ // src/envelope.ts
360
+ function isEnvelope(payload) {
361
+ if (typeof payload !== "object" || payload === null) return false;
362
+ const events = payload.events;
363
+ return Array.isArray(events) && events.every((event) => typeof event === "object" && event !== null);
364
+ }
343
365
  function computeLineSignature(channelSecret, rawBody) {
344
366
  return crypto.createHmac("sha256", channelSecret).update(rawBody, "utf8").digest("base64");
345
367
  }
@@ -396,11 +418,6 @@ function headerValue(headers, name) {
396
418
  }
397
419
  return void 0;
398
420
  }
399
- function isEnvelope(payload) {
400
- if (typeof payload !== "object" || payload === null) return false;
401
- const events = payload.events;
402
- return Array.isArray(events) && events.every((event) => typeof event === "object" && event !== null);
403
- }
404
421
  var CONFIG = [
405
422
  {
406
423
  key: "channelSecret",
@@ -472,8 +489,8 @@ function handlerFactory(adapter) {
472
489
  res.status(400).type("text/plain").send("invalid JSON body");
473
490
  return;
474
491
  }
475
- if (!Array.isArray(envelope.events)) {
476
- res.status(400).type("text/plain").send("missing 'events' array");
492
+ if (!isEnvelope(envelope)) {
493
+ res.status(400).type("text/plain").send("missing 'events' array of objects");
477
494
  return;
478
495
  }
479
496
  void adapter.dispatchWebhookBody(envelope).catch((err) => {
@@ -493,10 +510,25 @@ async function createWebhookServer(opts) {
493
510
  const createApp = await loadExpress();
494
511
  const app = opts.app ?? createApp();
495
512
  const path = opts.path ?? "/line";
496
- app.post(path, rawBodyCapture("gateway-line"), handlerFactory(opts.adapter));
513
+ app.post(
514
+ path,
515
+ rawBodyCapture("gateway-line", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),
516
+ handlerFactory(opts.adapter)
517
+ );
497
518
  return listenerLifecycle({ app, port: opts.port ?? 3e3, injected: opts.app !== void 0 });
498
519
  }
499
520
 
500
- export { ConfigurationError, LineAdapter, ReplyTokenCache, SDKNotInstalledError, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, mapSourceType, splitForLine, verifyLineSignature };
521
+ // src/webhook-verifier.ts
522
+ function lineWebhookVerifier(source) {
523
+ return async (request) => {
524
+ const rawBody = await request.text();
525
+ const signature = request.headers.get("x-line-signature") ?? void 0;
526
+ if (signature === void 0) return { ok: false, reason: "missing x-line-signature header" };
527
+ const secret = typeof source === "string" ? source : source.getChannelSecret();
528
+ return verifyLineSignature(secret, rawBody, signature) ? { ok: true } : { ok: false, reason: "signature mismatch" };
529
+ };
530
+ }
531
+
532
+ export { ConfigurationError, LineAdapter, ReplyTokenCache, SDKNotInstalledError, computeLineSignature, createWebhookServer, lineChannel, lineEventToMessageEvent, lineWebhookVerifier, mapSourceType, splitForLine, verifyLineSignature };
501
533
  //# sourceMappingURL=index.js.map
502
534
  //# sourceMappingURL=index.js.map
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","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IAAA,IAAQ,OAAA;AAC1B,EAAA,GAAA,CAAI,IAAA,CAAK,MAAM,cAAA,CAAe,cAAc,GAAG,cAAA,CAAe,IAAA,CAAK,OAAO,CAAC,CAAA;AAK3E,EAAA,OAAO,iBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F","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 AFTER signature validation. Iterates LINE's batch envelope and\n * dispatches each event.\n *\n * Answers `\"no_handler\"`, dispatching nothing and caching no reply token, when the batch holds an\n * event the handler would receive (a text message that passes the mention guard) and no handler\n * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired\n * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not\n * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's\n * console verification, or only follow and media events) answers `\"ok\"` either way. The handler is\n * read once per batch, so one that unsubscribes while handling an event still gets the rest.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<\"ok\" | \"no_handler\"> {\n const handler = this.inboundHandler;\n const events = envelope.events.map((ev) => ({ ev, normalized: lineEventToMessageEvent(ev) }));\n const deliverable = events.some(\n ({ normalized }) => normalized !== undefined && this.passesMentionGuard(normalized),\n );\n if (handler === undefined && deliverable) return \"no_handler\";\n for (const { ev, normalized } of events) {\n await this.dispatchSingleEvent(ev, normalized, handler);\n }\n return \"ok\";\n }\n\n private async dispatchSingleEvent(\n ev: LineWebhookEvent,\n normalized: GatewayMessageEvent | undefined,\n handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined,\n ): Promise<void> {\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 (handler === undefined) return;\n try {\n await handler(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 * `lineChannel` — the LINE channel described as data (FR-005 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { LineAdapter } from \"./adapter.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineAdapterOptions, LineWebhookEnvelope } from \"./types.js\";\n\nconst SIGNATURE_HEADER = \"x-line-signature\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-line: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\n/** A required string; an empty one is left for the adapter's own check, which names it. */\nfunction requiredString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n}\n\n/** An optional value: `undefined`, `null` and `\"\"` are absent, anything else must pass `check`. */\nfunction optional<T>(\n config: Readonly<Record<string, unknown>>,\n key: string,\n check: (value: unknown) => value is T,\n expected: string,\n): T | undefined {\n const value = config[key];\n if (value === undefined || value === null || value === \"\") return undefined;\n if (!check(value)) throw invalid(key, expected);\n return value;\n}\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction buildOptions(config: Readonly<Record<string, unknown>>): LineAdapterOptions {\n // Types are checked here, before the constructor: a numeric secret passes the constructor's\n // length check (`adapter.ts:32`) and would throw later, inside the signature HMAC, on the request\n // path. An empty secret or token is then refused by the constructor's own ConfigurationError.\n const channelSecret = requiredString(config, \"channelSecret\");\n const channelAccessToken = requiredString(config, \"channelAccessToken\");\n const botUserId = optional(config, \"botUserId\", isString, \"a string\");\n const requireMention = optional(config, \"requireMention\", isBoolean, \"a boolean\");\n return {\n channelSecret,\n channelAccessToken,\n ...(botUserId !== undefined ? { botUserId } : {}),\n ...(requireMention !== undefined ? { requireMention } : {}),\n };\n}\n\nfunction headerValue(\n headers: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) return value;\n }\n return undefined;\n}\n\n/** A LINE webhook envelope: an object whose `events` is an array of objects. */\nfunction isEnvelope(payload: unknown): payload is LineWebhookEnvelope {\n if (typeof payload !== \"object\" || payload === null) return false;\n const events = (payload as { events?: unknown }).events;\n return (\n Array.isArray(events) && events.every((event) => typeof event === \"object\" && event !== null)\n );\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"channelSecret\",\n required: true,\n secret: true,\n description: \"The channel secret that signs inbound webhooks (LINE Developers Console).\",\n },\n {\n key: \"channelAccessToken\",\n required: true,\n secret: true,\n description: \"The channel's long-lived access token (LINE Developers Console).\",\n },\n {\n key: \"botUserId\",\n required: false,\n secret: false,\n description: \"The bot's own user id; with requireMention, group messages must mention it.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"Whether group messages must mention the bot. Default true.\",\n },\n];\n\n/**\n * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to\n * `webhook.verify` and then `webhook.ingest`.\n *\n * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's\n * channel secret. `ingest` reports `\"malformed\"` for a payload with no `events` array or with an\n * event that is not an object, dispatching nothing; otherwise it dispatches through\n * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply\n * uses the reply API. A follow or other non-text event is skipped and still reports `\"delivered\"`.\n * It reports `\"no_handler\"`, dispatching nothing, when the payload holds a text message for the\n * handler and none is subscribed (before the runner started, after it stopped, or when this\n * adapter's connect failed under `connectFailure: \"isolate\"`). Only `\"delivered\"` should be\n * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered\n * otherwise.\n * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,\n * both with this package's `ConfigurationError`.\n *\n * @public\n */\nexport const lineChannel = {\n platform: \"line\" as const,\n transport: \"webhook\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): LineAdapter {\n return new LineAdapter(buildOptions(config));\n },\n webhook: {\n verify(\n adapter: LineAdapter,\n request: {\n readonly rawBody: string;\n readonly headers: Readonly<Record<string, string | undefined>>;\n },\n ): boolean {\n const signature = headerValue(request.headers, SIGNATURE_HEADER);\n return verifyLineSignature(adapter.getChannelSecret(), request.rawBody, signature);\n },\n async ingest(\n adapter: LineAdapter,\n payload: unknown,\n ): Promise<\"delivered\" | \"malformed\" | \"no_handler\"> {\n if (!isEnvelope(payload)) return \"malformed\";\n const outcome = await adapter.dispatchWebhookBody(payload);\n return outcome === \"no_handler\" ? \"no_handler\" : \"delivered\";\n },\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"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/normalize.ts","../src/refuse-attachments.ts","../src/reply-cache.ts","../src/split.ts","../src/adapter.ts","../src/envelope.ts","../src/signature.ts","../src/channel.ts","../src/webhook-server.ts","../src/webhook-verifier.ts"],"names":[],"mappings":";;;;AAsBO,IAAM,kBAAA,GAAN,cAAiC,yBAAA,CAA0B;AAAA,EAC9C,IAAA,GAAO,oBAAA;AAAA,EACzB,YAAY,IAAA,EAAiC;AAC3C,IAAA,KAAA,CAAM,gBAAgB,IAAI,CAAA;AAAA,EAC5B;AACF;AASO,IAAM,oBAAA,GAAN,cAAmC,kBAAA,CAAmB;AAAA,EAC3D,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM;AAAA,MACJ,IAAA,EAAM,mBAAA;AAAA,MACN,OAAA,EAAS,CAAA,wBAAA,EAA2B,OAAO,CAAA,+BAAA,EAAkC,OAAO,CAAA,CAAA;AAAA,MACpF,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AACF;;;ACKA,eAAsB,WAAA,GAAsC;AAC1D,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,MAAM,OAAO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,IAAA,IAAQ,OAAA;AAC1B,EAAA,GAAA,CAAI,IAAA;AAAA,IACF,IAAA;AAAA,IACA,cAAA,CAAe,cAAA,EAAgB,EAAE,QAAA,EAAU,2BAA2B,CAAA;AAAA,IACtE,cAAA,CAAe,KAAK,OAAO;AAAA,GAC7B;AAKA,EAAA,OAAO,iBAAA,CAAkB,EAAE,GAAA,EAAK,IAAA,EAAM,IAAA,CAAK,IAAA,IAAQ,GAAA,EAAM,QAAA,EAAU,IAAA,CAAK,GAAA,KAAQ,MAAA,EAAW,CAAA;AAC7F;;;ACjFO,SAAS,oBACd,MAAA,EACwD;AACxD,EAAA,OAAO,OAAO,OAAA,KAAuD;AACnE,IAAA,MAAM,OAAA,GAAU,MAAM,OAAA,CAAQ,IAAA,EAAK;AACnC,IAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,kBAAkB,CAAA,IAAK,MAAA;AAC7D,IAAA,IAAI,cAAc,MAAA,EAAW,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,QAAQ,iCAAA,EAAkC;AAC3F,IAAA,MAAM,SAAS,OAAO,MAAA,KAAW,QAAA,GAAW,MAAA,GAAS,OAAO,gBAAA,EAAiB;AAC7E,IAAA,OAAO,mBAAA,CAAoB,MAAA,EAAQ,OAAA,EAAS,SAAS,CAAA,GACjD,EAAE,EAAA,EAAI,IAAA,EAAK,GACX,EAAE,EAAA,EAAI,KAAA,EAAO,QAAQ,oBAAA,EAAqB;AAAA,EAChD,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * Typed errors for `@theokit/gateway-line`.\n *\n * `ConfigurationError` extends the shared core `GatewayConfigurationError`\n * base (roadmap M2) — only the package prefix is package-specific. Name,\n * message shape, `code`/`detail` fields, and `instanceof` are byte-identical\n * to the previous hand-rolled class (pinned by `tests/errors.test.ts`).\n */\n\nimport { GatewayConfigurationError, type GatewayConfigurationErrorOptions } from \"@theokit/gateway\";\n\n/** @knipignore — public input shape for `ConfigurationError` constructor (caller-extensible). */\nexport type ConfigurationErrorOptions = GatewayConfigurationErrorOptions;\n\n/**\n * Misconfiguration of this adapter, raised before any network call.\n *\n * Extends the shared core base so every gateway package reports configuration faults in one shape:\n * a structured `code` the caller can branch on, tagged with `\"gateway-line\"` as the origin. A\n * missing credential or an unsupported option is a programmer error, not a transient failure —\n * these are never retried.\n */\nexport class ConfigurationError extends GatewayConfigurationError {\n override readonly name = \"ConfigurationError\";\n constructor(opts: ConfigurationErrorOptions) {\n super(\"gateway-line\", opts);\n }\n}\n\n/**\n * The platform SDK this adapter needs is declared as a peer dependency and is not installed.\n *\n * Raised at connect time rather than at import, so a project that installs several gateway packages\n * only pays for the SDKs of the ones it actually starts. The message names the exact package and\n * the command that installs it.\n */\nexport class SDKNotInstalledError extends ConfigurationError {\n constructor(pkgName: string) {\n super({\n code: \"sdk_not_installed\",\n message: `gateway-line: peer-dep \"${pkgName}\" not installed. Run: pnpm add ${pkgName}`,\n detail: pkgName,\n });\n }\n}\n","/**\n * Lazy `@line/bot-sdk` loader + thin Client wrapper for sending.\n */\n\nimport { SDKNotInstalledError } from \"./errors.js\";\n\nexport interface LineSdkClient {\n replyMessage(\n replyToken: string,\n messages: Array<{ type: \"text\"; text: string }>,\n ): Promise<unknown>;\n pushMessage(to: string, messages: Array<{ type: \"text\"; text: string }>): Promise<unknown>;\n /**\n * `GET /v2/bot/info` — the cheapest call that makes LINE judge the token.\n *\n * `connect()` needs it because building a client performs no I/O at all: it\n * would otherwise report success for any string, and the operator would find\n * out at the first send. Telegram, Discord, Slack and Mattermost all surface a\n * bad credential from connect(); Matrix did not until 2026-08-17, and this was\n * the second adapter with the same gap.\n */\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n}\n\n/**\n * The v9 `MessagingApiClient` surface, as declared by the installed\n * `@line/bot-sdk` v9 `messagingApiClient.d.ts`. Both methods take ONE request\n * object — this is not the same shape as {@link LineSdkClient}, and conflating\n * the two is what broke every outbound message before 2026-08-17.\n */\ninterface LineV9Client {\n getBotInfo(): Promise<{ userId?: string; displayName?: string }>;\n replyMessage(request: {\n replyToken: string;\n messages: Array<{ type: \"text\"; text: string }>;\n }): Promise<unknown>;\n pushMessage(\n request: { to: string; messages: Array<{ type: \"text\"; text: string }> },\n xLineRetryKey?: string,\n ): Promise<unknown>;\n}\n\ninterface LineSdkModule {\n Client: new (cfg: { channelAccessToken: string; channelSecret?: string }) => LineSdkClient;\n messagingApi?: {\n MessagingApiClient: new (cfg: { channelAccessToken: string }) => LineV9Client;\n };\n}\n\nexport async function loadLineSdk(): Promise<LineSdkModule> {\n try {\n const mod = await import(\"@line/bot-sdk\");\n return mod as unknown as LineSdkModule;\n } catch {\n throw new SDKNotInstalledError(\"@line/bot-sdk\");\n }\n}\n\n/**\n * Build a client exposing the positional {@link LineSdkClient} shape the adapter\n * calls, from either the legacy (`Client`) or the v9\n * (`messagingApi.MessagingApiClient`) SDK.\n *\n * The v9 client is WRAPPED, not returned directly. An earlier version returned\n * it as-is on the claim that \"v9 SDK exposes both styles\" — it does not. v9\n * declares `replyMessage(request)` and `pushMessage(request, retryKey?)`, each\n * taking a single object, so the adapter's positional call arrived as\n * `{replyToken: undefined, messages: undefined}` and LINE rejected every send\n * with a 400. Since `@line/bot-sdk` is pinned at `^9.0.0`, this branch is the\n * one that always runs: the bug was total, not conditional.\n */\nexport function makeClient(\n mod: LineSdkModule,\n cfg: { channelAccessToken: string; channelSecret: string },\n): LineSdkClient {\n const v9 = mod.messagingApi?.MessagingApiClient;\n if (v9 !== undefined) {\n const client = new v9({ channelAccessToken: cfg.channelAccessToken });\n return {\n async replyMessage(replyToken, messages) {\n return client.replyMessage({ replyToken, messages });\n },\n async pushMessage(to, messages) {\n return client.pushMessage({ to, messages });\n },\n async getBotInfo() {\n return client.getBotInfo();\n },\n };\n }\n return new mod.Client(cfg);\n}\n","/**\n * Inbound normalization: LINE webhook event → LineMessageEvent.\n *\n * EC-4 absorbed: LINE webhook delivers 9 event types. Only `message`\n * events of `text` type are dispatched in v0.1; other types (`follow`,\n * `unfollow`, `postback`, image/audio/sticker messages, etc.) return\n * `undefined` so `adapter.dispatchEvent` skips them silently.\n *\n * D410: source.type mapping `user` → `dm`; `group`/`room` → `group`.\n */\n\nimport type { LineMessageEvent } from \"@theokit/gateway\";\n\nimport type { LineWebhookEvent } from \"./types.js\";\n\nexport function mapSourceType(sourceType: string): \"dm\" | \"group\" | \"thread\" {\n if (sourceType === \"user\") return \"dm\";\n return \"group\";\n}\n\n/**\n * Turn one LINE webhook event into a `LineMessageEvent`, or `undefined` when it is not a text\n * message.\n *\n * A LINE delivery carries a batch of heterogeneous events — follows, joins, stickers, images.\n * Returning `undefined` for the ones this adapter does not handle is the normal path, not an error.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: EC-4 event-type filter + source-shape narrowing + mentionee extraction are intentionally co-located so the dispatch contract stays linear.\nexport function lineEventToMessageEvent(event: LineWebhookEvent): LineMessageEvent | undefined {\n // EC-4: filter at the top — non-message events have undefined fields downstream.\n if (event.type !== \"message\") return undefined;\n if (event.message == null) return undefined;\n if (event.message.type !== \"text\") return undefined;\n\n const source = event.source;\n if (source == null) 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 * The refusal this adapter answers for an outbound that carries attachments (B-674).\n *\n * This adapter sends text only, so an outbound carrying attachments is refused rather than sent without its images.\n *\n * The check runs before any other, so a refusal makes no platform call. It lives in this package\n * rather than in `@theokit/gateway` so that the adapter calls nothing its declared core floor\n * lacks; only the `OutboundMessage` type is imported.\n */\n\nimport type { OutboundMessage, SendResult } from \"@theokit/gateway\";\n\n/**\n * `attachments_unsupported` when `out` carries attachments, otherwise `undefined`.\n *\n * Absent, `null` and an empty list carry nothing. `!== 0`, not `> 0`: any other non-array value\n * from a JavaScript caller has no numeric length and is refused rather than taken for an empty\n * list (EC-1).\n */\nexport function refuseAttachments(out: OutboundMessage): SendResult | undefined {\n if (out.attachments == null || out.attachments.length === 0) return undefined;\n return {\n ok: false,\n error: { code: \"attachments_unsupported\", message: \"line adapter cannot send attachments\" },\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), keeping table rows whole.\n *\n * LINE limits text messages to 5000 chars. A text within the limit goes through core\n * `chunkByGrapheme` as before. A longer one is cut at the last grapheme boundary within each part,\n * which is where `chunkByGrapheme`'s greedy walk ends a part, so emoji, regional indicators and\n * combining sequences are never severed and text with no table row splits exactly as it did\n * (pinned by `tests/split-no-table-baseline.test.ts` and the equivalence test in\n * `tests/split-tables.test.ts`).\n *\n * A cut that falls inside a Markdown table row which fits in a part moves back to the start of\n * that row, so the row arrives whole in the next message (B-556). The rule is core\n * `splitKeepingRows`, shared with gateway-sms.\n */\n\nimport { chunkByGrapheme, splitKeepingRows } from \"@theokit/gateway\";\n\nexport function splitForLine(text: string, limit = 5000): string[] {\n if (text.length <= limit) return chunkByGrapheme(text, { limit });\n // The core's RangeError for a limit of 0, 1.5 or NaN, with the message it had before.\n chunkByGrapheme(\"\", { limit });\n return splitKeepingRows(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 { refuseAttachments } from \"./refuse-attachments.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 async sendMessage(out: OutboundMessage): Promise<SendResult> {\n return refuseAttachments(out) ?? this.sendText(out);\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 private async sendText(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 AFTER signature validation. Iterates LINE's batch envelope and\n * dispatches each event.\n *\n * Answers `\"no_handler\"`, dispatching nothing and caching no reply token, when the batch holds an\n * event the handler would receive (a text message that passes the mention guard) and no handler\n * is subscribed: before `onInbound`, after `disconnect()`, or for an adapter a runner never wired\n * because its connect failed. A webhook route must not acknowledge that answer, or LINE does not\n * redeliver and the message is lost. A batch with nothing to deliver (an empty `events`, LINE's\n * console verification, or only follow and media events) answers `\"ok\"` either way. The handler is\n * read once per batch, so one that unsubscribes while handling an event still gets the rest.\n */\n async dispatchWebhookBody(envelope: LineWebhookEnvelope): Promise<\"ok\" | \"no_handler\"> {\n const handler = this.inboundHandler;\n const events = envelope.events.map((ev) => ({ ev, normalized: lineEventToMessageEvent(ev) }));\n const deliverable = events.some(\n ({ normalized }) => normalized !== undefined && this.passesMentionGuard(normalized),\n );\n if (handler === undefined && deliverable) return \"no_handler\";\n for (const { ev, normalized } of events) {\n await this.dispatchSingleEvent(ev, normalized, handler);\n }\n return \"ok\";\n }\n\n private async dispatchSingleEvent(\n ev: LineWebhookEvent,\n normalized: GatewayMessageEvent | undefined,\n handler: ((event: GatewayMessageEvent) => Promise<void>) | undefined,\n ): Promise<void> {\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 (handler === undefined) return;\n try {\n await handler(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 // The webhook path applies the same guard (D409); a dropped event is acknowledged, not delivered.\n if (!this.passesMentionGuard(event)) return \"ok\";\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","import type { LineWebhookEnvelope } from \"./types.js\";\n\n/** A LINE webhook envelope: an object whose `events` is an array of objects. */\nexport function isEnvelope(payload: unknown): payload is LineWebhookEnvelope {\n if (typeof payload !== \"object\" || payload === null) return false;\n const events = (payload as { events?: unknown }).events;\n return (\n Array.isArray(events) && events.every((event) => typeof event === \"object\" && event !== null)\n );\n}\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 * `lineChannel` — the LINE channel described as data (FR-005 of B-018).\n *\n * Typed locally on purpose (ADR D4 of B-018): this package declares `@theokit/gateway >=0.9.0` as\n * its peer, and a published `.d.ts` naming a core type that 0.9.0 lacks would break a consumer on\n * that floor with no gate here to catch it. The object is structurally a `ChannelDescriptor`; the\n * integration package assigns it to one, and its typecheck is where a drift between the two fails.\n */\n\nimport { LineAdapter } from \"./adapter.js\";\nimport { isEnvelope } from \"./envelope.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.js\";\nimport type { LineAdapterOptions } from \"./types.js\";\n\nconst SIGNATURE_HEADER = \"x-line-signature\";\n\nfunction invalid(key: string, expected: string): ConfigurationError {\n return new ConfigurationError({\n code: \"invalid_config\",\n message: `gateway-line: config.${key} must be ${expected}`,\n detail: key,\n });\n}\n\n/** A required string; an empty one is left for the adapter's own check, which names it. */\nfunction requiredString(config: Readonly<Record<string, unknown>>, key: string): string {\n const value = config[key];\n if (typeof value !== \"string\") throw invalid(key, \"a string\");\n return value;\n}\n\n/** An optional value: `undefined`, `null` and `\"\"` are absent, anything else must pass `check`. */\nfunction optional<T>(\n config: Readonly<Record<string, unknown>>,\n key: string,\n check: (value: unknown) => value is T,\n expected: string,\n): T | undefined {\n const value = config[key];\n if (value === undefined || value === null || value === \"\") return undefined;\n if (!check(value)) throw invalid(key, expected);\n return value;\n}\n\nconst isString = (value: unknown): value is string => typeof value === \"string\";\nconst isBoolean = (value: unknown): value is boolean => typeof value === \"boolean\";\n\nfunction buildOptions(config: Readonly<Record<string, unknown>>): LineAdapterOptions {\n // Types are checked here, before the constructor: a numeric secret passes the constructor's\n // length check (`adapter.ts:32`) and would throw later, inside the signature HMAC, on the request\n // path. An empty secret or token is then refused by the constructor's own ConfigurationError.\n const channelSecret = requiredString(config, \"channelSecret\");\n const channelAccessToken = requiredString(config, \"channelAccessToken\");\n const botUserId = optional(config, \"botUserId\", isString, \"a string\");\n const requireMention = optional(config, \"requireMention\", isBoolean, \"a boolean\");\n return {\n channelSecret,\n channelAccessToken,\n ...(botUserId !== undefined ? { botUserId } : {}),\n ...(requireMention !== undefined ? { requireMention } : {}),\n };\n}\n\nfunction headerValue(\n headers: Readonly<Record<string, string | undefined>>,\n name: string,\n): string | undefined {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === name) return value;\n }\n return undefined;\n}\n\n/** One configuration field, shaped like the core's `ChannelConfigField` (typed locally, D4). */\ninterface ConfigField {\n readonly key: string;\n readonly required: boolean;\n readonly secret: boolean;\n readonly description: string;\n}\n\nconst CONFIG: ReadonlyArray<ConfigField> = [\n {\n key: \"channelSecret\",\n required: true,\n secret: true,\n description: \"The channel secret that signs inbound webhooks (LINE Developers Console).\",\n },\n {\n key: \"channelAccessToken\",\n required: true,\n secret: true,\n description: \"The channel's long-lived access token (LINE Developers Console).\",\n },\n {\n key: \"botUserId\",\n required: false,\n secret: false,\n description: \"The bot's own user id; with requireMention, group messages must mention it.\",\n },\n {\n key: \"requireMention\",\n required: false,\n secret: false,\n description: \"Whether group messages must mention the bot. Default true.\",\n },\n];\n\n/**\n * The LINE channel: LINE delivers inbound events by webhook, so the app routes each request to\n * `webhook.verify` and then `webhook.ingest`.\n *\n * `verify` checks the `x-line-signature` header (any case) against the raw body with the adapter's\n * channel secret. `ingest` reports `\"malformed\"` for a payload with no `events` array or with an\n * event that is not an object, dispatching nothing; otherwise it dispatches through\n * `LineAdapter.dispatchWebhookBody`, which caches each event's reply token so the handler's reply\n * uses the reply API. A follow or other non-text event is skipped and still reports `\"delivered\"`.\n * It reports `\"no_handler\"`, dispatching nothing, when the payload holds a text message for the\n * handler and none is subscribed (before the runner started, after it stopped, or when this\n * adapter's connect failed under `connectFailure: \"isolate\"`). Only `\"delivered\"` should be\n * answered with 200: with webhook redelivery turned on, LINE redelivers a request answered\n * otherwise.\n * `create` refuses a field of the wrong type, and the adapter refuses an empty secret or token,\n * both with this package's `ConfigurationError`.\n *\n * @public\n */\nexport const lineChannel = {\n platform: \"line\" as const,\n transport: \"webhook\" as const,\n config: CONFIG,\n create(config: Readonly<Record<string, unknown>>): LineAdapter {\n return new LineAdapter(buildOptions(config));\n },\n webhook: {\n verify(\n adapter: LineAdapter,\n request: {\n readonly rawBody: string;\n readonly headers: Readonly<Record<string, string | undefined>>;\n },\n ): boolean {\n const signature = headerValue(request.headers, SIGNATURE_HEADER);\n return verifyLineSignature(adapter.getChannelSecret(), request.rawBody, signature);\n },\n async ingest(\n adapter: LineAdapter,\n payload: unknown,\n ): Promise<\"delivered\" | \"malformed\" | \"no_handler\"> {\n if (!isEnvelope(payload)) return \"malformed\";\n const outcome = await adapter.dispatchWebhookBody(payload);\n return outcome === \"no_handler\" ? \"no_handler\" : \"delivered\";\n },\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 {\n DEFAULT_WEBHOOK_MAX_BYTES,\n listenerLifecycle,\n loadPeer,\n rawBodyCapture,\n} from \"@theokit/gateway\";\nimport type { Express, Request, Response } from \"express\";\nimport type { LineAdapter } from \"./adapter.js\";\n\nimport { isEnvelope } from \"./envelope.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { verifyLineSignature } from \"./signature.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: unknown;\n try {\n envelope = JSON.parse(rawBody);\n } catch {\n res.status(400).type(\"text/plain\").send(\"invalid JSON body\");\n return;\n }\n if (!isEnvelope(envelope)) {\n res.status(400).type(\"text/plain\").send(\"missing 'events' array of objects\");\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(\n path,\n rawBodyCapture(\"gateway-line\", { maxBytes: DEFAULT_WEBHOOK_MAX_BYTES }),\n handlerFactory(opts.adapter),\n );\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","/**\n * The LINE half of a framework channel webhook, in the shape `theokit/server/webhook` validators\n * take: `(request) => Promise<{ ok: true } | { ok: false; reason }>`. The shape is structural, so\n * this package imports nothing from the framework.\n *\n * ```ts\n * await handleChannelWebhook(request, pathname, {\n * validators: { line: lineWebhookVerifier(adapter) },\n * })\n * ```\n *\n * @public\n */\n\nimport { verifyLineSignature } from \"./signature.js\";\n\n/** What a verifier answers. @public */\nexport type LineWebhookVerifyResult =\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: string };\n\n/**\n * Build a verifier for one channel secret (or an adapter exposing `getChannelSecret()`).\n *\n * The request body is READ as raw text, because LINE signs the exact bytes; pass a clone if the\n * body is needed afterwards.\n *\n * @public\n */\nexport function lineWebhookVerifier(\n source: string | { getChannelSecret(): string },\n): (request: Request) => Promise<LineWebhookVerifyResult> {\n return async (request: Request): Promise<LineWebhookVerifyResult> => {\n const rawBody = await request.text();\n const signature = request.headers.get(\"x-line-signature\") ?? undefined;\n if (signature === undefined) return { ok: false, reason: \"missing x-line-signature header\" };\n const secret = typeof source === \"string\" ? source : source.getChannelSecret();\n return verifyLineSignature(secret, rawBody, signature)\n ? { ok: true }\n : { ok: false, reason: \"signature mismatch\" };\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/gateway-line",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "LINE Messaging API platform adapter for @theokit/gateway. ADRs D405-D412.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -37,7 +37,7 @@
37
37
  ],
38
38
  "peerDependencies": {
39
39
  "@line/bot-sdk": "^9.0.0 || ^11.0.0",
40
- "@theokit/gateway": ">=0.9.0 <1.0.0",
40
+ "@theokit/gateway": ">=0.14.0 <1.0.0",
41
41
  "express": "^4.18.0 || ^5.0.0"
42
42
  },
43
43
  "peerDependenciesMeta": {
@@ -59,7 +59,7 @@
59
59
  "typescript": "5.9.3",
60
60
  "vitest": "^4.1.11",
61
61
  "zod": "^4.0.0",
62
- "@theokit/gateway": "0.11.0"
62
+ "@theokit/gateway": "0.17.0"
63
63
  },
64
64
  "publishConfig": {
65
65
  "access": "public",