pi-roundtable-line 0.12.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.14.0] - 2026-10-14
9
+
10
+ ### Added
11
+
12
+ - `LINE.health().webhooks.rejected.signatureForBot` counts the requests that failed the signature check and whose body names this bot's user id as its `destination`; they are still counted in `rejected.signature` as well. A scanner does not know the bot's id, so this counter rising while `accepted` stays flat means a wrong channel secret or URL. The body is read only within the existing size limit and is neither logged nor kept; before the plugin knows the bot's id the count stays zero.
13
+
14
+ ### Changed
15
+
16
+ - `WebhookHealth.rejected` has the new required field `signatureForBot`, so a caller that built a `WebhookHealth` or a `LineBridgePort` of its own must add it.
17
+ - Release in lockstep with pi-roundtable 0.14.0. The core peer range moves to `>=0.14.0 <0.15.0`.
18
+
19
+ ## [0.13.0] - 2026-10-13
20
+
21
+ ### Added
22
+
23
+ - `LINE.health()` gains `webhooks: WebhookHealth` (new type, exported): `{ accepted, rejected: { signature, destination, malformed }, lastAcceptedAt?, lastRejectedAt? }`, the counts and times of what the webhook has answered since the plugin was set up. `signature` is a missing or wrong signature (401), `destination` a signed webhook for another bot (403), `malformed` a body over the cap or not an events object (413, 400). Nothing of a request but its count is kept.
24
+
25
+ ### Changed
26
+
27
+ - `LineBridgePort.health()` returns the new `webhooks` field, so a caller that built a `LineBridgePort` of its own, to test a plugin that reads `LINE`, must add it.
28
+ - Release in lockstep with pi-roundtable 0.13.0. The core peer range moves to `>=0.13.0 <0.14.0`.
29
+
8
30
  ## [0.12.1] - 2026-10-13
9
31
 
10
32
  - Release in lockstep with pi-roundtable 0.12.1; no package-specific behavior changes. The core peer range stays `>=0.12.0 <0.13.0`.
