@dotlabo/agent-chat-relay 0.0.0-stage → 0.1.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.
@@ -0,0 +1,444 @@
1
+ // LINE のコネクター。Webhook の受信と、Messaging API での送信を担当する。
2
+
3
+ import { extname, join } from "node:path"
4
+ import { localId } from "../core/access.ts"
5
+ import { schedulePrune } from "../core/retention.ts"
6
+ import { MAX_IMAGE_BYTES, MediaStore } from "./line-media.ts"
7
+ import { acknowledger, assertNumericId, parsePermissionData, permissionData, remember, saveDownload, splitText, truncate, verdictText } from "./common.ts"
8
+ import { ApiClient, ApiError, jsonError, verifySignature } from "./http.ts"
9
+ import type { Attachment, Capabilities, Connector, ConnectorDeps, Log, Relay, Routes } from "../core/relay.ts"
10
+
11
+ const SERVICE = "line"
12
+ const REPLY_TOKEN_TTL_MS = 50 * 1000 // Reply トークンの有効期限は 1 分。余裕を見て 50 秒
13
+ const MAX_BUBBLES = 5 // 1 回の送信に入れられるメッセージの数(本文の吹き出しと画像を合わせて)
14
+ const MAX_BUBBLE_UNITS = 5000 // 吹き出し 1 つの最大文字数(UTF-16 の単位)
15
+ const MEDIA_TEXT = { image: "(画像)", video: "(動画)", audio: "(音声)" }
16
+ // 公開 URL に使うホスト名(Webhook の Host ヘッダー)の形。ヘッダーの値をそのまま URL に入れるので絞る
17
+ const HOST_RE = /^[A-Za-z0-9.-]{1,253}(:[0-9]{1,5})?$/
18
+
19
+ type Source = { type: "user" | "group" | "room"; userId?: string; groupId?: string; roomId?: string }
20
+ /** type は user(人)か all(全員)。userId は、その人がプロフィールの取得に同意しているときだけある */
21
+ type Mentionee = { index: number; length: number; type?: string; userId?: string; isSelf?: boolean }
22
+ type LineEvent = {
23
+ type: string
24
+ webhookEventId?: string
25
+ timestamp: number
26
+ replyToken?: string
27
+ source: Source
28
+ deliveryContext?: { isRedelivery?: boolean }
29
+ message?: {
30
+ id: string
31
+ type: string
32
+ text?: string
33
+ quoteToken?: string
34
+ /** 既読を付けるためのトークン(期限なし) */
35
+ markAsReadToken?: string
36
+ quotedMessageId?: string
37
+ mention?: { mentionees: Mentionee[] }
38
+ fileName?: string
39
+ fileSize?: number
40
+ contentProvider?: { type: string }
41
+ title?: string
42
+ address?: string
43
+ latitude?: number
44
+ longitude?: number
45
+ keywords?: string[]
46
+ }
47
+ postback?: { data: string }
48
+ }
49
+
50
+ type LineMessage = NonNullable<LineEvent["message"]>
51
+
52
+ type LineConfig = {
53
+ channelSecret: string
54
+ channelToken: string
55
+ apiBase?: string
56
+ dataApiBase?: string
57
+ /** 返す画像を公開する場所(ADR 0005)。ないと画像を送れない */
58
+ media?: MediaStore
59
+ /** 画像を公開する URL の先頭(例:https://example.com)。なければ、署名を確認した Webhook が届いたホスト名を使う */
60
+ publicUrl?: string
61
+ }
62
+
63
+ /** チャネルシークレットとアクセストークンがあれば、コネクターを作る */
64
+ export function lineFromEnv(env: Record<string, string | undefined>, deps: ConnectorDeps): LineConnector | undefined {
65
+ const channelSecret = env.RELAY_LINE_CHANNEL_SECRET
66
+ const channelToken = env.RELAY_LINE_CHANNEL_TOKEN
67
+ if (!channelSecret || !channelToken) return undefined
68
+ return new LineConnector(
69
+ {
70
+ channelSecret,
71
+ channelToken,
72
+ apiBase: env.RELAY_LINE_API_BASE,
73
+ dataApiBase: env.RELAY_LINE_DATA_API_BASE,
74
+ // 返す画像の公開場所。作業ディレクトリの外に置き、reply の files で送れる範囲(ADR 0009)や作業物と混ざらないようにする
75
+ media: new MediaStore(join(deps.home, "media")),
76
+ publicUrl: env.RELAY_PUBLIC_URL,
77
+ },
78
+ deps.relay,
79
+ deps.log,
80
+ )
81
+ }
82
+
83
+ export class LineConnector implements Connector {
84
+ readonly service = SERVICE
85
+ readonly label = "LINE"
86
+ readonly capabilities: Capabilities = {
87
+ // 1 回の送信に入る吹き出しは 5 つ。本文に 1 つ残す
88
+ files: { kinds: "JPEG と PNG の画像", maxBytes: MAX_IMAGE_BYTES, maxCount: MAX_BUBBLES - 1 },
89
+ // 分けた本文も 1 回の送信に入れるので、通数は増えない。画像を添えると、分けられる数はその分減る
90
+ text: { max: MAX_BUBBLE_UNITS, parts: MAX_BUBBLES },
91
+ }
92
+ readonly routes: Routes
93
+ private readonly api: ApiClient
94
+ private readonly dataApi: ApiClient
95
+ private readonly tokens = new Map<string, { token: string; at: number }[]>()
96
+ private readonly quoteTokens = new Map<string, string>()
97
+ private readonly sentIds = new Set<string>()
98
+ /** 受けた発言の送信者。引用元が送信者以外の発言かを確かめる(ADR 0028) */
99
+ private readonly senders = new Map<string, string>()
100
+ private readonly seenEvents = new Set<string>()
101
+ private readonly names = new Map<string, string>()
102
+ /** ファイルの元の名前。取得したファイルの拡張子に使う */
103
+ private readonly fileNames = new Map<string, string>()
104
+ /** 動画と音声の発言。取得の前に、LINE 側の変換が済んだかを確かめる */
105
+ private readonly transcoding = new Map<string, true>()
106
+ private publicBase?: string
107
+ private stopPrune?: () => void
108
+ private readonly acknowledge: ReturnType<typeof acknowledger>
109
+
110
+ constructor(
111
+ private readonly cfg: LineConfig,
112
+ private readonly relay: Relay,
113
+ private readonly log: Log,
114
+ private readonly now: () => number = Date.now,
115
+ ) {
116
+ const client = (base: string) =>
117
+ new ApiClient({
118
+ label: this.label,
119
+ base,
120
+ auth: () => ({ Authorization: `Bearer ${cfg.channelToken}` }),
121
+ errorMessage: (raw) => jsonError(raw, (b) => b.message),
122
+ })
123
+ this.api = client(cfg.apiBase ?? "https://api.line.me")
124
+ this.dataApi = client(cfg.dataApiBase ?? cfg.apiBase ?? "https://api-data.line.me")
125
+ this.publicBase = cfg.publicUrl?.replace(/\/$/, "")
126
+ this.acknowledge = acknowledger(log, this.label)
127
+ const media = cfg.media
128
+ this.routes = {
129
+ "/line/webhook": { POST: (req) => this.handleWebhook(req) },
130
+ // 返した画像(ADR 0005)。トンネルで外へ公開される
131
+ ...(media ? { "/media/:name": { GET: (req) => media.serve(req.params.name ?? "") } } : {}),
132
+ }
133
+ }
134
+
135
+ /** Webhook はエンドポイントで受けるので、ここでは返した画像の定期削除だけを始める(ADR 0005) */
136
+ async start(): Promise<void> {
137
+ if (this.cfg.media) this.stopPrune = schedulePrune(this.cfg.media.dir, "公開した画像", this.log)
138
+ }
139
+
140
+ stop(): void {
141
+ this.stopPrune?.()
142
+ }
143
+
144
+ /** 署名を確認し、すぐ 200 を返す。イベントはその後で処理する */
145
+ async handleWebhook(req: Request): Promise<Response> {
146
+ const body = await req.text()
147
+ if (!verifySignature(this.cfg.channelSecret, body, req.headers.get("x-line-signature") ?? "")) {
148
+ return new Response("bad signature", { status: 401 })
149
+ }
150
+ // 署名が合えば、LINE が登録された URL へ送ってきたもの。そのホスト名で画像を公開する(Quick Tunnel は起動ごとに変わる)。
151
+ // LINE は HTTPS の URL しか受け付けないので、トンネル経由(X-Forwarded-Proto: https)のときだけ使う
152
+ const host = req.headers.get("host") ?? ""
153
+ if (!this.cfg.publicUrl && req.headers.get("x-forwarded-proto") === "https" && HOST_RE.test(host)) this.publicBase = `https://${host}`
154
+ let events: LineEvent[]
155
+ try {
156
+ events = (JSON.parse(body) as { events?: LineEvent[] }).events ?? []
157
+ } catch {
158
+ return new Response("bad request", { status: 400 })
159
+ }
160
+ queueMicrotask(() => {
161
+ for (const ev of events) {
162
+ this.handleEvent(ev).catch((err) => this.log.error("LINE のイベントの処理に失敗しました", { error: String(err) }))
163
+ }
164
+ })
165
+ return new Response("ok")
166
+ }
167
+
168
+ async handleEvent(ev: LineEvent): Promise<void> {
169
+ if (ev.webhookEventId) {
170
+ if (this.seenEvents.has(ev.webhookEventId)) return
171
+ remember(this.seenEvents, ev.webhookEventId)
172
+ }
173
+ const room = roomOf(ev.source)
174
+ if (!room) return
175
+ if (ev.replyToken && !ev.deliveryContext?.isRedelivery) this.addToken(room, ev.replyToken)
176
+ const sender = ev.source.userId ? `${SERVICE}:${ev.source.userId}` : undefined
177
+
178
+ if (ev.type === "join") {
179
+ this.relay.joined(room)
180
+ return
181
+ }
182
+ if (ev.type === "postback") {
183
+ const p = parsePermissionData(ev.postback?.data ?? "")
184
+ if (!p || !sender) return
185
+ const ok = this.relay.answer(sender, p.id, p.verdict)
186
+ try {
187
+ await this.notice(room, verdictText(ok, p.verdict))
188
+ } finally {
189
+ if (ok) this.relay.remindPending(sender)
190
+ }
191
+ return
192
+ }
193
+ const msg = ev.message
194
+ if (ev.type !== "message" || !msg || !sender) return
195
+ const isDM = ev.source.type === "user"
196
+ if (msg.quoteToken) remember(this.quoteTokens, msg.id, msg.quoteToken)
197
+ remember(this.senders, msg.id, sender)
198
+
199
+ const content = this.content(msg, sender)
200
+ if (!content) return
201
+ const result = this.relay.receive({
202
+ id: msg.id,
203
+ room,
204
+ sender,
205
+ senderName: await this.memberName(ev.source).catch(() => undefined),
206
+ text: content.text,
207
+ ts: ev.timestamp,
208
+ attachments: content.attachments,
209
+ isDM,
210
+ mentioned: isDM || content.mentioned,
211
+ toOthers: content.toOthers,
212
+ })
213
+ if (result.acknowledge) this.acknowledge(() => this.acknowledgeMessage(msg.markAsReadToken, isDM ? localId(sender) : undefined))
214
+ }
215
+
216
+ /** 発言の本文・添付と、Bot へのメンションか、他人宛ての印があるか。扱わない種類なら undefined */
217
+ private content(msg: LineMessage, sender: string): { text: string; attachments: Attachment[]; mentioned: boolean; toOthers?: boolean } | undefined {
218
+ switch (msg.type) {
219
+ case "text": {
220
+ const mentionees = msg.mention?.mentionees ?? []
221
+ return {
222
+ text: stripSelfMentions(msg.text ?? "", mentionees),
223
+ attachments: [],
224
+ mentioned: mentionees.some((m) => m.isSelf) || this.quotesMe(msg),
225
+ toOthers: mentionsOthers(mentionees, sender) || this.quotesOthers(msg, sender),
226
+ }
227
+ }
228
+ case "image":
229
+ case "video":
230
+ case "audio":
231
+ // 外部の URL にあるもの(contentProvider が line 以外)は、LINE から取得できない
232
+ if (msg.contentProvider?.type !== "line") return undefined
233
+ if (msg.type !== "image") remember(this.transcoding, msg.id, true)
234
+ return { text: MEDIA_TEXT[msg.type], attachments: [{ name: `${msg.type}-${msg.id}`, type: msg.type }], mentioned: false }
235
+ case "file":
236
+ if (msg.fileName) remember(this.fileNames, msg.id, msg.fileName)
237
+ return { text: "(ファイル)", attachments: [{ name: msg.fileName ?? `file-${msg.id}`, type: "file", size: msg.fileSize }], mentioned: false }
238
+ case "location":
239
+ return { text: `(位置情報)${[msg.title, msg.address].filter(Boolean).join(" ")} (${msg.latitude}, ${msg.longitude})`, attachments: [], mentioned: false }
240
+ case "sticker": {
241
+ // text はメッセージスタンプに入力した文字。キーワードは最大 15 個あるので、先頭だけを書く
242
+ const label = msg.text || (msg.keywords ?? []).slice(0, 5).join("、")
243
+ return { text: label ? `(スタンプ:${label})` : "(スタンプ)", attachments: [], mentioned: this.quotesMe(msg), toOthers: this.quotesOthers(msg, sender) }
244
+ }
245
+ default:
246
+ return undefined
247
+ }
248
+ }
249
+
250
+ /** Bot の発言への返信か(メンションとして扱う) */
251
+ private quotesMe(msg: LineMessage): boolean {
252
+ return msg.quotedMessageId !== undefined && this.sentIds.has(msg.quotedMessageId)
253
+ }
254
+
255
+ /** 送信者以外の人の発言への返信か。引用元を受けていなければ、分からないので false(再起動の前の発言など) */
256
+ private quotesOthers(msg: LineMessage, sender: string): boolean {
257
+ const quoted = this.senders.get(msg.quotedMessageId ?? "")
258
+ return quoted !== undefined && quoted !== sender
259
+ }
260
+
261
+ /** 受け取りの合図(ADR 0012)。既読は、OAM の[チャット]がオンでないと API で付けられない */
262
+ private async acknowledgeMessage(markAsReadToken: string | undefined, dmUser: string | undefined): Promise<void> {
263
+ await Promise.all([
264
+ markAsReadToken ? this.post("/v2/bot/chat/markAsRead", { markAsReadToken }) : undefined,
265
+ dmUser ? this.post("/v2/bot/chat/loading/start", { chatId: dmUser, loadingSeconds: 60 }) : undefined,
266
+ ])
267
+ }
268
+
269
+ async send(room: string, text: string, opts?: { replyTo?: string; files?: string[] }): Promise<string[]> {
270
+ const files = opts?.files ?? []
271
+ // 画像を先に公開する。送れないものがあれば、何も送らずにエラーを返す
272
+ const images = await Promise.all(files.map((f) => this.publish(f)))
273
+ const bubbles = splitText(text, this.capabilities.text.max, this.capabilities.text.parts - images.length)
274
+ if (bubbles.length === 0 && images.length === 0) throw new Error("本文が空です")
275
+ const quoteToken = opts?.replyTo ? this.quoteTokens.get(opts.replyTo) : undefined
276
+ const messages: object[] = bubbles.map((t, i) => ({ type: "text", text: t, ...(i === 0 && quoteToken ? { quoteToken } : {}) }))
277
+ for (const img of images) messages.push({ type: "image", originalContentUrl: img.original, previewImageUrl: img.preview })
278
+ return this.deliver(room, messages)
279
+ }
280
+
281
+ private async publish(path: string): Promise<{ original: string; preview: string }> {
282
+ if (!this.cfg.media) throw new Error("画像を送る設定がありません")
283
+ if (!this.publicBase) throw new Error("画像を公開する URL が分からないため、送れません。Webhook が一度届くか、RELAY_PUBLIC_URL を設定すると送れます")
284
+ const { original, preview } = await this.cfg.media.publish(path)
285
+ return { original: `${this.publicBase}/media/${original}`, preview: `${this.publicBase}/media/${preview}` }
286
+ }
287
+
288
+ async sendApproval(user: string, text: string, requestId: string, opts?: { always?: boolean }): Promise<void> {
289
+ // 承認者の DM へ Push で送る。ボタンでも、yes/no の文字でも答えられる
290
+ const items = [
291
+ { label: "許可", data: permissionData("allow", requestId) },
292
+ ...(opts?.always ? [{ label: "常に許可", data: permissionData("always", requestId) }] : []),
293
+ { label: "拒否", data: permissionData("deny", requestId) },
294
+ ].map((b) => ({ type: "action", action: { type: "postback", label: b.label, data: b.data, displayText: b.label } }))
295
+ await this.post("/v2/bot/message/push", {
296
+ to: localId(user),
297
+ messages: [{ type: "text", text: truncate(text, this.capabilities.text.max), quickReply: { items } }],
298
+ })
299
+ }
300
+
301
+ async notice(room: string, text: string, opts: { push?: boolean } = {}): Promise<boolean> {
302
+ const messages = [{ type: "text", text }]
303
+ // Push が許されても、使うのは 1 対 1 のトークだけ。グループと複数人トークでは、人数分の通数になる(ADR 0024)
304
+ if (opts.push && localId(room).startsWith("U")) {
305
+ await this.deliver(room, messages)
306
+ return true
307
+ }
308
+ // それ以外の案内は Reply でだけ送り、Push の通数を使わない
309
+ const token = this.takeToken(room)
310
+ if (!token) return false
311
+ await this.post("/v2/bot/message/reply", { replyToken: token, messages })
312
+ return true
313
+ }
314
+
315
+ async download(_room: string, messageId: string, dir: string): Promise<string[]> {
316
+ assertNumericId(messageId)
317
+ if (this.transcoding.has(messageId)) {
318
+ const { status } = (await this.dataApi.call("GET", `/v2/bot/message/${messageId}/content/transcoding`)) as { status: string }
319
+ if (status === "processing") throw new Error("LINE で動画・音声を準備しているところです。しばらくしてから取得してください")
320
+ if (status !== "succeeded") throw new Error("LINE で動画・音声の準備に失敗したため、取得できません")
321
+ }
322
+ const res = await this.dataApi.download(`/v2/bot/message/${messageId}/content`, "first")
323
+ // 元の名前の拡張子が使えなければ(記号だけなど)、Content-Type から決める
324
+ const named = extname(this.fileNames.get(messageId) ?? "").replace(/[^.a-zA-Z0-9]/g, "")
325
+ const ext = named.length > 1 ? named : extension(res.headers.get("content-type") ?? "")
326
+ return [await saveDownload(res, dir, `${this.now()}-${messageId}`, ext)]
327
+ }
328
+
329
+ async roomName(room: string): Promise<string | undefined> {
330
+ const id = localId(room)
331
+ if (!id.startsWith("C")) return undefined
332
+ const cached = this.names.get(room)
333
+ if (cached) return cached
334
+ const name = ((await this.api.call("GET", `/v2/bot/group/${id}/summary`)) as { groupName?: string } | null)?.groupName
335
+ if (name) remember(this.names, room, name)
336
+ return name
337
+ }
338
+
339
+ private async memberName(source: Source): Promise<string | undefined> {
340
+ const user = source.userId
341
+ if (!user) return undefined
342
+ const key = `${source.groupId ?? source.roomId ?? ""}/${user}`
343
+ const cached = this.names.get(key)
344
+ if (cached) return cached
345
+ const path = source.groupId
346
+ ? `/v2/bot/group/${source.groupId}/member/${user}`
347
+ : source.roomId
348
+ ? `/v2/bot/room/${source.roomId}/member/${user}`
349
+ : `/v2/bot/profile/${user}`
350
+ const name = ((await this.api.call("GET", path)) as { displayName?: string } | null)?.displayName
351
+ if (name) remember(this.names, key, name)
352
+ return name
353
+ }
354
+
355
+ /** Reply は通数に数えないので優先する。トークンがないか無効なら Push で送る */
356
+ private async deliver(room: string, messages: object[]): Promise<string[]> {
357
+ const token = this.takeToken(room)
358
+ let res: unknown
359
+ // 応答の本文がなくても(null)、Reply で届いていれば Push しない(二重に届き、通数も使う)
360
+ let delivered = false
361
+ if (token) {
362
+ try {
363
+ res = await this.post("/v2/bot/message/reply", { replyToken: token, messages })
364
+ delivered = true
365
+ } catch (err) {
366
+ // 期限切れなどで使えない Reply トークンなら、Push に回す
367
+ if (!(err instanceof ApiError && err.status === 400 && /reply token/i.test(err.apiMessage))) throw err
368
+ }
369
+ }
370
+ if (!delivered) {
371
+ res = await this.post("/v2/bot/message/push", { to: localId(room), messages }).catch((err) => {
372
+ if (err instanceof ApiError && err.status === 429 && /monthly limit/i.test(err.apiMessage)) {
373
+ throw new Error("LINE の今月の送信数の上限に達したため、送れませんでした。次に発言があれば、その返事として送れます")
374
+ }
375
+ throw err
376
+ })
377
+ }
378
+ return ((res as { sentMessages?: { id: string; quoteToken?: string }[] } | null)?.sentMessages ?? []).map((s) => {
379
+ remember(this.sentIds, s.id)
380
+ if (s.quoteToken) remember(this.quoteTokens, s.id, s.quoteToken)
381
+ return s.id
382
+ })
383
+ }
384
+
385
+ private liveTokens(room: string): { token: string; at: number }[] {
386
+ return (this.tokens.get(room) ?? []).filter((t) => this.now() - t.at < REPLY_TOKEN_TTL_MS)
387
+ }
388
+
389
+ private addToken(room: string, token: string): void {
390
+ this.tokens.set(room, [...this.liveTokens(room), { token, at: this.now() }])
391
+ }
392
+
393
+ private takeToken(room: string): string | undefined {
394
+ const list = this.liveTokens(room)
395
+ const t = list.pop()
396
+ this.tokens.set(room, list)
397
+ return t?.token
398
+ }
399
+
400
+ private post(path: string, payload: object): Promise<unknown> {
401
+ return this.api.call("POST", path, payload)
402
+ }
403
+ }
404
+
405
+ function roomOf(s: Source): string | undefined {
406
+ const id = s.type === "group" ? s.groupId : s.type === "room" ? s.roomId : s.userId
407
+ return id ? `${SERVICE}:${id}` : undefined
408
+ }
409
+
410
+ /** 送信者以外の人へのメンションがあるか(Bot を含む。Inbound.toOthers)。全員へのメンション(type が all)は含まない */
411
+ function mentionsOthers(mentionees: Mentionee[], sender: string): boolean {
412
+ return mentionees.some((m) => m.type === "user" && m.userId !== localId(sender))
413
+ }
414
+
415
+ /** 本文から Bot へのメンションを取り除く。LINE の index と length は UTF-16 の単位 */
416
+ export function stripSelfMentions(text: string, mentionees: Mentionee[]): string {
417
+ const remove = Array.from({ length: text.length }, () => false)
418
+ for (const m of mentionees) {
419
+ if (!m.isSelf || m.index < 0 || m.length <= 0 || m.index + m.length > text.length) continue
420
+ remove.fill(true, m.index, m.index + m.length)
421
+ }
422
+ // split("") は UTF-16 の単位で分ける
423
+ return text
424
+ .split("")
425
+ .filter((_, i) => !remove[i])
426
+ .join("")
427
+ .trim()
428
+ }
429
+
430
+
431
+ const EXTENSIONS: Record<string, string> = {
432
+ "image/jpeg": ".jpg",
433
+ "image/png": ".png",
434
+ "image/gif": ".gif",
435
+ "video/mp4": ".mp4",
436
+ "audio/x-m4a": ".m4a",
437
+ "audio/mp4": ".m4a",
438
+ "application/pdf": ".pdf",
439
+ "text/plain": ".txt",
440
+ }
441
+
442
+ function extension(contentType: string): string {
443
+ return EXTENSIONS[contentType.split(";")[0]!.trim()] ?? ".bin"
444
+ }
@@ -0,0 +1,240 @@
1
+ // ルームの登録・送信者の許可・ペアリング(docs/relay.md)。
2
+ // 公式の Claude Code Discord プラグインの access.json を手本にした。
3
+ // ID はすべて「サービス名:サービス内の ID」(例:line:C0123…)で持つ。
4
+ // 親の中にある場(Discord のスレッド)は「親の ID/子の ID」とし、親の登録を引き継ぐ(ADR 0011)。
5
+
6
+ import { randomBytes } from "node:crypto"
7
+ import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
8
+ import { dirname } from "node:path"
9
+
10
+ /**
11
+ * 受信モード(ADR 0028)。mention:メンション(Bot の発言への返信を含む)のある発言だけを渡す。
12
+ * exceptOthers:他人宛ての印があり、メンションのない発言を除いて渡す。
13
+ * exceptOthersJev:exceptOthers に加えて、Jev が他人宛てと判定した発言も除く(ADR 0029)。all:すべて渡す
14
+ */
15
+ export const RECEIVE_MODES = { mention: "メンション時", exceptOthers: "他人宛てを除く", exceptOthersJev: "他人宛てを除く(Jev)", all: "すべて" } as const
16
+ export type ReceiveMode = keyof typeof RECEIVE_MODES
17
+
18
+ export function isReceiveMode(v: unknown): v is ReceiveMode {
19
+ return (Object.keys(RECEIVE_MODES) as unknown[]).includes(v)
20
+ }
21
+
22
+ export type RoomPolicy = {
23
+ receive: ReceiveMode
24
+ /** 空なら、ルームの誰の発言でも渡す。空でなければ、この人たちの発言だけを渡す */
25
+ allowFrom: string[]
26
+ }
27
+
28
+ export type Pending = {
29
+ /** room:ルームの登録。user:DM の相手を許可リストに入れる */
30
+ kind: "room" | "user"
31
+ target: string
32
+ createdAt: number
33
+ expiresAt: number
34
+ /** コードを返した回数。2 回で打ち切る */
35
+ replies: number
36
+ }
37
+
38
+ export type Access = {
39
+ /** DM で話せる人。実行承認の依頼も、この人たちの DM へ送る */
40
+ allowFrom: string[]
41
+ rooms: Record<string, RoomPolicy>
42
+ pending: Record<string, Pending>
43
+ }
44
+
45
+ export type Inbound = {
46
+ room: string
47
+ sender: string
48
+ isDM: boolean
49
+ mentioned: boolean
50
+ /**
51
+ * 送信者以外の人への宛て(メンション、その人の発言への返信・引用)がある。全員宛ては含まない。
52
+ * Bot への宛ても含んでよい。Bot への宛てはメンションになり、メンションを優先するので、他人宛ての印として働くのは Bot 以外への宛てだけ
53
+ */
54
+ toOthers?: boolean
55
+ }
56
+
57
+ export type GateResult =
58
+ /** screen は、渡す前に、Jev で他人宛てかを判定する発言(ADR 0029) */
59
+ | { action: "deliver"; screen?: true }
60
+ /** 登録したルームの、渡さない発言。履歴には残す。toOthers は、他人宛てとして外したとき */
61
+ | { action: "record"; toOthers?: true }
62
+ | { action: "drop" }
63
+ | { action: "pair"; code: string; isResend: boolean }
64
+
65
+ const PAIRING_TTL_MS = 60 * 60 * 1000
66
+ const MAX_PENDING = 3
67
+
68
+ function emptyAccess(): Access {
69
+ return { allowFrom: [], rooms: {}, pending: {} }
70
+ }
71
+
72
+ export class AccessStore {
73
+ /** 知らない受信モードを書いたルームと、その値。同じものは続けてログに書かない */
74
+ private readonly warned = new Map<string, unknown>()
75
+
76
+ constructor(
77
+ private readonly path: string,
78
+ private readonly now: () => number = Date.now,
79
+ ) {}
80
+
81
+ /** 受信のたびに読み直すので、登録や許可の変更に再起動は不要 */
82
+ load(): Access {
83
+ let raw: string
84
+ try {
85
+ raw = readFileSync(this.path, "utf8")
86
+ } catch (err) {
87
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return emptyAccess()
88
+ throw err
89
+ }
90
+ try {
91
+ const a = JSON.parse(raw) as Partial<Access>
92
+ return { allowFrom: a.allowFrom ?? [], rooms: this.normalizeRooms(a.rooms ?? {}), pending: a.pending ?? {} }
93
+ } catch {
94
+ // 壊れたファイルは退避して、空の状態から始める。誰の発言も渡さない状態で動く(フェイルクローズ)
95
+ renameSync(this.path, `${this.path}.corrupt-${this.now()}`)
96
+ console.error(`relay: ${this.path} が壊れていたため脇へ移しました`)
97
+ return emptyAccess()
98
+ }
99
+ }
100
+
101
+ save(a: Access): void {
102
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })
103
+ const tmp = `${this.path}.tmp`
104
+ writeFileSync(tmp, JSON.stringify(a, null, 2) + "\n", { mode: 0o600 })
105
+ chmodSync(tmp, 0o600)
106
+ renameSync(tmp, this.path)
107
+ }
108
+
109
+ /** 発言をエージェントに渡すかを決める。ペアリングのコードを出すときは保存も行う */
110
+ gate(m: Inbound): GateResult {
111
+ const a = this.load()
112
+ let changed = this.pruneExpired(a)
113
+ let result: GateResult
114
+ if (m.isDM) {
115
+ result = a.allowFrom.includes(m.sender) ? { action: "deliver" } : this.pair(a, "user", m.sender)
116
+ } else {
117
+ const key = registrationOf(m.room)
118
+ const policy = a.rooms[key]
119
+ // 未登録のルームでは、Bot に話しかけられたときだけコードを返す。スレッドなら、親を登録するコードになる
120
+ if (!policy) result = m.mentioned ? this.pair(a, "room", key) : { action: "drop" }
121
+ else result = byPolicy(policy, m)
122
+ }
123
+ if (result.action === "pair") changed = true
124
+ if (changed) this.save(a)
125
+ return result
126
+ }
127
+
128
+ /** Bot がルームに追加されたとき。未登録ならコードを出す */
129
+ joined(room: string): GateResult {
130
+ const a = this.load()
131
+ this.pruneExpired(a)
132
+ const key = registrationOf(room)
133
+ if (a.rooms[key]) return { action: "drop" }
134
+ const r = this.pair(a, "room", key)
135
+ this.save(a)
136
+ return r
137
+ }
138
+
139
+ /** 管理者が端末で打ったコードを確認し、登録する。登録したものを返す */
140
+ approve(code: string): Pending {
141
+ const a = this.load()
142
+ this.pruneExpired(a)
143
+ const key = code.trim().toLowerCase()
144
+ const p = a.pending[key]
145
+ if (!p) throw new Error("コードが見つからないか、期限(1 時間)が切れています")
146
+ if (p.kind === "user") {
147
+ if (!a.allowFrom.includes(p.target)) a.allowFrom.push(p.target)
148
+ } else {
149
+ a.rooms[p.target] ??= { receive: "mention", allowFrom: [] }
150
+ }
151
+ delete a.pending[key]
152
+ this.save(a)
153
+ return p
154
+ }
155
+
156
+ /** 登録したルームの受信モードを変える */
157
+ setReceive(room: string, mode: ReceiveMode): void {
158
+ const a = this.load()
159
+ const policy = a.rooms[room]
160
+ if (!policy) throw new Error("登録していないルームです。access の一覧の番号で指定できます")
161
+ policy.receive = mode
162
+ this.save(a)
163
+ }
164
+
165
+ /**
166
+ * 受信モードを読む。古い形(requireMention)は読み替える。知らない値は「メンション時」として扱い、ログに書く。
167
+ * 保存するときは receive だけを書く
168
+ */
169
+ private normalizeRooms(rooms: Record<string, Partial<RoomPolicy> & { requireMention?: boolean }>): Record<string, RoomPolicy> {
170
+ const out: Record<string, RoomPolicy> = {}
171
+ for (const [room, { receive, requireMention, allowFrom }] of Object.entries(rooms)) {
172
+ let mode: ReceiveMode
173
+ if (isReceiveMode(receive)) mode = receive
174
+ else if (receive === undefined) mode = requireMention === false ? "all" : "mention"
175
+ else {
176
+ mode = "mention"
177
+ if (this.warned.get(room) !== receive) console.error(`relay: access.json の受信モード ${JSON.stringify(receive)} は使えません。メンション時として扱います`)
178
+ this.warned.set(room, receive)
179
+ }
180
+ out[room] = { receive: mode, allowFrom: allowFrom ?? [] }
181
+ }
182
+ return out
183
+ }
184
+
185
+ private pair(a: Access, kind: Pending["kind"], target: string): GateResult {
186
+ for (const [code, p] of Object.entries(a.pending)) {
187
+ if (p.kind !== kind || p.target !== target) continue
188
+ if (p.replies >= 2) return { action: "drop" }
189
+ p.replies++
190
+ return { action: "pair", code, isResend: true }
191
+ }
192
+ if (Object.keys(a.pending).length >= MAX_PENDING) return { action: "drop" }
193
+ const code = randomBytes(3).toString("hex")
194
+ const now = this.now()
195
+ a.pending[code] = { kind, target, createdAt: now, expiresAt: now + PAIRING_TTL_MS, replies: 1 }
196
+ return { action: "pair", code, isResend: false }
197
+ }
198
+
199
+ private pruneExpired(a: Access): boolean {
200
+ let changed = false
201
+ for (const [code, p] of Object.entries(a.pending)) {
202
+ if (p.expiresAt < this.now()) {
203
+ delete a.pending[code]
204
+ changed = true
205
+ }
206
+ }
207
+ return changed
208
+ }
209
+ }
210
+
211
+ /** 登録したルームの発言を、そのルームの設定(許可する人と受信モード)で振り分ける */
212
+ function byPolicy(policy: RoomPolicy, m: Inbound): GateResult {
213
+ if (policy.allowFrom.length > 0 && !policy.allowFrom.includes(m.sender)) return { action: "record" }
214
+ if (m.mentioned || policy.receive === "all") return { action: "deliver" }
215
+ if (policy.receive === "mention") return { action: "record" }
216
+ // 他人宛てを除くモード
217
+ if (m.toOthers) return { action: "record", toOthers: true }
218
+ return policy.receive === "exceptOthersJev" ? { action: "deliver", screen: true } : { action: "deliver" }
219
+ }
220
+
221
+ /**
222
+ * 送信先の制限:登録したルーム(と、ID が「その ID/子」のもの)と、許可した人の DM にだけ送れる。1 対 1 のトークでは、相手の ID がルームになる。
223
+ * 中核は ID の文字列しか見ない。子が本当にその親の中にあるかは、入れ子の ID を使うコネクターが送るときに確認する(Connector.nestedRooms)
224
+ */
225
+ export function canSendTo(a: Access, room: string): boolean {
226
+ return registrationOf(room) in a.rooms || a.allowFrom.includes(room)
227
+ }
228
+
229
+ /** 登録を参照するルームの ID。「親/子」(どちらも空でなく、/ は 1 つだけ)の形なら親。ほかの形はそのまま(登録と一致しない) */
230
+ export function registrationOf(room: string): string {
231
+ return /^([^/]+)\/[^/.]+$/.exec(room)?.[1] ?? room
232
+ }
233
+
234
+ export function serviceOf(id: string): string {
235
+ return id.slice(0, id.indexOf(":"))
236
+ }
237
+
238
+ export function localId(id: string): string {
239
+ return id.slice(id.indexOf(":") + 1)
240
+ }