@im-more/dsh-onebot 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 +11 -0
- package/lib/index.js +2003 -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 +140 -0
- package/lib/types/bot.js.map +1 -0
- package/lib/types/config.d.ts +40 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +33 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/cqcode.d.ts +29 -0
- package/lib/types/cqcode.d.ts.map +1 -0
- package/lib/types/cqcode.js +73 -0
- package/lib/types/cqcode.js.map +1 -0
- package/lib/types/decode.d.ts +106 -0
- package/lib/types/decode.d.ts.map +1 -0
- package/lib/types/decode.js +433 -0
- package/lib/types/decode.js.map +1 -0
- package/lib/types/errors.d.ts +32 -0
- package/lib/types/errors.d.ts.map +1 -0
- package/lib/types/errors.js +117 -0
- package/lib/types/errors.js.map +1 -0
- package/lib/types/identity.d.ts +18 -0
- package/lib/types/identity.d.ts.map +1 -0
- package/lib/types/identity.js +27 -0
- package/lib/types/identity.js.map +1 -0
- package/lib/types/index.d.ts +7 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +6 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/modes/segment.d.ts +16 -0
- package/lib/types/modes/segment.d.ts.map +1 -0
- package/lib/types/modes/segment.js +80 -0
- package/lib/types/modes/segment.js.map +1 -0
- package/lib/types/modes/shared.d.ts +101 -0
- package/lib/types/modes/shared.d.ts.map +1 -0
- package/lib/types/modes/shared.js +208 -0
- package/lib/types/modes/shared.js.map +1 -0
- package/lib/types/request.d.ts +64 -0
- package/lib/types/request.d.ts.map +1 -0
- package/lib/types/request.js +108 -0
- package/lib/types/request.js.map +1 -0
- package/lib/types/send.d.ts +93 -0
- package/lib/types/send.d.ts.map +1 -0
- package/lib/types/send.js +161 -0
- package/lib/types/send.js.map +1 -0
- package/lib/types/transport/http.d.ts +29 -0
- package/lib/types/transport/http.d.ts.map +1 -0
- package/lib/types/transport/http.js +158 -0
- package/lib/types/transport/http.js.map +1 -0
- package/lib/types/transport/shared.d.ts +48 -0
- package/lib/types/transport/shared.d.ts.map +1 -0
- package/lib/types/transport/shared.js +75 -0
- package/lib/types/transport/shared.js.map +1 -0
- package/lib/types/transport/ws-reverse.d.ts +42 -0
- package/lib/types/transport/ws-reverse.d.ts.map +1 -0
- package/lib/types/transport/ws-reverse.js +178 -0
- package/lib/types/transport/ws-reverse.js.map +1 -0
- package/lib/types/transport/ws.d.ts +40 -0
- package/lib/types/transport/ws.d.ts.map +1 -0
- package/lib/types/transport/ws.js +233 -0
- package/lib/types/transport/ws.js.map +1 -0
- package/lib/types/types.d.ts +495 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +191 -0
- package/lib/types/types.js.map +1 -0
- package/package.json +68 -3
- package/src/bot.ts +230 -0
- package/src/config.ts +66 -0
- package/src/cqcode.ts +85 -0
- package/src/decode.ts +524 -0
- package/src/errors.ts +134 -0
- package/src/identity.ts +34 -0
- package/src/index.ts +18 -0
- package/src/modes/segment.ts +109 -0
- package/src/modes/shared.ts +277 -0
- package/src/request.ts +128 -0
- package/src/send.ts +233 -0
- package/src/transport/http.ts +221 -0
- package/src/transport/shared.ts +98 -0
- package/src/transport/ws-reverse.ts +236 -0
- package/src/transport/ws.ts +286 -0
- package/src/types.ts +743 -0
- package/README.md +0 -3
package/src/send.ts
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Outbound hooks: the send pipeline's payload, deletion, member reads, message reads and reactions.
|
|
3
|
+
*
|
|
4
|
+
* Requests go through the migrated `Internal` surface, so the action names and parameter order are the upstream ones.
|
|
5
|
+
* Images, records and videos travel as the source string itself; a `<file>` becomes `download_file` plus
|
|
6
|
+
* `upload_group_file` / `upload_private_file`, because those actions accept only a path on the implementation's host.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
PlatformError,
|
|
11
|
+
type ChatRef,
|
|
12
|
+
type InboundMessage,
|
|
13
|
+
type MembersPage,
|
|
14
|
+
type MessageRef,
|
|
15
|
+
type SendContext,
|
|
16
|
+
type SentPart,
|
|
17
|
+
type Target,
|
|
18
|
+
type UserRef,
|
|
19
|
+
} from '@deepseek-ai/cordis-plugin-im-core'
|
|
20
|
+
import { randomUUID } from 'node:crypto'
|
|
21
|
+
import { fileURLToPath } from 'node:url'
|
|
22
|
+
import type { OneBotBot } from './bot.ts'
|
|
23
|
+
import type { CQCode } from './cqcode.ts'
|
|
24
|
+
import { decodeMessage, expandForward } from './decode.ts'
|
|
25
|
+
import {
|
|
26
|
+
GROUP_PREFIX,
|
|
27
|
+
PRIVATE_PREFIX,
|
|
28
|
+
type OneBotPayload,
|
|
29
|
+
} from './modes/shared.ts'
|
|
30
|
+
import type { Internal } from './types.ts'
|
|
31
|
+
|
|
32
|
+
/** Everything the send hooks need from the adapter. */
|
|
33
|
+
export interface OneBotSendDeps {
|
|
34
|
+
readonly internal: Internal
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A chat id split into the action family that addresses it. */
|
|
38
|
+
export interface OneBotChat {
|
|
39
|
+
kind: 'group' | 'private'
|
|
40
|
+
id: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Split a DSH chat id into the OneBot action family and the platform id.
|
|
45
|
+
* @param chat - the target chat.
|
|
46
|
+
* @returns kind and raw id.
|
|
47
|
+
* @throws PlatformError `invalid` for a chat id this adapter did not produce.
|
|
48
|
+
*/
|
|
49
|
+
export function chatTarget(chat: ChatRef): OneBotChat {
|
|
50
|
+
if (chat.id.startsWith(GROUP_PREFIX)) {
|
|
51
|
+
return { kind: 'group', id: chat.id.slice(GROUP_PREFIX.length) }
|
|
52
|
+
}
|
|
53
|
+
if (chat.id.startsWith(PRIVATE_PREFIX)) {
|
|
54
|
+
return { kind: 'private', id: chat.id.slice(PRIVATE_PREFIX.length) }
|
|
55
|
+
}
|
|
56
|
+
throw new PlatformError(
|
|
57
|
+
'invalid',
|
|
58
|
+
`onebot: chat id "${chat.id}" must start with "group:" or "private:"`,
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Data URI prefix of an inline image; the implementation wants the `base64://` form instead. */
|
|
63
|
+
const DATA_URL = /^data:([\w/.+-]+);base64,/
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Normalize one media source without fetching it.
|
|
67
|
+
*
|
|
68
|
+
* A `data:` URI becomes the `base64://` form the implementation decodes; every other source (an `http(s)` URL, a
|
|
69
|
+
* `base64://` payload, a path) is passed through unchanged, because the implementation fetches it itself.
|
|
70
|
+
*
|
|
71
|
+
* @param src - the element's source.
|
|
72
|
+
* @returns the string to put in the segment's `file` field.
|
|
73
|
+
*/
|
|
74
|
+
export function normalizeSource(src: string): string {
|
|
75
|
+
const match = DATA_URL.exec(src)
|
|
76
|
+
return match === null ? src : `base64://${src.slice(match[0].length)}`
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Send one serialized payload.
|
|
81
|
+
* @param deps - the action client.
|
|
82
|
+
* @param payload - the mode's request data.
|
|
83
|
+
* @param target - the target chat.
|
|
84
|
+
* @param ctx - part index, quote and options.
|
|
85
|
+
* @returns the published part.
|
|
86
|
+
*/
|
|
87
|
+
export async function sendPayload(
|
|
88
|
+
deps: OneBotSendDeps,
|
|
89
|
+
payload: OneBotPayload,
|
|
90
|
+
_target: Target,
|
|
91
|
+
_ctx: SendContext,
|
|
92
|
+
): Promise<SentPart> {
|
|
93
|
+
if (payload.kind === 'file') {
|
|
94
|
+
const chat = chatTarget(payload.chat)
|
|
95
|
+
if (chat.kind === 'group') {
|
|
96
|
+
await deps.internal.uploadGroupFile(chat.id, payload.key, payload.name)
|
|
97
|
+
} else {
|
|
98
|
+
await deps.internal.uploadPrivateFile(chat.id, payload.key, payload.name)
|
|
99
|
+
}
|
|
100
|
+
// Neither action answers with a message id, so the part carries a synthesized one the platform cannot address.
|
|
101
|
+
const id = `onebot-file:${randomUUID()}`
|
|
102
|
+
return {
|
|
103
|
+
id,
|
|
104
|
+
kind: 'file',
|
|
105
|
+
time: Date.now(),
|
|
106
|
+
referrer: { chatId: payload.chat.id, messageId: id },
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const chat = chatTarget(payload.chat)
|
|
111
|
+
const segments = payload.segments as CQCode[]
|
|
112
|
+
const sent: number =
|
|
113
|
+
chat.kind === 'group'
|
|
114
|
+
? await deps.internal.sendGroupMsg(chat.id, segments)
|
|
115
|
+
: await deps.internal.sendPrivateMsg(chat.id, segments)
|
|
116
|
+
const messageId: number | undefined = sent
|
|
117
|
+
if (messageId === undefined) {
|
|
118
|
+
// The request reached the implementation, so the outcome is unknown rather than unpublished.
|
|
119
|
+
throw new PlatformError(
|
|
120
|
+
'invalid',
|
|
121
|
+
'onebot: the implementation answered a send without message_id',
|
|
122
|
+
{ published: 'unknown' },
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
const id = String(messageId)
|
|
126
|
+
return {
|
|
127
|
+
id,
|
|
128
|
+
kind: 'message',
|
|
129
|
+
time: Date.now(),
|
|
130
|
+
referrer: { chatId: payload.chat.id, messageId: id },
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Recall one published part.
|
|
136
|
+
*
|
|
137
|
+
* A file part carries a synthesized id that no platform message answers, so it is skipped instead of recalling an
|
|
138
|
+
* unrelated message.
|
|
139
|
+
*
|
|
140
|
+
* @param deps - the action client.
|
|
141
|
+
* @param part - the part to recall.
|
|
142
|
+
*/
|
|
143
|
+
export async function deletePart(
|
|
144
|
+
deps: OneBotSendDeps,
|
|
145
|
+
part: SentPart,
|
|
146
|
+
): Promise<void> {
|
|
147
|
+
if (part.kind === 'file') return
|
|
148
|
+
await deps.internal.deleteMsg(part.id)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* List the members of one group.
|
|
153
|
+
* @param deps - the action client.
|
|
154
|
+
* @param chat - the group chat.
|
|
155
|
+
* @returns the whole member list; the standard offers no paging.
|
|
156
|
+
*/
|
|
157
|
+
export async function members(
|
|
158
|
+
deps: OneBotSendDeps,
|
|
159
|
+
chat: ChatRef,
|
|
160
|
+
): Promise<MembersPage> {
|
|
161
|
+
const target = chatTarget(chat)
|
|
162
|
+
if (target.kind !== 'group') {
|
|
163
|
+
throw new PlatformError(
|
|
164
|
+
'invalid',
|
|
165
|
+
'onebot: members() is only available in a group chat',
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
const list = await deps.internal.getGroupMemberList(target.id)
|
|
169
|
+
const data: UserRef[] = list.map((member) => {
|
|
170
|
+
const name = member.card || member.nickname
|
|
171
|
+
return {
|
|
172
|
+
id: String(member.user_id),
|
|
173
|
+
...(name === '' ? {} : { name }),
|
|
174
|
+
...(member.role === undefined ? {} : { role: member.role }),
|
|
175
|
+
}
|
|
176
|
+
})
|
|
177
|
+
return { data }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Read one message, expanding any merged forward it carries.
|
|
182
|
+
* @param deps - the action client.
|
|
183
|
+
* @param bot - the adapter, needed by the forward expansion.
|
|
184
|
+
* @param chat - the chat the caller asked about; the answer carries no chat, so it is reused verbatim.
|
|
185
|
+
* @param id - platform message id.
|
|
186
|
+
* @returns the decoded message, with the same `chat.id` the caller passed.
|
|
187
|
+
*/
|
|
188
|
+
export async function getMessage(
|
|
189
|
+
deps: OneBotSendDeps,
|
|
190
|
+
bot: OneBotBot,
|
|
191
|
+
chat: ChatRef,
|
|
192
|
+
id: string,
|
|
193
|
+
): Promise<InboundMessage> {
|
|
194
|
+
const data = await deps.internal.getMsg(id)
|
|
195
|
+
return expandForward(bot, decodeMessage(bot, data, chat))
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Add one reaction to a published message.
|
|
200
|
+
* @param deps - the action client.
|
|
201
|
+
* @param message - the message to react to.
|
|
202
|
+
* @param emoji - platform emoji id.
|
|
203
|
+
*/
|
|
204
|
+
export async function createReaction(
|
|
205
|
+
deps: OneBotSendDeps,
|
|
206
|
+
message: MessageRef,
|
|
207
|
+
emoji: string,
|
|
208
|
+
): Promise<void> {
|
|
209
|
+
await deps.internal.setMsgEmojiLike(message.id, emoji, true)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Remove one reaction from a published message.
|
|
214
|
+
* @param deps - the action client.
|
|
215
|
+
* @param message - the message to react to.
|
|
216
|
+
* @param emoji - platform emoji id.
|
|
217
|
+
*/
|
|
218
|
+
export async function deleteReaction(
|
|
219
|
+
deps: OneBotSendDeps,
|
|
220
|
+
message: MessageRef,
|
|
221
|
+
emoji: string,
|
|
222
|
+
): Promise<void> {
|
|
223
|
+
await deps.internal.setMsgEmojiLike(message.id, emoji, false)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Convert a `file:` source into the local path an upload action accepts.
|
|
228
|
+
* @param src - a `file:` URI.
|
|
229
|
+
* @returns the filesystem path.
|
|
230
|
+
*/
|
|
231
|
+
export function localPathOf(src: string): string {
|
|
232
|
+
return fileURLToPath(src)
|
|
233
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP transport (`protocol: 'http'`): an outbound `POST {endpoint}/{action}` client and an inbound event route.
|
|
3
|
+
*
|
|
4
|
+
* Both directions run at once, as in the upstream plugin. The outbound call authenticates with the standard
|
|
5
|
+
* `Authorization: Bearer` header; the inbound route checks `X-Signature` (HMAC-SHA1 over the re-serialized parsed body,
|
|
6
|
+
* the upstream behaviour implementations in the field verify) and `X-Self-ID`, and answers `204` only after the host
|
|
7
|
+
* accepted the event.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { Dict } from '@deepseek-ai/cosmokit'
|
|
11
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
12
|
+
import type { OneBotBot } from '../bot.ts'
|
|
13
|
+
import { routePath } from '../config.ts'
|
|
14
|
+
import { decodePayload } from '../decode.ts'
|
|
15
|
+
import { OneBotHttpError } from '../errors.ts'
|
|
16
|
+
import { installRequest } from '../request.ts'
|
|
17
|
+
import type { Response as OneBotResponse, Payload } from '../types.ts'
|
|
18
|
+
import {
|
|
19
|
+
headerOf,
|
|
20
|
+
matchesSecret,
|
|
21
|
+
readBody,
|
|
22
|
+
signatureOf,
|
|
23
|
+
writeStatus,
|
|
24
|
+
} from './shared.ts'
|
|
25
|
+
|
|
26
|
+
/** The part of `ctx.webServer` this transport uses. */
|
|
27
|
+
interface WebServerLike {
|
|
28
|
+
register(route: {
|
|
29
|
+
kind: 'exact'
|
|
30
|
+
path: string
|
|
31
|
+
auth: 'anonymous'
|
|
32
|
+
handler: (
|
|
33
|
+
request: IncomingMessage,
|
|
34
|
+
response: ServerResponse,
|
|
35
|
+
) => void | Promise<void>
|
|
36
|
+
}): () => void
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The HTTP service's failure carries the response it refused; recover it structurally. */
|
|
40
|
+
function responseOf(cause: unknown): Response | undefined {
|
|
41
|
+
if (typeof cause !== 'object' || cause === null || !('response' in cause))
|
|
42
|
+
return undefined
|
|
43
|
+
const response = (cause as { response?: unknown }).response
|
|
44
|
+
return response instanceof Response ? response : undefined
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The HTTP transport of one bot. */
|
|
48
|
+
export class OneBotHttp {
|
|
49
|
+
private dispose: (() => void) | undefined
|
|
50
|
+
private warnedNoSecret = false
|
|
51
|
+
|
|
52
|
+
constructor(private readonly bot: OneBotBot) {}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Claim the event route and install the action caller.
|
|
56
|
+
*/
|
|
57
|
+
async start(): Promise<void> {
|
|
58
|
+
const webServer = this.bot.ctx.get('webServer') as WebServerLike | undefined
|
|
59
|
+
if (webServer === undefined) {
|
|
60
|
+
throw this.fail(
|
|
61
|
+
'onebot: protocol "http" needs a profile-provided webServer to receive event reports',
|
|
62
|
+
)
|
|
63
|
+
}
|
|
64
|
+
const path = routePath(this.bot.config.path)
|
|
65
|
+
try {
|
|
66
|
+
this.dispose = webServer.register({
|
|
67
|
+
kind: 'exact',
|
|
68
|
+
path,
|
|
69
|
+
auth: 'anonymous',
|
|
70
|
+
handler: (request, response) => this.handle(request, response),
|
|
71
|
+
})
|
|
72
|
+
} catch (error) {
|
|
73
|
+
throw this.fail(
|
|
74
|
+
`onebot: cannot claim the http event route ${path}: ${
|
|
75
|
+
error instanceof Error ? error.message : String(error)
|
|
76
|
+
}`,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
const endpoint = this.bot.config.endpoint
|
|
80
|
+
installRequest(this.bot, (action, params) =>
|
|
81
|
+
this.call(endpoint, action, params),
|
|
82
|
+
)
|
|
83
|
+
this.bot.user = {
|
|
84
|
+
id: this.bot.config.selfId,
|
|
85
|
+
name: this.bot.config.selfId,
|
|
86
|
+
isBot: true,
|
|
87
|
+
}
|
|
88
|
+
this.bot.online()
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Release the event route. */
|
|
92
|
+
async stop(): Promise<void> {
|
|
93
|
+
this.dispose?.()
|
|
94
|
+
this.dispose = undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Log a start failure before throwing it, because `Bot.start` only stores a connect failure on `bot.error`. */
|
|
98
|
+
private fail(message: string): Error {
|
|
99
|
+
this.bot.ctx.logger.error(message)
|
|
100
|
+
return new Error(message)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** One action call against `{endpoint}/{action}`. */
|
|
104
|
+
private async call(
|
|
105
|
+
endpoint: string,
|
|
106
|
+
action: string,
|
|
107
|
+
params: Dict,
|
|
108
|
+
): Promise<OneBotResponse> {
|
|
109
|
+
const url = `${endpoint.replace(/\/+$/, '')}/${action}`
|
|
110
|
+
const { token } = this.bot.config
|
|
111
|
+
let response: Response
|
|
112
|
+
try {
|
|
113
|
+
response = await this.bot.ctx.http(url, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
data: params,
|
|
116
|
+
...(token === ''
|
|
117
|
+
? {}
|
|
118
|
+
: { headers: { Authorization: `Bearer ${token}` } }),
|
|
119
|
+
})
|
|
120
|
+
} catch (cause) {
|
|
121
|
+
const refused = responseOf(cause)
|
|
122
|
+
if (refused !== undefined) {
|
|
123
|
+
const body = await refused.text().catch(() => '')
|
|
124
|
+
throw new OneBotHttpError(
|
|
125
|
+
`onebot: ${action} was refused with HTTP ${refused.status}${
|
|
126
|
+
body === '' ? '' : `: ${body.slice(0, 200)}`
|
|
127
|
+
}`,
|
|
128
|
+
refused.status,
|
|
129
|
+
{ cause },
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
throw new OneBotHttpError(
|
|
133
|
+
`onebot: ${action} request failed: ${
|
|
134
|
+
cause instanceof Error ? cause.message : String(cause)
|
|
135
|
+
}`,
|
|
136
|
+
0,
|
|
137
|
+
{ cause },
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
let body: unknown
|
|
141
|
+
try {
|
|
142
|
+
body = await response.json()
|
|
143
|
+
} catch (cause) {
|
|
144
|
+
throw new OneBotHttpError(
|
|
145
|
+
`onebot: ${action} answered with a body that is not JSON`,
|
|
146
|
+
response.status,
|
|
147
|
+
{ cause },
|
|
148
|
+
)
|
|
149
|
+
}
|
|
150
|
+
if (typeof body !== 'object' || body === null) {
|
|
151
|
+
throw new OneBotHttpError(
|
|
152
|
+
`onebot: ${action} answered with a body that is not an action envelope`,
|
|
153
|
+
response.status,
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
return body as OneBotResponse
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Check and deliver one event report. */
|
|
160
|
+
private async handle(
|
|
161
|
+
request: IncomingMessage,
|
|
162
|
+
response: ServerResponse,
|
|
163
|
+
): Promise<void> {
|
|
164
|
+
try {
|
|
165
|
+
if (request.method !== 'POST') {
|
|
166
|
+
writeStatus(response, 405, { allow: 'POST' })
|
|
167
|
+
return
|
|
168
|
+
}
|
|
169
|
+
const { secret } = this.bot.config
|
|
170
|
+
const signature = headerOf(request, 'x-signature')
|
|
171
|
+
if (secret === '') {
|
|
172
|
+
if (!this.warnedNoSecret) {
|
|
173
|
+
this.warnedNoSecret = true
|
|
174
|
+
this.bot.ctx.logger.warn(
|
|
175
|
+
'onebot: secret is empty, so event reports are accepted without X-Signature',
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
} else if (signature === undefined || signature === '') {
|
|
179
|
+
writeStatus(response, 401)
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
const body = await readBody(request)
|
|
183
|
+
let parsed: unknown
|
|
184
|
+
try {
|
|
185
|
+
parsed = JSON.parse(body)
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.bot.ctx.logger.debug(
|
|
188
|
+
'onebot: event report is not JSON: %s',
|
|
189
|
+
error instanceof Error ? error.message : String(error),
|
|
190
|
+
)
|
|
191
|
+
writeStatus(response, 400)
|
|
192
|
+
return
|
|
193
|
+
}
|
|
194
|
+
if (
|
|
195
|
+
secret !== '' &&
|
|
196
|
+
!matchesSecret(signatureOf(secret, parsed), signature)
|
|
197
|
+
) {
|
|
198
|
+
writeStatus(response, 403)
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
if (headerOf(request, 'x-self-id') !== this.bot.config.selfId) {
|
|
202
|
+
writeStatus(response, 403)
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
206
|
+
writeStatus(response, 400)
|
|
207
|
+
return
|
|
208
|
+
}
|
|
209
|
+
const session = decodePayload(this.bot, parsed as Payload)
|
|
210
|
+
if (session !== undefined) await this.bot.receive(session)
|
|
211
|
+
writeStatus(response, 204)
|
|
212
|
+
} catch (error) {
|
|
213
|
+
this.bot.ctx.logger.warn(
|
|
214
|
+
'onebot: event report failed: %s',
|
|
215
|
+
error instanceof Error ? error.message : String(error),
|
|
216
|
+
)
|
|
217
|
+
if (!response.headersSent) writeStatus(response, 500)
|
|
218
|
+
else response.end()
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
3
|
+
import type { Duplex } from 'node:stream'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Compare a received credential with the configured one without leaking its length through early exits.
|
|
7
|
+
* @param expected - the configured secret or token.
|
|
8
|
+
* @param received - the presented value, when one was sent.
|
|
9
|
+
* @returns whether they are equal.
|
|
10
|
+
*/
|
|
11
|
+
export function matchesSecret(
|
|
12
|
+
expected: string,
|
|
13
|
+
received: string | undefined,
|
|
14
|
+
): boolean {
|
|
15
|
+
if (received === undefined) return false
|
|
16
|
+
const left = Buffer.from(expected, 'utf8')
|
|
17
|
+
const right = Buffer.from(received, 'utf8')
|
|
18
|
+
if (left.length !== right.length) return false
|
|
19
|
+
return timingSafeEqual(left, right)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* One header of an inbound request, when it arrived exactly once.
|
|
24
|
+
* @param request - the inbound request.
|
|
25
|
+
* @param name - lower-case header name.
|
|
26
|
+
* @returns the header value, or undefined when absent or repeated.
|
|
27
|
+
*/
|
|
28
|
+
export function headerOf(
|
|
29
|
+
request: IncomingMessage,
|
|
30
|
+
name: string,
|
|
31
|
+
): string | undefined {
|
|
32
|
+
const value = request.headers[name]
|
|
33
|
+
return typeof value === 'string' ? value : undefined
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Read a request body to its end. The adapter imposes no size limit, as the upstream plugin does not.
|
|
38
|
+
* @param request - the inbound request.
|
|
39
|
+
* @returns the decoded body.
|
|
40
|
+
*/
|
|
41
|
+
export async function readBody(request: IncomingMessage): Promise<string> {
|
|
42
|
+
const chunks: Buffer[] = []
|
|
43
|
+
for await (const chunk of request) {
|
|
44
|
+
chunks.push(
|
|
45
|
+
Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array),
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Answer an inbound request with an empty response.
|
|
53
|
+
* @param response - the server response.
|
|
54
|
+
* @param status - HTTP status code.
|
|
55
|
+
* @param headers - extra response headers.
|
|
56
|
+
*/
|
|
57
|
+
export function writeStatus(
|
|
58
|
+
response: ServerResponse,
|
|
59
|
+
status: number,
|
|
60
|
+
headers: Record<string, string> = {},
|
|
61
|
+
): void {
|
|
62
|
+
response.writeHead(status, headers)
|
|
63
|
+
response.end()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Refuse an HTTP upgrade that the adapter does not accept, before handing the socket to a WebSocket server.
|
|
68
|
+
* @param socket - the raw connection.
|
|
69
|
+
* @param status - HTTP status code.
|
|
70
|
+
* @param reason - reason phrase.
|
|
71
|
+
*/
|
|
72
|
+
export function rejectUpgrade(
|
|
73
|
+
socket: Duplex,
|
|
74
|
+
status: number,
|
|
75
|
+
reason: string,
|
|
76
|
+
): void {
|
|
77
|
+
socket.write(
|
|
78
|
+
`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`,
|
|
79
|
+
)
|
|
80
|
+
socket.destroy()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* The `X-Signature` value of one event report.
|
|
85
|
+
*
|
|
86
|
+
* The upstream plugin signs the re-serialized parsed body rather than the raw bytes; this keeps that behaviour because
|
|
87
|
+
* it is what implementations in the field have been verifying against for years.
|
|
88
|
+
*
|
|
89
|
+
* @param secret - the configured `secret`.
|
|
90
|
+
* @param body - the parsed event payload.
|
|
91
|
+
* @returns `sha1=<hex digest>`.
|
|
92
|
+
*/
|
|
93
|
+
export function signatureOf(secret: string, body: unknown): string {
|
|
94
|
+
const digest = createHmac('sha1', secret)
|
|
95
|
+
.update(JSON.stringify(body))
|
|
96
|
+
.digest('hex')
|
|
97
|
+
return `sha1=${digest}`
|
|
98
|
+
}
|