@im-more/dsh-line 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/cordis.patch.yml +12 -0
- package/lib/index.js +1701 -0
- package/lib/index.js.map +1 -0
- package/lib/types/bot.d.ts +55 -0
- package/lib/types/bot.d.ts.map +1 -0
- package/lib/types/bot.js +169 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +47 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +77 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/decode.d.ts +60 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +321 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +47 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +112 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +17 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +24 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +17 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +16 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/media.d.ts +19 -0
- package/lib/types/media.d.ts.map +1 -0
- package/lib/types/media.js +55 -0
- package/lib/types/media.js.map +1 -0
- package/lib/types/modes/shared.d.ts +126 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +316 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/modes/text.d.ts +13 -0
- package/lib/types/modes/text.d.ts.map +1 -0
- package/lib/types/modes/text.js +143 -0
- package/lib/types/modes/text.js.map +1 -0
- package/lib/types/request.d.ts +49 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +162 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +43 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +74 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/signature.d.ts +19 -0
- package/lib/types/signature.d.ts.map +1 -0
- package/lib/types/signature.js +30 -0
- package/lib/types/signature.js.map +1 -0
- package/lib/types/transport/media.d.ts +62 -0
- package/lib/types/transport/media.d.ts.map +1 -0
- package/lib/types/transport/media.js +104 -0
- package/lib/types/transport/media.js.map +1 -0
- package/lib/types/transport/webhook.d.ts +62 -0
- package/lib/types/transport/webhook.d.ts.map +1 -0
- package/lib/types/transport/webhook.js +208 -0
- package/lib/types/transport/webhook.js.map +1 -0
- package/lib/types/types/definition.d.ts +1006 -0
- package/lib/types/types/definition.d.ts.map +1 -0
- package/lib/types/types/definition.js +2 -0
- package/lib/types/types/definition.js.map +1 -0
- package/lib/types/types/index.d.ts +542 -0
- package/lib/types/types/index.d.ts.map +1 -0
- package/lib/types/types/index.js +4 -0
- package/lib/types/types/index.js.map +1 -0
- package/lib/types/types/internal.d.ts +8 -0
- package/lib/types/types/internal.d.ts.map +1 -0
- package/lib/types/types/internal.js +234 -0
- package/lib/types/types/internal.js.map +1 -0
- package/lib/types/types/request.d.ts +341 -0
- package/lib/types/types/request.d.ts.map +1 -0
- package/lib/types/types/request.js +2 -0
- package/lib/types/types/request.js.map +1 -0
- package/package.json +61 -3
- package/src/bot.ts +229 -0
- package/src/config.ts +113 -0
- package/src/decode.ts +418 -0
- package/src/errors.ts +138 -0
- package/src/identity.ts +28 -0
- package/src/index.ts +60 -0
- package/src/media.ts +66 -0
- package/src/modes/shared.ts +408 -0
- package/src/modes/text.ts +177 -0
- package/src/request.ts +215 -0
- package/src/send.ts +104 -0
- package/src/signature.ts +32 -0
- package/src/transport/media.ts +117 -0
- package/src/transport/webhook.ts +266 -0
- package/src/types/.eslintrc.yml +2 -0
- package/src/types/definition.ts +1008 -0
- package/src/types/index.ts +593 -0
- package/src/types/internal.ts +233 -0
- package/src/types/request.ts +341 -0
- package/README.md +0 -3
package/src/request.ts
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport every LINE REST call shares: API root, bearer authentication, JSON unwrapping, the failure
|
|
3
|
+
* `errors.ts` classifies, and content download.
|
|
4
|
+
*
|
|
5
|
+
* The typed method surface lives on `Internal`; the generated route table calls {@link invoke}, so the migrated layer
|
|
6
|
+
* and the hand-written calls (identity, push, members, content download) cannot diverge in authentication or failure
|
|
7
|
+
* handling.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
11
|
+
import type {} from '@deepseek-ai/cordis-plugin-http'
|
|
12
|
+
import type { Config } from './config.ts'
|
|
13
|
+
import { LineApiError } from './errors.ts'
|
|
14
|
+
import type { LineErrorDetail } from './errors.ts'
|
|
15
|
+
|
|
16
|
+
/** Root of the messaging API: every method except content download and the two audience uploads. */
|
|
17
|
+
export const LINE_API_ORIGIN = 'https://api.line.me'
|
|
18
|
+
|
|
19
|
+
/** Root of the content API, which serves the bytes of an inbound message. */
|
|
20
|
+
export const LINE_DATA_ORIGIN = 'https://api-data.line.me'
|
|
21
|
+
|
|
22
|
+
/** How much of a body that carried no JSON is kept in the error and the log; enough to recognise a gateway page. */
|
|
23
|
+
const BODY_PREFIX_BYTES = 512
|
|
24
|
+
|
|
25
|
+
/** One request body, query and cancellation, as the generated route table describes it. */
|
|
26
|
+
export interface LineRequestConfig {
|
|
27
|
+
data?: object
|
|
28
|
+
params?: Record<string, unknown> | undefined
|
|
29
|
+
signal?: AbortSignal | undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** What one call needs from the adapter. */
|
|
33
|
+
export interface LineRequest {
|
|
34
|
+
readonly ctx: Context
|
|
35
|
+
readonly config: Config
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Message of any caught value, for a log line. */
|
|
39
|
+
function messageOf(error: unknown): string {
|
|
40
|
+
return error instanceof Error ? error.message : String(error)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Whether a failed `ctx.http` call was the caller's cancellation rather than a transport failure. */
|
|
44
|
+
function isCancellation(
|
|
45
|
+
cause: unknown,
|
|
46
|
+
signal: AbortSignal | undefined,
|
|
47
|
+
): boolean {
|
|
48
|
+
if (signal?.aborted === true) return true
|
|
49
|
+
if (
|
|
50
|
+
(cause instanceof Error || cause instanceof DOMException) &&
|
|
51
|
+
cause.name === 'AbortError'
|
|
52
|
+
) {
|
|
53
|
+
return true
|
|
54
|
+
}
|
|
55
|
+
return signal?.reason !== undefined && cause === signal.reason
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A cancelled request rejects with the signal's reason, so the classifier sees the cancellation itself. */
|
|
59
|
+
function cancellation(
|
|
60
|
+
cause: unknown,
|
|
61
|
+
signal: AbortSignal | undefined,
|
|
62
|
+
): unknown {
|
|
63
|
+
return signal?.aborted === true ? signal.reason : cause
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One JSON object, when the value is a plain object. */
|
|
67
|
+
function asRecord(value: unknown): Record<string, unknown> | undefined {
|
|
68
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
69
|
+
? (value as Record<string, unknown>)
|
|
70
|
+
: undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The `details` array of a business refusal, keeping only the fields a log or a caller can name. */
|
|
74
|
+
function detailsOf(value: unknown): LineErrorDetail[] {
|
|
75
|
+
if (!Array.isArray(value)) return []
|
|
76
|
+
const out: LineErrorDetail[] = []
|
|
77
|
+
for (const item of value) {
|
|
78
|
+
const record = asRecord(item)
|
|
79
|
+
if (record === undefined) continue
|
|
80
|
+
out.push({
|
|
81
|
+
...(typeof record.property === 'string'
|
|
82
|
+
? { property: record.property }
|
|
83
|
+
: {}),
|
|
84
|
+
...(typeof record.message === 'string'
|
|
85
|
+
? { message: record.message }
|
|
86
|
+
: {}),
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
return out
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The field names a business refusal names, for the error message. */
|
|
93
|
+
function propertiesOf(details: readonly LineErrorDetail[]): string {
|
|
94
|
+
const names = details
|
|
95
|
+
.map((detail) => detail.property)
|
|
96
|
+
.filter((name): name is string => name !== undefined && name !== '')
|
|
97
|
+
return names.length === 0 ? '' : ` (${names.join(', ')})`
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Call one messaging API endpoint.
|
|
102
|
+
*
|
|
103
|
+
* @param request - the adapter whose credentials and context the call uses.
|
|
104
|
+
* @param method - HTTP method.
|
|
105
|
+
* @param path - endpoint path under {@link LINE_API_ORIGIN}.
|
|
106
|
+
* @param config - body, query parameters and cancellation of the call.
|
|
107
|
+
* @returns the unwrapped JSON answer.
|
|
108
|
+
* @throws LineApiError when the platform refused the call or did not answer with JSON.
|
|
109
|
+
*/
|
|
110
|
+
export async function invoke<T>(
|
|
111
|
+
request: LineRequest,
|
|
112
|
+
method: string,
|
|
113
|
+
path: string,
|
|
114
|
+
config: LineRequestConfig = {},
|
|
115
|
+
): Promise<T> {
|
|
116
|
+
let response: Response
|
|
117
|
+
try {
|
|
118
|
+
response = await request.ctx.http(`${LINE_API_ORIGIN}${path}`, {
|
|
119
|
+
method,
|
|
120
|
+
headers: { authorization: `Bearer ${request.config.token}` },
|
|
121
|
+
...(config.data === undefined ? {} : { data: config.data }),
|
|
122
|
+
...(config.params === undefined ? {} : { params: config.params }),
|
|
123
|
+
...(config.signal === undefined ? {} : { signal: config.signal }),
|
|
124
|
+
})
|
|
125
|
+
} catch (cause) {
|
|
126
|
+
if (isCancellation(cause, config.signal)) {
|
|
127
|
+
throw cancellation(cause, config.signal)
|
|
128
|
+
}
|
|
129
|
+
throw new LineApiError(
|
|
130
|
+
`line: ${method} ${path} request failed: ${messageOf(cause)}`,
|
|
131
|
+
{ cause },
|
|
132
|
+
)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let text: string
|
|
136
|
+
try {
|
|
137
|
+
text = await response.text()
|
|
138
|
+
} catch (cause) {
|
|
139
|
+
// Reading the body fails when the caller cancelled mid-answer; that is still a cancellation.
|
|
140
|
+
if (isCancellation(cause, config.signal)) {
|
|
141
|
+
throw cancellation(cause, config.signal)
|
|
142
|
+
}
|
|
143
|
+
throw new LineApiError(
|
|
144
|
+
`line: ${method} ${path} answered ${response.status} but its body could not be read`,
|
|
145
|
+
{ status: response.status, cause },
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let body: unknown
|
|
150
|
+
let nonJson = false
|
|
151
|
+
if (text !== '') {
|
|
152
|
+
try {
|
|
153
|
+
body = JSON.parse(text)
|
|
154
|
+
} catch {
|
|
155
|
+
nonJson = true
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const record = asRecord(body)
|
|
159
|
+
const platformMessage =
|
|
160
|
+
typeof record?.message === 'string'
|
|
161
|
+
? record.message
|
|
162
|
+
: typeof record?.error_description === 'string'
|
|
163
|
+
? record.error_description
|
|
164
|
+
: undefined
|
|
165
|
+
const error = typeof record?.error === 'string' ? record.error : undefined
|
|
166
|
+
const details = detailsOf(record?.details)
|
|
167
|
+
if (response.status < 200 || response.status >= 300 || nonJson) {
|
|
168
|
+
const suffix =
|
|
169
|
+
(platformMessage === undefined ? '' : `: ${platformMessage}`) +
|
|
170
|
+
propertiesOf(details)
|
|
171
|
+
throw new LineApiError(
|
|
172
|
+
`line: ${method} ${path} answered ${response.status}${suffix}`,
|
|
173
|
+
{
|
|
174
|
+
status: response.status,
|
|
175
|
+
...(platformMessage === undefined ? {} : { platformMessage }),
|
|
176
|
+
...(error === undefined ? {} : { error }),
|
|
177
|
+
...(details.length === 0 ? {} : { details }),
|
|
178
|
+
...(text === '' ? {} : { bodyText: text.slice(0, BODY_PREFIX_BYTES) }),
|
|
179
|
+
nonJson,
|
|
180
|
+
},
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
return body as T
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Download the bytes of one inbound message from the content API.
|
|
188
|
+
*
|
|
189
|
+
* The answer is returned as it arrived, whatever its status: the caller maps `200`/`202`/`404`/`410` to the inbound
|
|
190
|
+
* media contract. A request that never got an answer rejects.
|
|
191
|
+
*
|
|
192
|
+
* @param request - the adapter whose credentials and context the download uses.
|
|
193
|
+
* @param messageId - platform message id the bytes belong to.
|
|
194
|
+
* @param signal - cancellation.
|
|
195
|
+
* @returns the content API answer.
|
|
196
|
+
*/
|
|
197
|
+
export async function downloadContent(
|
|
198
|
+
request: LineRequest,
|
|
199
|
+
messageId: string,
|
|
200
|
+
signal?: AbortSignal,
|
|
201
|
+
): Promise<Response> {
|
|
202
|
+
try {
|
|
203
|
+
const response: Response = await request.ctx.http(
|
|
204
|
+
`${LINE_DATA_ORIGIN}/v2/bot/message/${encodeURIComponent(messageId)}/content`,
|
|
205
|
+
{
|
|
206
|
+
headers: { authorization: `Bearer ${request.config.token}` },
|
|
207
|
+
...(signal === undefined ? {} : { signal }),
|
|
208
|
+
},
|
|
209
|
+
)
|
|
210
|
+
return response
|
|
211
|
+
} catch (cause) {
|
|
212
|
+
if (isCancellation(cause, signal)) throw cancellation(cause, signal)
|
|
213
|
+
throw cause
|
|
214
|
+
}
|
|
215
|
+
}
|
package/src/send.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound: one push request per draft, and the member pages `im_members` reads.
|
|
3
|
+
*
|
|
4
|
+
* LINE has no reply API the DSH pipeline could use — a reply token lives one minute and is single-use, while a turn may
|
|
5
|
+
* run for minutes — so every send is a push. The reply token is still kept in the inbound referrer for a plugin that
|
|
6
|
+
* calls `bot.internal.replyMessage` itself.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { PlatformError } from '@deepseek-ai/cordis-plugin-im-core'
|
|
10
|
+
import type {
|
|
11
|
+
ChatRef,
|
|
12
|
+
MembersPage,
|
|
13
|
+
SendContext,
|
|
14
|
+
SentPart,
|
|
15
|
+
Target,
|
|
16
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
17
|
+
import { parseChatId } from './decode.ts'
|
|
18
|
+
import type { LinePayload } from './modes/shared.ts'
|
|
19
|
+
import type { Internal } from './types/internal.ts'
|
|
20
|
+
|
|
21
|
+
/** Everything `sendPayload` and `members` need from the adapter. */
|
|
22
|
+
export interface LineSendDeps {
|
|
23
|
+
readonly internal: Internal
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Send one serialized payload and report the parts the platform created.
|
|
28
|
+
*
|
|
29
|
+
* A refused push is a request-level failure: LINE has no partial send, and it documents that a request answered with an
|
|
30
|
+
* error sent nothing.
|
|
31
|
+
*
|
|
32
|
+
* @param deps - the adapter's API surface.
|
|
33
|
+
* @param payload - one push body.
|
|
34
|
+
* @param _target - the chat the payload goes to; the recipient already rides `payload.to`.
|
|
35
|
+
* @param _ctx - the core send context; this adapter keeps no per-part state.
|
|
36
|
+
* @returns the published part; its `aliases` are the remaining message ids of the same request.
|
|
37
|
+
* @throws PlatformError `invalid` when the answer carries no `sentMessages`, with an unknown outcome.
|
|
38
|
+
*/
|
|
39
|
+
export async function sendPayload(
|
|
40
|
+
deps: LineSendDeps,
|
|
41
|
+
payload: LinePayload,
|
|
42
|
+
_target: Target,
|
|
43
|
+
_ctx: SendContext,
|
|
44
|
+
): Promise<SentPart> {
|
|
45
|
+
const answer = await deps.internal.pushMessage({
|
|
46
|
+
to: payload.to,
|
|
47
|
+
messages: payload.messages,
|
|
48
|
+
})
|
|
49
|
+
const sent = answer.sentMessages ?? []
|
|
50
|
+
const [head, ...rest] = sent
|
|
51
|
+
if (head === undefined) {
|
|
52
|
+
// The request reached the platform and was accepted, but no message id came back: the outcome is not "unpublished".
|
|
53
|
+
throw new PlatformError(
|
|
54
|
+
'invalid',
|
|
55
|
+
'line: pushMessage answered without sentMessages',
|
|
56
|
+
{ published: 'unknown' },
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
id: head.id,
|
|
61
|
+
kind: 'message',
|
|
62
|
+
time: Date.now(),
|
|
63
|
+
...(rest.length === 0
|
|
64
|
+
? {}
|
|
65
|
+
: { aliases: rest.map((message) => message.id) }),
|
|
66
|
+
// The quote tokens of this request are how a later reply can quote one of its own messages.
|
|
67
|
+
raw: {
|
|
68
|
+
ids: sent.map((message) => message.id),
|
|
69
|
+
quoteTokens: sent.map((message) => message.quoteToken),
|
|
70
|
+
},
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* One page of the members of a chat.
|
|
76
|
+
*
|
|
77
|
+
* A group or a room lists its member ids through the platform; a direct chat's only member is the peer, which the
|
|
78
|
+
* `chat.id` already names. Names are not filled in: the platform wants one profile request per member, and that
|
|
79
|
+
* request is refused for a user who has not agreed to the Official Accounts Terms of Use.
|
|
80
|
+
*
|
|
81
|
+
* @param deps - the adapter's API surface.
|
|
82
|
+
* @param chat - the chat to list.
|
|
83
|
+
* @param cursor - the previous page's `next` token, valid for 24 hours.
|
|
84
|
+
* @param _limit - unused; the platform fixes the page size at 100 and the host truncates the answer.
|
|
85
|
+
* @returns one page of member ids.
|
|
86
|
+
*/
|
|
87
|
+
export async function members(
|
|
88
|
+
deps: LineSendDeps,
|
|
89
|
+
chat: ChatRef,
|
|
90
|
+
cursor?: string,
|
|
91
|
+
_limit?: number,
|
|
92
|
+
): Promise<MembersPage> {
|
|
93
|
+
const address = parseChatId(chat.id)
|
|
94
|
+
if (address.kind === 'user') return { data: [{ id: address.id }] }
|
|
95
|
+
const query = cursor === undefined ? undefined : { start: cursor }
|
|
96
|
+
const answer =
|
|
97
|
+
address.kind === 'group'
|
|
98
|
+
? await deps.internal.getGroupMembersIds(address.id, query)
|
|
99
|
+
: await deps.internal.getRoomMembersIds(address.id, query)
|
|
100
|
+
return {
|
|
101
|
+
data: answer.memberIds.map((id) => ({ id })),
|
|
102
|
+
...(answer.next === undefined ? {} : { next: answer.next }),
|
|
103
|
+
}
|
|
104
|
+
}
|
package/src/signature.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The `x-line-signature` value of one webhook request.
|
|
5
|
+
*
|
|
6
|
+
* LINE signs the request body exactly as it arrived, keyed by the channel secret.
|
|
7
|
+
*
|
|
8
|
+
* @param secret - the channel secret.
|
|
9
|
+
* @param body - the raw request body, before any decoding.
|
|
10
|
+
* @returns base64 of `HMAC-SHA256(secret, body)`.
|
|
11
|
+
*/
|
|
12
|
+
export function signatureOf(secret: string, body: string): string {
|
|
13
|
+
return createHmac('sha256', secret).update(body).digest('base64')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Compare a received signature with the computed one without leaking where they differ.
|
|
18
|
+
*
|
|
19
|
+
* @param expected - the signature computed from the body.
|
|
20
|
+
* @param received - the header value, if the request carried one.
|
|
21
|
+
* @returns whether the header matches.
|
|
22
|
+
*/
|
|
23
|
+
export function matchesSignature(
|
|
24
|
+
expected: string,
|
|
25
|
+
received: string | undefined,
|
|
26
|
+
): boolean {
|
|
27
|
+
if (received === undefined) return false
|
|
28
|
+
const left = Buffer.from(expected, 'utf8')
|
|
29
|
+
const right = Buffer.from(received, 'utf8')
|
|
30
|
+
if (left.length !== right.length) return false
|
|
31
|
+
return timingSafeEqual(left, right)
|
|
32
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound media: the public route LINE fetches staged bytes from.
|
|
3
|
+
*
|
|
4
|
+
* The Messaging API has no endpoint that uploads message media; an image, video or audio message carries only HTTPS URLs
|
|
5
|
+
* that the LINE servers fetch themselves. The adapter therefore stages the bytes of every non-HTTPS source in memory
|
|
6
|
+
* and serves them from an anonymous, unguessable URL for the lifetime of the process.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { randomBytes } from 'node:crypto'
|
|
10
|
+
import type { LineBot } from '../bot.ts'
|
|
11
|
+
import { routePath } from '../config.ts'
|
|
12
|
+
import type { WebServerLike } from './webhook.ts'
|
|
13
|
+
|
|
14
|
+
/** One staged attachment. */
|
|
15
|
+
export interface StagedMedia {
|
|
16
|
+
data: Uint8Array
|
|
17
|
+
mime?: string
|
|
18
|
+
name?: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Staged bytes by opaque token.
|
|
23
|
+
*
|
|
24
|
+
* Entries live until the process exits: the platform may fetch a URL minutes after a send, and the W1 rule forbids
|
|
25
|
+
* inventing a TTL or a byte cap the platform does not document. The `prepare` cache means the same media is staged
|
|
26
|
+
* once, not once per send.
|
|
27
|
+
*/
|
|
28
|
+
export class MediaStaging {
|
|
29
|
+
private readonly entries = new Map<string, StagedMedia>()
|
|
30
|
+
|
|
31
|
+
constructor(
|
|
32
|
+
private readonly base: string,
|
|
33
|
+
private readonly prefix: string,
|
|
34
|
+
) {}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Stage one attachment.
|
|
38
|
+
*
|
|
39
|
+
* @param media - the bytes, their MIME type and name.
|
|
40
|
+
* @returns the public URL LINE fetches the bytes from.
|
|
41
|
+
*/
|
|
42
|
+
stage(media: StagedMedia): string {
|
|
43
|
+
// 128 random bits: the route is anonymous, so the URL is the only thing keeping unrelated readers out.
|
|
44
|
+
const token = randomBytes(16).toString('base64url')
|
|
45
|
+
this.entries.set(token, media)
|
|
46
|
+
return `${this.base}${this.prefix}/${token}`
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Read staged bytes back.
|
|
51
|
+
*
|
|
52
|
+
* @param token - the last path segment of a URL returned by {@link stage}.
|
|
53
|
+
* @returns the staged attachment, or undefined for an unknown token.
|
|
54
|
+
*/
|
|
55
|
+
get(token: string): StagedMedia | undefined {
|
|
56
|
+
return this.entries.get(token)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The number of attachments currently staged, for tests and diagnostics. */
|
|
60
|
+
get size(): number {
|
|
61
|
+
return this.entries.size
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The public media route.
|
|
67
|
+
*
|
|
68
|
+
* It is registered as a `prefix` resource, so the web server hands it a Fetch `Request` and takes the `Response` back;
|
|
69
|
+
* the route is anonymous because LINE's servers carry no DSH peer credential.
|
|
70
|
+
*/
|
|
71
|
+
export class LineMediaRoute {
|
|
72
|
+
private dispose: (() => void) | undefined
|
|
73
|
+
|
|
74
|
+
constructor(
|
|
75
|
+
private readonly bot: LineBot,
|
|
76
|
+
private readonly webServer: WebServerLike,
|
|
77
|
+
) {}
|
|
78
|
+
|
|
79
|
+
/** Register the prefix route. */
|
|
80
|
+
start(): void {
|
|
81
|
+
const path = routePath(this.bot.config.media.path)
|
|
82
|
+
this.dispose = this.webServer.register({
|
|
83
|
+
kind: 'prefix',
|
|
84
|
+
path,
|
|
85
|
+
auth: 'anonymous',
|
|
86
|
+
resource: (request) => this.serve(request),
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Release the route. */
|
|
91
|
+
stop(): void {
|
|
92
|
+
this.dispose?.()
|
|
93
|
+
this.dispose = undefined
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private async serve(request: Request): Promise<Response> {
|
|
97
|
+
const prefix = `${routePath(this.bot.config.media.path)}/`
|
|
98
|
+
const { pathname } = new URL(request.url)
|
|
99
|
+
if (!pathname.startsWith(prefix)) {
|
|
100
|
+
return new Response(null, { status: 404 })
|
|
101
|
+
}
|
|
102
|
+
const segment = pathname.slice(prefix.length)
|
|
103
|
+
let token: string
|
|
104
|
+
try {
|
|
105
|
+
token = decodeURIComponent(segment)
|
|
106
|
+
} catch {
|
|
107
|
+
// The web server answers a malformed escape before this route runs; a token it still cannot decode names nothing.
|
|
108
|
+
return new Response(null, { status: 404 })
|
|
109
|
+
}
|
|
110
|
+
const media = this.bot.staging.get(token)
|
|
111
|
+
if (media === undefined) return new Response(null, { status: 404 })
|
|
112
|
+
const headers = new Headers()
|
|
113
|
+
headers.set('content-type', media.mime ?? 'application/octet-stream')
|
|
114
|
+
headers.set('content-length', String(media.data.byteLength))
|
|
115
|
+
return new Response(media.data, { status: 200, headers })
|
|
116
|
+
}
|
|
117
|
+
}
|