@zhin.js/adapter-line 0.1.1 → 1.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/CHANGELOG.md +596 -0
- package/README.md +54 -22
- package/adapters/line.js +31 -0
- package/adapters/line.ts +36 -0
- package/agent/tools/get_group_members.ts +16 -0
- package/agent/tools/get_profile.ts +16 -0
- package/commands/endpoint/add/[id].js +3 -0
- package/commands/endpoint/add/[id].ts +3 -0
- package/commands/endpoint/list.js +3 -0
- package/commands/endpoint/list.ts +3 -0
- package/commands/endpoint/remove/[id].js +3 -0
- package/commands/endpoint/remove/[id].ts +3 -0
- package/lib/client.d.ts +33 -0
- package/lib/client.js +54 -0
- package/lib/endpoint.d.ts +41 -37
- package/lib/endpoint.js +149 -500
- package/lib/index.d.ts +4 -15
- package/lib/index.js +4 -83
- package/lib/line-endpoint-commands.d.ts +1 -0
- package/lib/line-endpoint-commands.js +17 -0
- package/lib/line-runtime-state.d.ts +1 -0
- package/lib/line-runtime-state.js +6 -0
- package/lib/protocol.d.ts +158 -0
- package/lib/protocol.js +265 -0
- package/lib/side-event-dispatch.d.ts +4 -0
- package/lib/side-event-dispatch.js +42 -0
- package/lib/webhook.d.ts +13 -0
- package/lib/webhook.js +50 -0
- package/package.json +61 -21
- package/plugin.js +14 -0
- package/schema.json +86 -0
- package/src/client.ts +87 -0
- package/src/endpoint.ts +197 -551
- package/src/index.ts +51 -100
- package/src/line-endpoint-commands.ts +18 -0
- package/src/line-runtime-state.ts +7 -0
- package/src/protocol.ts +442 -0
- package/src/side-event-dispatch.ts +54 -0
- package/src/webhook.ts +79 -0
- package/lib/adapter.d.ts +0 -15
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -20
- package/lib/adapter.js.map +0 -1
- package/lib/endpoint.d.ts.map +0 -1
- package/lib/endpoint.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/types.d.ts +0 -112
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js +0 -5
- package/lib/types.js.map +0 -1
- package/plugin.yml +0 -3
- package/src/adapter.ts +0 -29
- package/src/types.ts +0 -130
- /package/{skills/line → agent}/PERMITS.md +0 -0
- /package/{skills/line/SKILL.md → agent/skills/line.md} +0 -0
package/src/index.ts
CHANGED
|
@@ -1,100 +1,51 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
properties: {
|
|
53
|
-
userId: { type: 'string', description: 'LINE user ID (starts with U)' },
|
|
54
|
-
},
|
|
55
|
-
required: ['userId'],
|
|
56
|
-
},
|
|
57
|
-
execute: async ({ userId }: { userId: string }) => {
|
|
58
|
-
if (!userId.startsWith('U')) {
|
|
59
|
-
throw new Error(`Invalid userId "${userId}": must start with U`);
|
|
60
|
-
}
|
|
61
|
-
const response = await fetch(`${apiBaseUrl}/v2/profile/${userId}`, {
|
|
62
|
-
headers: { 'Authorization': `Bearer ${accessToken}` },
|
|
63
|
-
});
|
|
64
|
-
if (!response.ok) {
|
|
65
|
-
const errorText = await response.text();
|
|
66
|
-
throw new Error(`LINE Profile API error ${response.status}: ${errorText}`);
|
|
67
|
-
}
|
|
68
|
-
return await response.json();
|
|
69
|
-
},
|
|
70
|
-
}));
|
|
71
|
-
|
|
72
|
-
disposers.push(toolService.addTool({
|
|
73
|
-
name: 'line_get_group_members',
|
|
74
|
-
description: 'Get LINE group member IDs',
|
|
75
|
-
parameters: {
|
|
76
|
-
type: 'object',
|
|
77
|
-
properties: {
|
|
78
|
-
groupId: { type: 'string', description: 'LINE group ID (starts with G)' },
|
|
79
|
-
},
|
|
80
|
-
required: ['groupId'],
|
|
81
|
-
},
|
|
82
|
-
execute: async ({ groupId }: { groupId: string }) => {
|
|
83
|
-
if (!groupId.startsWith('G')) {
|
|
84
|
-
throw new Error(`Invalid groupId "${groupId}": must start with G`);
|
|
85
|
-
}
|
|
86
|
-
const response = await fetch(`${apiBaseUrl}/v2/bot/group/${groupId}/members/ids`, {
|
|
87
|
-
headers: { 'Authorization': `Bearer ${accessToken}` },
|
|
88
|
-
});
|
|
89
|
-
if (!response.ok) {
|
|
90
|
-
const errorText = await response.text();
|
|
91
|
-
throw new Error(`LINE Group Members API error ${response.status}: ${errorText}`);
|
|
92
|
-
}
|
|
93
|
-
return await response.json();
|
|
94
|
-
},
|
|
95
|
-
}));
|
|
96
|
-
|
|
97
|
-
return () => {
|
|
98
|
-
for (const disposer of disposers) disposer();
|
|
99
|
-
};
|
|
100
|
-
});
|
|
1
|
+
export {
|
|
2
|
+
formatInboundContent,
|
|
3
|
+
formatOutboundMessages,
|
|
4
|
+
generateMessageId,
|
|
5
|
+
isMessageEvent,
|
|
6
|
+
isPostbackEvent,
|
|
7
|
+
isValidLineRecipientId,
|
|
8
|
+
normalizeWebhookPath,
|
|
9
|
+
readTextBody,
|
|
10
|
+
resolveChannel,
|
|
11
|
+
resolveLineConfig,
|
|
12
|
+
verifySignature,
|
|
13
|
+
type LineAdapterConfig,
|
|
14
|
+
type LineApiResponse,
|
|
15
|
+
type LineChannel,
|
|
16
|
+
type LineEvent,
|
|
17
|
+
type LineFollowEvent,
|
|
18
|
+
type LineJoinEvent,
|
|
19
|
+
type LineLeaveEvent,
|
|
20
|
+
type LineMessage,
|
|
21
|
+
type LineMessageEvent,
|
|
22
|
+
type LinePostbackEvent,
|
|
23
|
+
type LinePushRequest,
|
|
24
|
+
type LineReplyMessage,
|
|
25
|
+
type LineReplyRequest,
|
|
26
|
+
type LineSource,
|
|
27
|
+
type LineUnfollowEvent,
|
|
28
|
+
type LineUser,
|
|
29
|
+
type LineWebhookBody,
|
|
30
|
+
type LineWireSegment,
|
|
31
|
+
type ResolvedLineConfig,
|
|
32
|
+
} from './protocol.js';
|
|
33
|
+
|
|
34
|
+
export {
|
|
35
|
+
LineEndpoint,
|
|
36
|
+
type LineEndpointOptions,
|
|
37
|
+
type LineFetch,
|
|
38
|
+
} from './endpoint.js';
|
|
39
|
+
|
|
40
|
+
export {
|
|
41
|
+
registerLineWebhookRoutes,
|
|
42
|
+
handleLineWebhookRequest,
|
|
43
|
+
type LineWebhookHandler,
|
|
44
|
+
} from './webhook.js';
|
|
45
|
+
|
|
46
|
+
export {
|
|
47
|
+
LineClient,
|
|
48
|
+
lineClient,
|
|
49
|
+
type LineClientEventMap,
|
|
50
|
+
type LineGroupMember,
|
|
51
|
+
} from './client.js';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `line.endpoint` 命令族:由 @zhin.js/adapter 的 createEndpointCommands 套件生成。
|
|
3
|
+
* commands/endpoint/ 下的 list / add / remove 直接默认导出这三项。
|
|
4
|
+
*/
|
|
5
|
+
import { createEndpointCommands } from 'zhin.js/adapter';
|
|
6
|
+
import { defineCommand } from 'zhin.js/command';
|
|
7
|
+
import { lineRuntimeStateToken } from './line-runtime-state.js';
|
|
8
|
+
|
|
9
|
+
export const lineEndpointCommands = createEndpointCommands({
|
|
10
|
+
adapterKey: 'line',
|
|
11
|
+
adapterDisplayName: 'LINE',
|
|
12
|
+
fields: [
|
|
13
|
+
{ key: 'channelSecret', required: true, env: true, description: 'LINE channel secret' },
|
|
14
|
+
{ key: 'channelAccessToken', required: true, env: true, description: 'LINE channel access token' },
|
|
15
|
+
],
|
|
16
|
+
running: (use) => use(lineRuntimeStateToken).endpoints.values(),
|
|
17
|
+
describeEntry: (entry) => `channelAccessToken: ${String(entry.channelAccessToken)}`,
|
|
18
|
+
}, defineCommand);
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LINE 插件实例的运行时状态:adapter create() 注册的 endpoint 列表。
|
|
3
|
+
* 由 plugin.ts setup() provide,adapter create 与 `line.endpoint` 命令共享(同一 owner generation)。
|
|
4
|
+
*/
|
|
5
|
+
import { defineEndpointRuntimeStateToken } from 'zhin.js/adapter';
|
|
6
|
+
|
|
7
|
+
export const lineRuntimeStateToken = defineEndpointRuntimeStateToken('line');
|
package/src/protocol.ts
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LINE Messaging API protocol helpers — no legacy Adapter/Endpoint / segment-mapper.
|
|
3
|
+
* Canonicalization is owned by gateway/core before endpoint.send.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
7
|
+
import type { IncomingMessage } from 'node:http';
|
|
8
|
+
import { isMediaRef } from '@zhin.js/core';
|
|
9
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
10
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
11
|
+
|
|
12
|
+
const logger = getLogger('line');
|
|
13
|
+
|
|
14
|
+
/** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
|
|
15
|
+
export interface LineAdapterConfig {
|
|
16
|
+
readonly id?: string;
|
|
17
|
+
readonly channelSecret?: string;
|
|
18
|
+
readonly channelAccessToken?: string;
|
|
19
|
+
readonly webhookPath?: string;
|
|
20
|
+
readonly apiBaseUrl?: string;
|
|
21
|
+
/** Transitional: legacy root `endpoints[]` with `context: line`. */
|
|
22
|
+
readonly endpoints?: ReadonlyArray<Partial<ResolvedLineConfig> & {
|
|
23
|
+
readonly context?: string;
|
|
24
|
+
}>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ResolvedLineConfig {
|
|
28
|
+
readonly context: 'line';
|
|
29
|
+
readonly id: string;
|
|
30
|
+
readonly channelSecret: string;
|
|
31
|
+
readonly channelAccessToken: string;
|
|
32
|
+
readonly webhookPath: string;
|
|
33
|
+
readonly apiBaseUrl: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface LineUser {
|
|
37
|
+
readonly userId: string;
|
|
38
|
+
readonly displayName?: string;
|
|
39
|
+
readonly pictureUrl?: string;
|
|
40
|
+
readonly statusMessage?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface LineMessageEvent {
|
|
44
|
+
readonly type: 'message';
|
|
45
|
+
readonly replyToken: string;
|
|
46
|
+
readonly source: LineSource;
|
|
47
|
+
readonly timestamp: number;
|
|
48
|
+
readonly message: LineMessage;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface LineFollowEvent {
|
|
52
|
+
readonly type: 'follow';
|
|
53
|
+
readonly replyToken: string;
|
|
54
|
+
readonly source: LineSource;
|
|
55
|
+
readonly timestamp: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface LineUnfollowEvent {
|
|
59
|
+
readonly type: 'unfollow';
|
|
60
|
+
readonly source: LineSource;
|
|
61
|
+
readonly timestamp: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface LineJoinEvent {
|
|
65
|
+
readonly type: 'join';
|
|
66
|
+
readonly replyToken: string;
|
|
67
|
+
readonly source: LineSource;
|
|
68
|
+
readonly timestamp: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface LineLeaveEvent {
|
|
72
|
+
readonly type: 'leave';
|
|
73
|
+
readonly source: LineSource;
|
|
74
|
+
readonly timestamp: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface LinePostbackEvent {
|
|
78
|
+
readonly type: 'postback';
|
|
79
|
+
readonly replyToken: string;
|
|
80
|
+
readonly source: LineSource;
|
|
81
|
+
readonly timestamp: number;
|
|
82
|
+
readonly postback: {
|
|
83
|
+
readonly data: string;
|
|
84
|
+
readonly params?: Record<string, string>;
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export type LineEvent =
|
|
89
|
+
| LineMessageEvent
|
|
90
|
+
| LineFollowEvent
|
|
91
|
+
| LineUnfollowEvent
|
|
92
|
+
| LineJoinEvent
|
|
93
|
+
| LineLeaveEvent
|
|
94
|
+
| LinePostbackEvent;
|
|
95
|
+
|
|
96
|
+
export interface LineSource {
|
|
97
|
+
readonly type: 'user' | 'group' | 'room';
|
|
98
|
+
readonly userId?: string;
|
|
99
|
+
readonly groupId?: string;
|
|
100
|
+
readonly roomId?: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface LineMessage {
|
|
104
|
+
readonly id: string;
|
|
105
|
+
readonly type: 'text' | 'image' | 'video' | 'audio' | 'file' | 'location' | 'sticker';
|
|
106
|
+
readonly text?: string;
|
|
107
|
+
readonly fileName?: string;
|
|
108
|
+
readonly fileSize?: number;
|
|
109
|
+
readonly title?: string;
|
|
110
|
+
readonly address?: string;
|
|
111
|
+
readonly latitude?: number;
|
|
112
|
+
readonly longitude?: number;
|
|
113
|
+
readonly packageId?: string;
|
|
114
|
+
readonly stickerId?: string;
|
|
115
|
+
readonly stickerResourceType?: string;
|
|
116
|
+
readonly duration?: number;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface LineWebhookBody {
|
|
120
|
+
readonly destination: string;
|
|
121
|
+
readonly events: readonly LineEvent[];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface LineReplyMessage {
|
|
125
|
+
readonly type: 'text' | 'image' | 'video' | 'audio' | 'location' | 'sticker' | 'flex';
|
|
126
|
+
readonly text?: string;
|
|
127
|
+
readonly originalContentUrl?: string;
|
|
128
|
+
readonly previewImageUrl?: string;
|
|
129
|
+
readonly packageId?: string;
|
|
130
|
+
readonly stickerId?: string;
|
|
131
|
+
readonly title?: string;
|
|
132
|
+
readonly address?: string;
|
|
133
|
+
readonly latitude?: number;
|
|
134
|
+
readonly longitude?: number;
|
|
135
|
+
readonly duration?: number;
|
|
136
|
+
readonly altText?: string;
|
|
137
|
+
readonly contents?: Record<string, unknown>;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface LineReplyRequest {
|
|
141
|
+
readonly replyToken: string;
|
|
142
|
+
readonly messages: readonly LineReplyMessage[];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export interface LinePushRequest {
|
|
146
|
+
readonly to: string;
|
|
147
|
+
readonly messages: readonly LineReplyMessage[];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface LineApiResponse {
|
|
151
|
+
readonly sentMessages?: ReadonlyArray<{ readonly id: string; readonly quoteToken?: string }>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface LineWireSegment {
|
|
155
|
+
readonly type: string;
|
|
156
|
+
readonly data?: Record<string, unknown>;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface LineChannel {
|
|
160
|
+
readonly channelType: 'private' | 'group' | 'channel';
|
|
161
|
+
readonly channelId: string;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function resolveLineConfig(config: LineAdapterConfig = {}): ResolvedLineConfig {
|
|
165
|
+
const entry = config.endpoints?.find((item) => item.context === 'line');
|
|
166
|
+
const channelSecret = config.channelSecret
|
|
167
|
+
?? entry?.channelSecret
|
|
168
|
+
?? process.env.LINE_CHANNEL_SECRET;
|
|
169
|
+
const channelAccessToken = config.channelAccessToken
|
|
170
|
+
?? entry?.channelAccessToken
|
|
171
|
+
?? process.env.LINE_CHANNEL_ACCESS_TOKEN;
|
|
172
|
+
if (!channelSecret || !channelAccessToken) {
|
|
173
|
+
throw new TypeError(
|
|
174
|
+
'LINE adapter requires channelSecret + channelAccessToken (plugins.<key> or endpoints with context: line)',
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
const id = (typeof config.id === 'string' && config.id)
|
|
178
|
+
|| (typeof entry?.id === 'string' && entry.id)
|
|
179
|
+
|| process.env.LINE_BOT_NAME
|
|
180
|
+
|| 'line-bot';
|
|
181
|
+
const webhookPath = normalizeWebhookPath(
|
|
182
|
+
config.webhookPath ?? entry?.webhookPath ?? '/line/webhook',
|
|
183
|
+
);
|
|
184
|
+
const apiBaseUrl = (config.apiBaseUrl ?? entry?.apiBaseUrl ?? 'https://api.line.me').replace(/\/$/, '');
|
|
185
|
+
return {
|
|
186
|
+
context: 'line',
|
|
187
|
+
id,
|
|
188
|
+
channelSecret,
|
|
189
|
+
channelAccessToken,
|
|
190
|
+
webhookPath,
|
|
191
|
+
apiBaseUrl,
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function normalizeWebhookPath(path: string): string {
|
|
196
|
+
const trimmed = path.trim() || '/line/webhook';
|
|
197
|
+
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function isMessageEvent(event: LineEvent): event is LineMessageEvent {
|
|
201
|
+
return event.type === 'message' && 'message' in event && (event as LineMessageEvent).message != null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function isLineLifecycleEvent(event: LineEvent): boolean {
|
|
205
|
+
return event.type === 'follow'
|
|
206
|
+
|| event.type === 'unfollow'
|
|
207
|
+
|| event.type === 'join'
|
|
208
|
+
|| event.type === 'leave';
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function isPostbackEvent(event: LineEvent): event is LinePostbackEvent {
|
|
212
|
+
return event.type === 'postback' && 'postback' in event;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export function resolveChannel(source: LineSource): LineChannel {
|
|
216
|
+
switch (source.type) {
|
|
217
|
+
case 'user':
|
|
218
|
+
return { channelType: 'private', channelId: source.userId || '' };
|
|
219
|
+
case 'group':
|
|
220
|
+
return { channelType: 'group', channelId: source.groupId || '' };
|
|
221
|
+
case 'room':
|
|
222
|
+
return { channelType: 'channel', channelId: source.roomId || '' };
|
|
223
|
+
default:
|
|
224
|
+
return { channelType: 'private', channelId: '' };
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 入站归一化 → ConversationRef:LINE user → private、group → group、room → channel。
|
|
230
|
+
* LINE 没有 guild/频道容器概念,无 parent;recipient id 前缀(U/G/R)自带场景信息。
|
|
231
|
+
*/
|
|
232
|
+
export function lineInboundConversation(endpointKey: string, source: LineSource): ConversationRef {
|
|
233
|
+
const channel = resolveChannel(source);
|
|
234
|
+
return {
|
|
235
|
+
endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
|
|
236
|
+
kind: channel.channelType,
|
|
237
|
+
id: channel.channelId,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function generateMessageId(event: LineEvent): string {
|
|
242
|
+
if (isMessageEvent(event) && event.message?.id) return event.message.id;
|
|
243
|
+
return `${event.type}-${event.timestamp}`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Build inbound text for OutboundMessageService.receive. */
|
|
247
|
+
export function formatInboundContent(event: LineEvent): string {
|
|
248
|
+
if (isMessageEvent(event)) {
|
|
249
|
+
const msg = event.message;
|
|
250
|
+
switch (msg.type) {
|
|
251
|
+
case 'text':
|
|
252
|
+
return msg.text || '';
|
|
253
|
+
case 'location':
|
|
254
|
+
return msg.address || `[location: ${msg.latitude},${msg.longitude}]`;
|
|
255
|
+
case 'image':
|
|
256
|
+
return '[image]';
|
|
257
|
+
case 'video':
|
|
258
|
+
return '[video]';
|
|
259
|
+
case 'audio':
|
|
260
|
+
return '[audio]';
|
|
261
|
+
case 'file':
|
|
262
|
+
return msg.fileName ? `[file: ${msg.fileName}]` : '[file]';
|
|
263
|
+
case 'sticker':
|
|
264
|
+
return `[sticker: ${msg.packageId}/${msg.stickerId}]`;
|
|
265
|
+
default:
|
|
266
|
+
return `[${(msg as LineMessage).type}]`;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
if (event.type === 'follow') return '[follow]';
|
|
270
|
+
if (event.type === 'join') return '[join]';
|
|
271
|
+
if (event.type === 'unfollow') return '[unfollow]';
|
|
272
|
+
if (event.type === 'leave') return '[leave]';
|
|
273
|
+
if (event.type === 'postback') return `[postback: ${event.postback.data}]`;
|
|
274
|
+
return '';
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function verifySignature(
|
|
278
|
+
channelSecret: string,
|
|
279
|
+
body: string,
|
|
280
|
+
signature: string,
|
|
281
|
+
): boolean {
|
|
282
|
+
const hmac = createHmac('sha256', channelSecret);
|
|
283
|
+
hmac.update(body, 'utf-8');
|
|
284
|
+
const computedSignature = hmac.digest('base64');
|
|
285
|
+
const sigBuf = Buffer.from(signature);
|
|
286
|
+
const computedBuf = Buffer.from(computedSignature);
|
|
287
|
+
if (sigBuf.length !== computedBuf.length) return false;
|
|
288
|
+
return timingSafeEqual(sigBuf, computedBuf);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export function isValidLineRecipientId(id: string): boolean {
|
|
292
|
+
return /^[UGR]/.test(id);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function buildTextMessage(text: string): LineReplyMessage {
|
|
296
|
+
const truncated = text.length > 5000 ? `${text.slice(0, 4997)}...` : text;
|
|
297
|
+
return { type: 'text', text: truncated };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* 解析 image/audio/video 段的投递源(canonical MediaRef 唯一来源)。
|
|
302
|
+
* LINE Messaging API 媒体消息仅消费远程 HTTPS URL(无上传通道),
|
|
303
|
+
* 因此只有 kind=url 可投递;base64 / path / file 一律 warn + 丢弃。
|
|
304
|
+
*/
|
|
305
|
+
function resolveMediaUrl(seg: LineWireSegment): string | undefined {
|
|
306
|
+
const media = (seg.data ?? {}).media;
|
|
307
|
+
if (!isMediaRef(media)) {
|
|
308
|
+
logger.warn(formatCompact({
|
|
309
|
+
op: 'line_outbound_media_dropped',
|
|
310
|
+
type: seg.type,
|
|
311
|
+
reason: 'missing_media_ref',
|
|
312
|
+
}));
|
|
313
|
+
return undefined;
|
|
314
|
+
}
|
|
315
|
+
if (media.kind !== 'url') {
|
|
316
|
+
logger.warn(formatCompact({
|
|
317
|
+
op: 'line_outbound_media_dropped',
|
|
318
|
+
type: seg.type,
|
|
319
|
+
reason: 'unsupported_media_kind',
|
|
320
|
+
kind: media.kind,
|
|
321
|
+
}));
|
|
322
|
+
return undefined;
|
|
323
|
+
}
|
|
324
|
+
return media.value;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Wire-encode an already-rendered outbound payload into LINE Reply/Push messages.
|
|
329
|
+
* Segment canonicalization is intentionally not done here.
|
|
330
|
+
*/
|
|
331
|
+
export function formatOutboundMessages(payload: unknown): LineReplyMessage[] {
|
|
332
|
+
if (typeof payload === 'string') {
|
|
333
|
+
return [buildTextMessage(payload)];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const items: Array<string | LineWireSegment> = Array.isArray(payload)
|
|
337
|
+
? payload as Array<string | LineWireSegment>
|
|
338
|
+
: payload && typeof payload === 'object' && 'type' in (payload as object)
|
|
339
|
+
? [payload as LineWireSegment]
|
|
340
|
+
: [];
|
|
341
|
+
|
|
342
|
+
if (items.length === 0) {
|
|
343
|
+
const text = payload == null
|
|
344
|
+
? ''
|
|
345
|
+
: typeof payload === 'object'
|
|
346
|
+
? JSON.stringify(payload)
|
|
347
|
+
: String(payload);
|
|
348
|
+
return [buildTextMessage(text)];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const messages: LineReplyMessage[] = [];
|
|
352
|
+
for (const item of items) {
|
|
353
|
+
if (typeof item === 'string') {
|
|
354
|
+
messages.push(buildTextMessage(item));
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
const data = item.data ?? {};
|
|
358
|
+
switch (item.type) {
|
|
359
|
+
case 'text':
|
|
360
|
+
messages.push(buildTextMessage(String(data.text ?? data.content ?? '')));
|
|
361
|
+
break;
|
|
362
|
+
case 'at':
|
|
363
|
+
if (data.id) {
|
|
364
|
+
messages.push(buildTextMessage(`@${String(data.name || data.id)}`));
|
|
365
|
+
}
|
|
366
|
+
break;
|
|
367
|
+
case 'image': {
|
|
368
|
+
const url = resolveMediaUrl(item);
|
|
369
|
+
if (url) {
|
|
370
|
+
messages.push({
|
|
371
|
+
type: 'image',
|
|
372
|
+
originalContentUrl: url,
|
|
373
|
+
previewImageUrl: url,
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
break;
|
|
377
|
+
}
|
|
378
|
+
case 'video': {
|
|
379
|
+
const url = resolveMediaUrl(item);
|
|
380
|
+
if (url) {
|
|
381
|
+
messages.push({
|
|
382
|
+
type: 'video',
|
|
383
|
+
originalContentUrl: url,
|
|
384
|
+
previewImageUrl: typeof data.previewUrl === 'string' ? data.previewUrl : url,
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
case 'audio': {
|
|
390
|
+
const url = resolveMediaUrl(item);
|
|
391
|
+
if (url) {
|
|
392
|
+
messages.push({
|
|
393
|
+
type: 'audio',
|
|
394
|
+
originalContentUrl: url,
|
|
395
|
+
duration: typeof data.duration === 'number' ? data.duration : 0,
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
case 'location':
|
|
401
|
+
messages.push({
|
|
402
|
+
type: 'location',
|
|
403
|
+
title: String(data.title || 'Location'),
|
|
404
|
+
address: String(data.address || ''),
|
|
405
|
+
latitude: typeof data.latitude === 'number' ? data.latitude : 0,
|
|
406
|
+
longitude: typeof data.longitude === 'number' ? data.longitude : 0,
|
|
407
|
+
});
|
|
408
|
+
break;
|
|
409
|
+
case 'sticker':
|
|
410
|
+
messages.push({
|
|
411
|
+
type: 'sticker',
|
|
412
|
+
packageId: String(data.package_id || '1'),
|
|
413
|
+
stickerId: String(data.sticker_id || '1'),
|
|
414
|
+
});
|
|
415
|
+
break;
|
|
416
|
+
default:
|
|
417
|
+
messages.push(buildTextMessage(`[${item.type}]`));
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// LINE allows at most 5 messages per Reply/Push request.
|
|
422
|
+
return messages.slice(0, 5);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export async function readTextBody(
|
|
426
|
+
request: IncomingMessage,
|
|
427
|
+
options: { readonly limit?: number } = {},
|
|
428
|
+
): Promise<string> {
|
|
429
|
+
const limit = options.limit ?? 1_048_576;
|
|
430
|
+
const chunks: Buffer[] = [];
|
|
431
|
+
let size = 0;
|
|
432
|
+
for await (const chunk of request) {
|
|
433
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
434
|
+
size += buffer.length;
|
|
435
|
+
if (size > limit) {
|
|
436
|
+
request.destroy();
|
|
437
|
+
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
438
|
+
}
|
|
439
|
+
chunks.push(buffer);
|
|
440
|
+
}
|
|
441
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
442
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { buildNotice, senderFromId } from '@zhin.js/core';
|
|
2
|
+
import type { EndpointEventEmitter } from 'zhin.js/adapter';
|
|
3
|
+
import { formatCompact, type getAdapterLogger } from '@zhin.js/logger';
|
|
4
|
+
import {
|
|
5
|
+
isLineLifecycleEvent,
|
|
6
|
+
lineInboundConversation,
|
|
7
|
+
type LineEvent,
|
|
8
|
+
} from './protocol.js';
|
|
9
|
+
|
|
10
|
+
function mapLineLifecycleParts(type: LineEvent['type']): { scene_type: string; sub_type: string } {
|
|
11
|
+
switch (type) {
|
|
12
|
+
case 'follow':
|
|
13
|
+
return { scene_type: 'friend', sub_type: 'increase' };
|
|
14
|
+
case 'unfollow':
|
|
15
|
+
return { scene_type: 'friend', sub_type: 'decrease' };
|
|
16
|
+
case 'join':
|
|
17
|
+
return { scene_type: 'group', sub_type: 'member_increase' };
|
|
18
|
+
case 'leave':
|
|
19
|
+
return { scene_type: 'group', sub_type: 'member_decrease' };
|
|
20
|
+
default:
|
|
21
|
+
return { scene_type: 'line', sub_type: type };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function receiveLineSideEvent(
|
|
26
|
+
emit: EndpointEventEmitter,
|
|
27
|
+
endpointKey: string,
|
|
28
|
+
configId: string,
|
|
29
|
+
event: LineEvent,
|
|
30
|
+
logger: ReturnType<typeof getAdapterLogger>,
|
|
31
|
+
): void {
|
|
32
|
+
if (!isLineLifecycleEvent(event)) return;
|
|
33
|
+
const parts = mapLineLifecycleParts(event.type);
|
|
34
|
+
const conversation = lineInboundConversation(endpointKey, event.source);
|
|
35
|
+
const userId = event.source.userId || conversation.id;
|
|
36
|
+
void emit('notice.receive', buildNotice(event, {
|
|
37
|
+
$id: `line:${event.type}:${event.timestamp}:${userId}`,
|
|
38
|
+
$adapter: 'line' as never,
|
|
39
|
+
$endpoint: configId,
|
|
40
|
+
$type: 'notice',
|
|
41
|
+
$scene_id: conversation.id,
|
|
42
|
+
$scene_type: parts.scene_type,
|
|
43
|
+
$sub_type: parts.sub_type,
|
|
44
|
+
$actor: senderFromId(userId),
|
|
45
|
+
$timestamp: event.timestamp,
|
|
46
|
+
})).catch((err) => {
|
|
47
|
+
logger.warn(formatCompact({
|
|
48
|
+
op: 'line_side_event_failed',
|
|
49
|
+
endpoint: configId,
|
|
50
|
+
event: event.type,
|
|
51
|
+
error: err instanceof Error ? err.message : String(err),
|
|
52
|
+
}));
|
|
53
|
+
});
|
|
54
|
+
}
|