package/README.md CHANGED
@@ -11,7 +11,7 @@ It covers intake (the credentials and token source, the webhook, the allowlist o
11
11
 
12
12
  ## Requirements
13
13
 
14
- - Bun 1.3 or later, and pi-roundtable `>=0.12.0 <0.13.0` as a peer dependency.
14
+ - Bun 1.3 or later, and pi-roundtable `>=0.14.0 <0.15.0` as a peer dependency.
15
15
  - PostgreSQL, which the host already needs.
16
16
  - An HTTP listener on the host that LINE can reach over HTTPS (the webhook URL is set in the channel's settings).
17
17
  - A Messaging API channel: its channel id and channel secret.
@@ -81,6 +81,30 @@ An event with a `webhookEventId` already stored is not stored again, so LINE's r
81
81
  The bot's user id comes from `GET /v2/bot/info` when the host starts.
82
82
  If LINE cannot be reached then, the plugin logs a warning with a code and keeps trying (at most every 30 seconds, when a webhook arrives); until it knows the id a webhook is vouched for by its signature alone.
83
83
 
84
+ ### Webhook counters
85
+
86
+ `LINE.health()` returns `{ tokensIssued, tokenFailure, webhooks }`, where `webhooks` is what the webhook has answered since the plugin was set up (it starts at zero with each process):
87
+
88
+ ```ts
89
+ webhooks: {
90
+ accepted: number; // answered 200, a Verify included
91
+ rejected: {
92
+ signature: number; // 401: the signature is missing or wrong
93
+ signatureForBot: number; // of those, the body names this bot as its destination
94
+ destination: number; // 403: signed, but for another bot
95
+ malformed: number; // 400 and 413: not a LINE events object, or over 1 MiB
96
+ };
97
+ lastAcceptedAt?: string; // ISO time; left out until there was one
98
+ lastRejectedAt?: string;
99
+ };
100
+ ```
101
+
102
+ They are counts and times only: no body, address or signature is kept, and a request adds one to a counter and nothing else.
103
+ A `405` and a `500` (the database could not store the events) are in no counter.
104
+ A host that watches for a channel whose webhook URL or secret has drifted can alarm on `rejected.signatureForBot` growing while `accepted` does not: a scanner that finds the URL does not know the bot's user id, so a request that fails its signature yet names this bot as its `destination` is far more likely LINE with a wrong channel secret (or a rotated one) than noise.
105
+ To tell, the handler reads the `destination` of a body that failed its signature, only within the 1 MiB limit, and never logs or keeps it; `signatureForBot` also counts in `signature`.
106
+ Until the plugin knows the bot's user id it cannot tell, and `signatureForBot` stays at zero.
107
+
84
108
  ## Chats and the allowlist
85
109
 
86
110
  The first event from a chat the bot has not seen records it as `pending`: its key, when it was first and last seen, and counts.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable-line",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "A LINE Messaging API transport for pi-roundtable: a signed webhook that persists events before it answers, a durable inbox worker, and an allowlist of the groups and chats it mirrors",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -33,14 +33,14 @@
33
33
  "test": "bun test"
34
34
  },
35
35
  "peerDependencies": {
36
- "pi-roundtable": ">=0.12.0 <0.13.0"
36
+ "pi-roundtable": ">=0.14.0 <0.15.0"
37
37
  },
38
38
  "devDependencies": {
39
39
  "@biomejs/biome": "2.5.15",
40
40
  "@earendil-works/pi-ai": ">=1.0.0 <2",
41
41
  "@earendil-works/pi-coding-agent": ">=1.0.0 <2",
42
42
  "@types/bun": "1.4.2",
43
- "pi-roundtable": "0.12.1",
43
+ "pi-roundtable": "0.14.0",
44
44
  "typebox": "1.3.34",
45
45
  "typescript": "7.0.2"
46
46
  }
package/src/index.ts CHANGED
@@ -52,4 +52,5 @@ export type {
52
52
  } from "./sources.ts";
53
53
  export { LineSurface } from "./surface.ts";
54
54
  export type { LineCredentials, TokenMode } from "./token.ts";
55
+ export type { WebhookHealth } from "./webhook.ts";
55
56
  export { WEBHOOK_MAX_BYTES } from "./webhook.ts";
package/src/plugin.ts CHANGED
@@ -21,7 +21,7 @@ import { RetentionSweeper } from "./retention.ts";
21
21
  import { PgSources } from "./sources.ts";
22
22
  import { LineSurface } from "./surface.ts";
23
23
  import { TokenSource } from "./token.ts";
24
- import { webhookHandler } from "./webhook.ts";
24
+ import { WebhookStats, webhookHandler } from "./webhook.ts";
25
25
 
26
26
  /**
27
27
  * The LINE transport: a webhook on the host's HTTP listener that stores every signed event before
@@ -44,6 +44,7 @@ export function line(options: LineOptions): RoundtablePlugin {
44
44
  setup: (context: PluginContext) => {
45
45
  const sql = context.database();
46
46
  const now = () => context.env.now();
47
+ const webhooks = new WebhookStats();
47
48
  const api = new LineApi({
48
49
  tokens,
49
50
  ...(options.fetch ? { fetch: options.fetch } : {}),
@@ -143,6 +144,7 @@ export function line(options: LineOptions): RoundtablePlugin {
143
144
  return {
144
145
  tokensIssued: health.issued,
145
146
  tokenFailure: health.lastFailure,
147
+ webhooks: webhooks.health(),
146
148
  };
147
149
  },
148
150
  subscribe: (handler) => {
@@ -212,6 +214,7 @@ export function line(options: LineOptions): RoundtablePlugin {
212
214
  now,
213
215
  botUserId: () => bot.current(),
214
216
  stored: () => worker.kick(),
217
+ stats: webhooks,
215
218
  }),
216
219
  },
217
220
  ],
package/src/port.ts CHANGED
@@ -3,6 +3,7 @@ import type { LineContentRequest, LineContentResult } from "./content.ts";
3
3
  import type { LineSubscriber } from "./messages.ts";
4
4
  import type { LineOutbox } from "./outbox.ts";
5
5
  import type { LineSources } from "./sources.ts";
6
+ import type { WebhookHealth } from "./webhook.ts";
6
7
 
7
8
  /** What other plugins read from this one, through the `LINE` service key. */
8
9
  export interface LineBridgePort {
@@ -12,8 +13,16 @@ export interface LineBridgePort {
12
13
  readonly outbox: LineOutbox;
13
14
  /** The bot's user id once LINE has told it, else undefined. */
14
15
  botUserId(): string | undefined;
15
- /** The token source's health: how many tokens were issued and why the last attempt failed, if it did. */
16
- health(): { tokensIssued: number; tokenFailure: string | undefined };
16
+ /**
17
+ * The plugin's health: how many tokens were issued and why the last attempt failed, if it did, and
18
+ * what the webhook has answered since the plugin was set up (`webhooks`: counts and times only,
19
+ * never a body, an address or a signature).
20
+ */
21
+ health(): {
22
+ tokensIssued: number;
23
+ tokenFailure: string | undefined;
24
+ webhooks: WebhookHealth;
25
+ };
17
26
  /**
18
27
  * Becomes the one consumer of the package: from now on each stored event of an allowed chat, the
19
28
  * `join` and `leave` of any chat that is not blocked, and an `unsend` stored while its chat was
package/src/webhook.ts CHANGED
@@ -8,6 +8,70 @@ import type { TokenSource } from "./token.ts";
8
8
  /** The most a webhook request body may hold: LINE sends far less, and anything near this is not LINE. */
9
9
  export const WEBHOOK_MAX_BYTES = 1024 * 1024;
10
10
 
11
+ /** What the webhook has answered since the plugin was set up: counts and times only, never a body, address or signature. */
12
+ export interface WebhookHealth {
13
+ /** Requests with a valid signature for this bot that were answered `200` (an empty Verify included). */
14
+ accepted: number;
15
+ /**
16
+ * Requests turned away: `signature` is a missing or wrong `x-line-signature`, `signatureForBot`
17
+ * is the part of those whose body names this bot as its `destination` (a scanner does not know
18
+ * the bot's id, so it rising while `accepted` stays flat means a wrong channel secret or URL),
19
+ * `destination` is a signed webhook for another bot, `malformed` is a body that is too large or
20
+ * not a webhook.
21
+ */
22
+ rejected: {
23
+ signature: number;
24
+ signatureForBot: number;
25
+ destination: number;
26
+ malformed: number;
27
+ };
28
+ /** When the last request was accepted, as an ISO time; left out until one was. */
29
+ lastAcceptedAt?: string;
30
+ /** When the last request was rejected, as an ISO time; left out until one was. */
31
+ lastRejectedAt?: string;
32
+ }
33
+
34
+ /** The webhook's counters: each request adds to one of them and nothing else is kept. */
35
+ export class WebhookStats {
36
+ #accepted = 0;
37
+ #rejected = {
38
+ signature: 0,
39
+ signatureForBot: 0,
40
+ destination: 0,
41
+ malformed: 0,
42
+ };
43
+ #acceptedAt: string | undefined;
44
+ #rejectedAt: string | undefined;
45
+
46
+ accept(at: Date): void {
47
+ this.#accepted++;
48
+ this.#acceptedAt = at.toISOString();
49
+ }
50
+
51
+ reject(
52
+ reason: Exclude<keyof WebhookHealth["rejected"], "signatureForBot">,
53
+ at: Date,
54
+ ): void {
55
+ this.#rejected[reason]++;
56
+ this.#rejectedAt = at.toISOString();
57
+ }
58
+
59
+ /** A refused signature; `forBot` when the body names this bot, which counts in `signatureForBot` too. */
60
+ rejectSignature(forBot: boolean, at: Date): void {
61
+ this.reject("signature", at);
62
+ if (forBot) this.#rejected.signatureForBot++;
63
+ }
64
+
65
+ health(): WebhookHealth {
66
+ return {
67
+ accepted: this.#accepted,
68
+ rejected: { ...this.#rejected },
69
+ ...(this.#acceptedAt ? { lastAcceptedAt: this.#acceptedAt } : {}),
70
+ ...(this.#rejectedAt ? { lastRejectedAt: this.#rejectedAt } : {}),
71
+ };
72
+ }
73
+ }
74
+
11
75
  export interface WebhookOptions {
12
76
  sql: SQL;
13
77
  tokens: TokenSource;
@@ -17,6 +81,8 @@ export interface WebhookOptions {
17
81
  botUserId: () => string | undefined;
18
82
  /** Called after events were stored, so the worker looks at the inbox now rather than at its next poll. */
19
83
  stored: () => void;
84
+ /** Counts what the webhook answers; the plugin reads it for `LINE.health()`. */
85
+ stats: WebhookStats;
20
86
  maxBytes?: number;
21
87
  }
22
88
 
@@ -56,22 +122,50 @@ async function readCapped(
56
122
  return body;
57
123
  }
58
124
 
125
+ /**
126
+ * The `destination` a body that failed its signature claims, only to tell a request meant for this
127
+ * bot from a scan. The body is already within the size limit; it is neither logged nor kept, and a
128
+ * body that is not JSON, or has no text `destination`, names nobody.
129
+ */
130
+ function claimedDestination(body: Uint8Array): string | undefined {
131
+ try {
132
+ const value: unknown = JSON.parse(
133
+ new TextDecoder("utf-8", { fatal: true }).decode(body),
134
+ );
135
+ if (typeof value !== "object" || value === null) return undefined;
136
+ const destination = (value as { destination?: unknown }).destination;
137
+ return typeof destination === "string" ? destination : undefined;
138
+ } catch {
139
+ return undefined;
140
+ }
141
+ }
142
+
59
143
  /**
60
144
  * LINE's webhook: the raw body is verified against `x-line-signature` before anything is parsed,
61
145
  * every event is stored in one transaction, and only then does it answer `200`. A database that
62
146
  * is down answers `500`, which makes LINE's redelivery (if the channel has it on) resend.
63
- * An empty `events` array (LINE's Verify button) is a `200` that stores nothing.
147
+ * An empty `events` array (LINE's Verify button) is a `200` that stores nothing. Each answer adds
148
+ * to `options.stats`, which keeps counts and times only.
64
149
  */
65
150
  export function webhookHandler(
66
151
  options: WebhookOptions,
67
152
  ): (request: Request) => Promise<Response> {
68
153
  const max = options.maxBytes ?? WEBHOOK_MAX_BYTES;
154
+ const { stats } = options;
69
155
  return async (request) => {
70
156
  if (request.method !== "POST") return reply(405, "Method Not Allowed");
71
157
  const body = await readCapped(request, max);
72
- if (!body) return reply(413, "Payload Too Large");
158
+ if (!body) {
159
+ stats.reject("malformed", options.now());
160
+ return reply(413, "Payload Too Large");
161
+ }
73
162
  const signature = request.headers.get("x-line-signature");
74
163
  if (!signature || !options.tokens.verifies(body, signature)) {
164
+ const bot = options.botUserId();
165
+ stats.rejectSignature(
166
+ bot !== undefined && claimedDestination(body) === bot,
167
+ options.now(),
168
+ );
75
169
  options.logger.warn("a LINE webhook was refused: bad signature");
76
170
  return reply(401, "Unauthorized");
77
171
  }
@@ -80,15 +174,20 @@ export function webhookHandler(
80
174
  parsed = await parseWebhook(body);
81
175
  } catch (error) {
82
176
  if (!(error instanceof LineError)) throw error;
177
+ stats.reject("malformed", options.now());
83
178
  options.logger.warn({ code: error.code }, "a LINE webhook was refused");
84
179
  return reply(400, "Bad Request");
85
180
  }
86
181
  const bot = options.botUserId();
87
182
  if (bot !== undefined && parsed.destination !== bot) {
183
+ stats.reject("destination", options.now());
88
184
  options.logger.warn("a LINE webhook was refused: it is for another bot");
89
185
  return reply(403, "Forbidden");
90
186
  }
91
- if (parsed.events.length === 0) return reply(200, "OK");
187
+ if (parsed.events.length === 0) {
188
+ stats.accept(options.now());
189
+ return reply(200, "OK");
190
+ }
92
191
  try {
93
192
  const result = await persistEvents(
94
193
  options.sql,
@@ -105,6 +204,7 @@ export function webhookHandler(
105
204
  );
106
205
  return reply(500, "Internal Server Error");
107
206
  }
207
+ stats.accept(options.now());
108
208
  return reply(200, "OK");
109
209
  };
110
210
  }