@zhin.js/adapter-line 0.1.0 → 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/lib/index.d.ts
CHANGED
|
@@ -1,15 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
router: import('@zhin.js/host-router').Router;
|
|
6
|
-
}
|
|
7
|
-
}
|
|
8
|
-
interface Adapters {
|
|
9
|
-
line: LineAdapter;
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
export * from './types.js';
|
|
13
|
-
export { LineEndpoint } from './endpoint.js';
|
|
14
|
-
export { LineAdapter } from './adapter.js';
|
|
15
|
-
//# sourceMappingURL=index.d.ts.map
|
|
1
|
+
export { formatInboundContent, formatOutboundMessages, generateMessageId, isMessageEvent, isPostbackEvent, isValidLineRecipientId, normalizeWebhookPath, readTextBody, resolveChannel, resolveLineConfig, verifySignature, type LineAdapterConfig, type LineApiResponse, type LineChannel, type LineEvent, type LineFollowEvent, type LineJoinEvent, type LineLeaveEvent, type LineMessage, type LineMessageEvent, type LinePostbackEvent, type LinePushRequest, type LineReplyMessage, type LineReplyRequest, type LineSource, type LineUnfollowEvent, type LineUser, type LineWebhookBody, type LineWireSegment, type ResolvedLineConfig, } from './protocol.js';
|
|
2
|
+
export { LineEndpoint, type LineEndpointOptions, type LineFetch, } from './endpoint.js';
|
|
3
|
+
export { registerLineWebhookRoutes, handleLineWebhookRequest, type LineWebhookHandler, } from './webhook.js';
|
|
4
|
+
export { LineClient, lineClient, type LineClientEventMap, type LineGroupMember, } from './client.js';
|
package/lib/index.js
CHANGED
|
@@ -1,83 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { LineAdapter } from './adapter.js';
|
|
6
|
-
export * from './types.js';
|
|
7
|
-
export { LineEndpoint } from './endpoint.js';
|
|
8
|
-
export { LineAdapter } from './adapter.js';
|
|
9
|
-
const plugin = usePlugin();
|
|
10
|
-
const { provide, useContext } = plugin;
|
|
11
|
-
useContext('router', (router) => {
|
|
12
|
-
provide({
|
|
13
|
-
name: 'line',
|
|
14
|
-
description: 'LINE Messaging API Endpoint Adapter',
|
|
15
|
-
mounted: async (p) => {
|
|
16
|
-
const adapter = new LineAdapter(p, router);
|
|
17
|
-
await adapter.start();
|
|
18
|
-
return adapter;
|
|
19
|
-
},
|
|
20
|
-
dispose: async (adapter) => {
|
|
21
|
-
await adapter.stop();
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
});
|
|
25
|
-
// L11: Register LINE-specific tools
|
|
26
|
-
useContext('tool', 'line', (toolService, lineAdapter) => {
|
|
27
|
-
const accessToken = lineAdapter.endpoints.values().next().value?.$config?.channelAccessToken;
|
|
28
|
-
const apiBaseUrl = lineAdapter.endpoints.values().next().value?.$config?.apiBaseUrl || 'https://api.line.me';
|
|
29
|
-
const disposers = [];
|
|
30
|
-
disposers.push(toolService.addTool({
|
|
31
|
-
name: 'line_get_profile',
|
|
32
|
-
description: 'Get LINE user profile by userId',
|
|
33
|
-
parameters: {
|
|
34
|
-
type: 'object',
|
|
35
|
-
properties: {
|
|
36
|
-
userId: { type: 'string', description: 'LINE user ID (starts with U)' },
|
|
37
|
-
},
|
|
38
|
-
required: ['userId'],
|
|
39
|
-
},
|
|
40
|
-
execute: async ({ userId }) => {
|
|
41
|
-
if (!userId.startsWith('U')) {
|
|
42
|
-
throw new Error(`Invalid userId "${userId}": must start with U`);
|
|
43
|
-
}
|
|
44
|
-
const response = await fetch(`${apiBaseUrl}/v2/profile/${userId}`, {
|
|
45
|
-
headers: { 'Authorization': `Bearer ${accessToken}` },
|
|
46
|
-
});
|
|
47
|
-
if (!response.ok) {
|
|
48
|
-
const errorText = await response.text();
|
|
49
|
-
throw new Error(`LINE Profile API error ${response.status}: ${errorText}`);
|
|
50
|
-
}
|
|
51
|
-
return await response.json();
|
|
52
|
-
},
|
|
53
|
-
}));
|
|
54
|
-
disposers.push(toolService.addTool({
|
|
55
|
-
name: 'line_get_group_members',
|
|
56
|
-
description: 'Get LINE group member IDs',
|
|
57
|
-
parameters: {
|
|
58
|
-
type: 'object',
|
|
59
|
-
properties: {
|
|
60
|
-
groupId: { type: 'string', description: 'LINE group ID (starts with G)' },
|
|
61
|
-
},
|
|
62
|
-
required: ['groupId'],
|
|
63
|
-
},
|
|
64
|
-
execute: async ({ groupId }) => {
|
|
65
|
-
if (!groupId.startsWith('G')) {
|
|
66
|
-
throw new Error(`Invalid groupId "${groupId}": must start with G`);
|
|
67
|
-
}
|
|
68
|
-
const response = await fetch(`${apiBaseUrl}/v2/bot/group/${groupId}/members/ids`, {
|
|
69
|
-
headers: { 'Authorization': `Bearer ${accessToken}` },
|
|
70
|
-
});
|
|
71
|
-
if (!response.ok) {
|
|
72
|
-
const errorText = await response.text();
|
|
73
|
-
throw new Error(`LINE Group Members API error ${response.status}: ${errorText}`);
|
|
74
|
-
}
|
|
75
|
-
return await response.json();
|
|
76
|
-
},
|
|
77
|
-
}));
|
|
78
|
-
return () => {
|
|
79
|
-
for (const disposer of disposers)
|
|
80
|
-
disposer();
|
|
81
|
-
};
|
|
82
|
-
});
|
|
83
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
export { formatInboundContent, formatOutboundMessages, generateMessageId, isMessageEvent, isPostbackEvent, isValidLineRecipientId, normalizeWebhookPath, readTextBody, resolveChannel, resolveLineConfig, verifySignature, } from './protocol.js';
|
|
2
|
+
export { LineEndpoint, } from './endpoint.js';
|
|
3
|
+
export { registerLineWebhookRoutes, handleLineWebhookRequest, } from './webhook.js';
|
|
4
|
+
export { LineClient, lineClient, } from './client.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const lineEndpointCommands: import("@zhin.js/adapter").EndpointCommands<Readonly<import("@zhin.js/command").CommandDefinition<unknown, unknown, import("@zhin.js/command").CommandMessage, string | undefined>>>;
|
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
export const lineEndpointCommands = createEndpointCommands({
|
|
9
|
+
adapterKey: 'line',
|
|
10
|
+
adapterDisplayName: 'LINE',
|
|
11
|
+
fields: [
|
|
12
|
+
{ key: 'channelSecret', required: true, env: true, description: 'LINE channel secret' },
|
|
13
|
+
{ key: 'channelAccessToken', required: true, env: true, description: 'LINE channel access token' },
|
|
14
|
+
],
|
|
15
|
+
running: (use) => use(lineRuntimeStateToken).endpoints.values(),
|
|
16
|
+
describeEntry: (entry) => `channelAccessToken: ${String(entry.channelAccessToken)}`,
|
|
17
|
+
}, defineCommand);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const lineRuntimeStateToken: import("zhin.js").Token<import("@zhin.js/adapter").EndpointRuntimeState>;
|
|
@@ -0,0 +1,6 @@
|
|
|
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
|
+
export const lineRuntimeStateToken = defineEndpointRuntimeStateToken('line');
|
|
@@ -0,0 +1,158 @@
|
|
|
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
|
+
import type { IncomingMessage } from 'node:http';
|
|
6
|
+
import type { ConversationRef } from '@zhin.js/im-contract';
|
|
7
|
+
/** Plugin Runtime owner config (`plugins.<instanceKey>` / schema.json). */
|
|
8
|
+
export interface LineAdapterConfig {
|
|
9
|
+
readonly id?: string;
|
|
10
|
+
readonly channelSecret?: string;
|
|
11
|
+
readonly channelAccessToken?: string;
|
|
12
|
+
readonly webhookPath?: string;
|
|
13
|
+
readonly apiBaseUrl?: string;
|
|
14
|
+
/** Transitional: legacy root `endpoints[]` with `context: line`. */
|
|
15
|
+
readonly endpoints?: ReadonlyArray<Partial<ResolvedLineConfig> & {
|
|
16
|
+
readonly context?: string;
|
|
17
|
+
}>;
|
|
18
|
+
}
|
|
19
|
+
export interface ResolvedLineConfig {
|
|
20
|
+
readonly context: 'line';
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly channelSecret: string;
|
|
23
|
+
readonly channelAccessToken: string;
|
|
24
|
+
readonly webhookPath: string;
|
|
25
|
+
readonly apiBaseUrl: string;
|
|
26
|
+
}
|
|
27
|
+
export interface LineUser {
|
|
28
|
+
readonly userId: string;
|
|
29
|
+
readonly displayName?: string;
|
|
30
|
+
readonly pictureUrl?: string;
|
|
31
|
+
readonly statusMessage?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface LineMessageEvent {
|
|
34
|
+
readonly type: 'message';
|
|
35
|
+
readonly replyToken: string;
|
|
36
|
+
readonly source: LineSource;
|
|
37
|
+
readonly timestamp: number;
|
|
38
|
+
readonly message: LineMessage;
|
|
39
|
+
}
|
|
40
|
+
export interface LineFollowEvent {
|
|
41
|
+
readonly type: 'follow';
|
|
42
|
+
readonly replyToken: string;
|
|
43
|
+
readonly source: LineSource;
|
|
44
|
+
readonly timestamp: number;
|
|
45
|
+
}
|
|
46
|
+
export interface LineUnfollowEvent {
|
|
47
|
+
readonly type: 'unfollow';
|
|
48
|
+
readonly source: LineSource;
|
|
49
|
+
readonly timestamp: number;
|
|
50
|
+
}
|
|
51
|
+
export interface LineJoinEvent {
|
|
52
|
+
readonly type: 'join';
|
|
53
|
+
readonly replyToken: string;
|
|
54
|
+
readonly source: LineSource;
|
|
55
|
+
readonly timestamp: number;
|
|
56
|
+
}
|
|
57
|
+
export interface LineLeaveEvent {
|
|
58
|
+
readonly type: 'leave';
|
|
59
|
+
readonly source: LineSource;
|
|
60
|
+
readonly timestamp: number;
|
|
61
|
+
}
|
|
62
|
+
export interface LinePostbackEvent {
|
|
63
|
+
readonly type: 'postback';
|
|
64
|
+
readonly replyToken: string;
|
|
65
|
+
readonly source: LineSource;
|
|
66
|
+
readonly timestamp: number;
|
|
67
|
+
readonly postback: {
|
|
68
|
+
readonly data: string;
|
|
69
|
+
readonly params?: Record<string, string>;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
export type LineEvent = LineMessageEvent | LineFollowEvent | LineUnfollowEvent | LineJoinEvent | LineLeaveEvent | LinePostbackEvent;
|
|
73
|
+
export interface LineSource {
|
|
74
|
+
readonly type: 'user' | 'group' | 'room';
|
|
75
|
+
readonly userId?: string;
|
|
76
|
+
readonly groupId?: string;
|
|
77
|
+
readonly roomId?: string;
|
|
78
|
+
}
|
|
79
|
+
export interface LineMessage {
|
|
80
|
+
readonly id: string;
|
|
81
|
+
readonly type: 'text' | 'image' | 'video' | 'audio' | 'file' | 'location' | 'sticker';
|
|
82
|
+
readonly text?: string;
|
|
83
|
+
readonly fileName?: string;
|
|
84
|
+
readonly fileSize?: number;
|
|
85
|
+
readonly title?: string;
|
|
86
|
+
readonly address?: string;
|
|
87
|
+
readonly latitude?: number;
|
|
88
|
+
readonly longitude?: number;
|
|
89
|
+
readonly packageId?: string;
|
|
90
|
+
readonly stickerId?: string;
|
|
91
|
+
readonly stickerResourceType?: string;
|
|
92
|
+
readonly duration?: number;
|
|
93
|
+
}
|
|
94
|
+
export interface LineWebhookBody {
|
|
95
|
+
readonly destination: string;
|
|
96
|
+
readonly events: readonly LineEvent[];
|
|
97
|
+
}
|
|
98
|
+
export interface LineReplyMessage {
|
|
99
|
+
readonly type: 'text' | 'image' | 'video' | 'audio' | 'location' | 'sticker' | 'flex';
|
|
100
|
+
readonly text?: string;
|
|
101
|
+
readonly originalContentUrl?: string;
|
|
102
|
+
readonly previewImageUrl?: string;
|
|
103
|
+
readonly packageId?: string;
|
|
104
|
+
readonly stickerId?: string;
|
|
105
|
+
readonly title?: string;
|
|
106
|
+
readonly address?: string;
|
|
107
|
+
readonly latitude?: number;
|
|
108
|
+
readonly longitude?: number;
|
|
109
|
+
readonly duration?: number;
|
|
110
|
+
readonly altText?: string;
|
|
111
|
+
readonly contents?: Record<string, unknown>;
|
|
112
|
+
}
|
|
113
|
+
export interface LineReplyRequest {
|
|
114
|
+
readonly replyToken: string;
|
|
115
|
+
readonly messages: readonly LineReplyMessage[];
|
|
116
|
+
}
|
|
117
|
+
export interface LinePushRequest {
|
|
118
|
+
readonly to: string;
|
|
119
|
+
readonly messages: readonly LineReplyMessage[];
|
|
120
|
+
}
|
|
121
|
+
export interface LineApiResponse {
|
|
122
|
+
readonly sentMessages?: ReadonlyArray<{
|
|
123
|
+
readonly id: string;
|
|
124
|
+
readonly quoteToken?: string;
|
|
125
|
+
}>;
|
|
126
|
+
}
|
|
127
|
+
export interface LineWireSegment {
|
|
128
|
+
readonly type: string;
|
|
129
|
+
readonly data?: Record<string, unknown>;
|
|
130
|
+
}
|
|
131
|
+
export interface LineChannel {
|
|
132
|
+
readonly channelType: 'private' | 'group' | 'channel';
|
|
133
|
+
readonly channelId: string;
|
|
134
|
+
}
|
|
135
|
+
export declare function resolveLineConfig(config?: LineAdapterConfig): ResolvedLineConfig;
|
|
136
|
+
export declare function normalizeWebhookPath(path: string): string;
|
|
137
|
+
export declare function isMessageEvent(event: LineEvent): event is LineMessageEvent;
|
|
138
|
+
export declare function isLineLifecycleEvent(event: LineEvent): boolean;
|
|
139
|
+
export declare function isPostbackEvent(event: LineEvent): event is LinePostbackEvent;
|
|
140
|
+
export declare function resolveChannel(source: LineSource): LineChannel;
|
|
141
|
+
/**
|
|
142
|
+
* 入站归一化 → ConversationRef:LINE user → private、group → group、room → channel。
|
|
143
|
+
* LINE 没有 guild/频道容器概念,无 parent;recipient id 前缀(U/G/R)自带场景信息。
|
|
144
|
+
*/
|
|
145
|
+
export declare function lineInboundConversation(endpointKey: string, source: LineSource): ConversationRef;
|
|
146
|
+
export declare function generateMessageId(event: LineEvent): string;
|
|
147
|
+
/** Build inbound text for OutboundMessageService.receive. */
|
|
148
|
+
export declare function formatInboundContent(event: LineEvent): string;
|
|
149
|
+
export declare function verifySignature(channelSecret: string, body: string, signature: string): boolean;
|
|
150
|
+
export declare function isValidLineRecipientId(id: string): boolean;
|
|
151
|
+
/**
|
|
152
|
+
* Wire-encode an already-rendered outbound payload into LINE Reply/Push messages.
|
|
153
|
+
* Segment canonicalization is intentionally not done here.
|
|
154
|
+
*/
|
|
155
|
+
export declare function formatOutboundMessages(payload: unknown): LineReplyMessage[];
|
|
156
|
+
export declare function readTextBody(request: IncomingMessage, options?: {
|
|
157
|
+
readonly limit?: number;
|
|
158
|
+
}): Promise<string>;
|
package/lib/protocol.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
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
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
6
|
+
import { isMediaRef } from '@zhin.js/core';
|
|
7
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
8
|
+
const logger = getLogger('line');
|
|
9
|
+
export function resolveLineConfig(config = {}) {
|
|
10
|
+
const entry = config.endpoints?.find((item) => item.context === 'line');
|
|
11
|
+
const channelSecret = config.channelSecret
|
|
12
|
+
?? entry?.channelSecret
|
|
13
|
+
?? process.env.LINE_CHANNEL_SECRET;
|
|
14
|
+
const channelAccessToken = config.channelAccessToken
|
|
15
|
+
?? entry?.channelAccessToken
|
|
16
|
+
?? process.env.LINE_CHANNEL_ACCESS_TOKEN;
|
|
17
|
+
if (!channelSecret || !channelAccessToken) {
|
|
18
|
+
throw new TypeError('LINE adapter requires channelSecret + channelAccessToken (plugins.<key> or endpoints with context: line)');
|
|
19
|
+
}
|
|
20
|
+
const id = (typeof config.id === 'string' && config.id)
|
|
21
|
+
|| (typeof entry?.id === 'string' && entry.id)
|
|
22
|
+
|| process.env.LINE_BOT_NAME
|
|
23
|
+
|| 'line-bot';
|
|
24
|
+
const webhookPath = normalizeWebhookPath(config.webhookPath ?? entry?.webhookPath ?? '/line/webhook');
|
|
25
|
+
const apiBaseUrl = (config.apiBaseUrl ?? entry?.apiBaseUrl ?? 'https://api.line.me').replace(/\/$/, '');
|
|
26
|
+
return {
|
|
27
|
+
context: 'line',
|
|
28
|
+
id,
|
|
29
|
+
channelSecret,
|
|
30
|
+
channelAccessToken,
|
|
31
|
+
webhookPath,
|
|
32
|
+
apiBaseUrl,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export function normalizeWebhookPath(path) {
|
|
36
|
+
const trimmed = path.trim() || '/line/webhook';
|
|
37
|
+
return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
|
|
38
|
+
}
|
|
39
|
+
export function isMessageEvent(event) {
|
|
40
|
+
return event.type === 'message' && 'message' in event && event.message != null;
|
|
41
|
+
}
|
|
42
|
+
export function isLineLifecycleEvent(event) {
|
|
43
|
+
return event.type === 'follow'
|
|
44
|
+
|| event.type === 'unfollow'
|
|
45
|
+
|| event.type === 'join'
|
|
46
|
+
|| event.type === 'leave';
|
|
47
|
+
}
|
|
48
|
+
export function isPostbackEvent(event) {
|
|
49
|
+
return event.type === 'postback' && 'postback' in event;
|
|
50
|
+
}
|
|
51
|
+
export function resolveChannel(source) {
|
|
52
|
+
switch (source.type) {
|
|
53
|
+
case 'user':
|
|
54
|
+
return { channelType: 'private', channelId: source.userId || '' };
|
|
55
|
+
case 'group':
|
|
56
|
+
return { channelType: 'group', channelId: source.groupId || '' };
|
|
57
|
+
case 'room':
|
|
58
|
+
return { channelType: 'channel', channelId: source.roomId || '' };
|
|
59
|
+
default:
|
|
60
|
+
return { channelType: 'private', channelId: '' };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 入站归一化 → ConversationRef:LINE user → private、group → group、room → channel。
|
|
65
|
+
* LINE 没有 guild/频道容器概念,无 parent;recipient id 前缀(U/G/R)自带场景信息。
|
|
66
|
+
*/
|
|
67
|
+
export function lineInboundConversation(endpointKey, source) {
|
|
68
|
+
const channel = resolveChannel(source);
|
|
69
|
+
return {
|
|
70
|
+
endpoint: { id: endpointKey, adapter: endpointKey.split('\0')[0] ?? endpointKey },
|
|
71
|
+
kind: channel.channelType,
|
|
72
|
+
id: channel.channelId,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export function generateMessageId(event) {
|
|
76
|
+
if (isMessageEvent(event) && event.message?.id)
|
|
77
|
+
return event.message.id;
|
|
78
|
+
return `${event.type}-${event.timestamp}`;
|
|
79
|
+
}
|
|
80
|
+
/** Build inbound text for OutboundMessageService.receive. */
|
|
81
|
+
export function formatInboundContent(event) {
|
|
82
|
+
if (isMessageEvent(event)) {
|
|
83
|
+
const msg = event.message;
|
|
84
|
+
switch (msg.type) {
|
|
85
|
+
case 'text':
|
|
86
|
+
return msg.text || '';
|
|
87
|
+
case 'location':
|
|
88
|
+
return msg.address || `[location: ${msg.latitude},${msg.longitude}]`;
|
|
89
|
+
case 'image':
|
|
90
|
+
return '[image]';
|
|
91
|
+
case 'video':
|
|
92
|
+
return '[video]';
|
|
93
|
+
case 'audio':
|
|
94
|
+
return '[audio]';
|
|
95
|
+
case 'file':
|
|
96
|
+
return msg.fileName ? `[file: ${msg.fileName}]` : '[file]';
|
|
97
|
+
case 'sticker':
|
|
98
|
+
return `[sticker: ${msg.packageId}/${msg.stickerId}]`;
|
|
99
|
+
default:
|
|
100
|
+
return `[${msg.type}]`;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (event.type === 'follow')
|
|
104
|
+
return '[follow]';
|
|
105
|
+
if (event.type === 'join')
|
|
106
|
+
return '[join]';
|
|
107
|
+
if (event.type === 'unfollow')
|
|
108
|
+
return '[unfollow]';
|
|
109
|
+
if (event.type === 'leave')
|
|
110
|
+
return '[leave]';
|
|
111
|
+
if (event.type === 'postback')
|
|
112
|
+
return `[postback: ${event.postback.data}]`;
|
|
113
|
+
return '';
|
|
114
|
+
}
|
|
115
|
+
export function verifySignature(channelSecret, body, signature) {
|
|
116
|
+
const hmac = createHmac('sha256', channelSecret);
|
|
117
|
+
hmac.update(body, 'utf-8');
|
|
118
|
+
const computedSignature = hmac.digest('base64');
|
|
119
|
+
const sigBuf = Buffer.from(signature);
|
|
120
|
+
const computedBuf = Buffer.from(computedSignature);
|
|
121
|
+
if (sigBuf.length !== computedBuf.length)
|
|
122
|
+
return false;
|
|
123
|
+
return timingSafeEqual(sigBuf, computedBuf);
|
|
124
|
+
}
|
|
125
|
+
export function isValidLineRecipientId(id) {
|
|
126
|
+
return /^[UGR]/.test(id);
|
|
127
|
+
}
|
|
128
|
+
function buildTextMessage(text) {
|
|
129
|
+
const truncated = text.length > 5000 ? `${text.slice(0, 4997)}...` : text;
|
|
130
|
+
return { type: 'text', text: truncated };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* 解析 image/audio/video 段的投递源(canonical MediaRef 唯一来源)。
|
|
134
|
+
* LINE Messaging API 媒体消息仅消费远程 HTTPS URL(无上传通道),
|
|
135
|
+
* 因此只有 kind=url 可投递;base64 / path / file 一律 warn + 丢弃。
|
|
136
|
+
*/
|
|
137
|
+
function resolveMediaUrl(seg) {
|
|
138
|
+
const media = (seg.data ?? {}).media;
|
|
139
|
+
if (!isMediaRef(media)) {
|
|
140
|
+
logger.warn(formatCompact({
|
|
141
|
+
op: 'line_outbound_media_dropped',
|
|
142
|
+
type: seg.type,
|
|
143
|
+
reason: 'missing_media_ref',
|
|
144
|
+
}));
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
if (media.kind !== 'url') {
|
|
148
|
+
logger.warn(formatCompact({
|
|
149
|
+
op: 'line_outbound_media_dropped',
|
|
150
|
+
type: seg.type,
|
|
151
|
+
reason: 'unsupported_media_kind',
|
|
152
|
+
kind: media.kind,
|
|
153
|
+
}));
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
return media.value;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Wire-encode an already-rendered outbound payload into LINE Reply/Push messages.
|
|
160
|
+
* Segment canonicalization is intentionally not done here.
|
|
161
|
+
*/
|
|
162
|
+
export function formatOutboundMessages(payload) {
|
|
163
|
+
if (typeof payload === 'string') {
|
|
164
|
+
return [buildTextMessage(payload)];
|
|
165
|
+
}
|
|
166
|
+
const items = Array.isArray(payload)
|
|
167
|
+
? payload
|
|
168
|
+
: payload && typeof payload === 'object' && 'type' in payload
|
|
169
|
+
? [payload]
|
|
170
|
+
: [];
|
|
171
|
+
if (items.length === 0) {
|
|
172
|
+
const text = payload == null
|
|
173
|
+
? ''
|
|
174
|
+
: typeof payload === 'object'
|
|
175
|
+
? JSON.stringify(payload)
|
|
176
|
+
: String(payload);
|
|
177
|
+
return [buildTextMessage(text)];
|
|
178
|
+
}
|
|
179
|
+
const messages = [];
|
|
180
|
+
for (const item of items) {
|
|
181
|
+
if (typeof item === 'string') {
|
|
182
|
+
messages.push(buildTextMessage(item));
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const data = item.data ?? {};
|
|
186
|
+
switch (item.type) {
|
|
187
|
+
case 'text':
|
|
188
|
+
messages.push(buildTextMessage(String(data.text ?? data.content ?? '')));
|
|
189
|
+
break;
|
|
190
|
+
case 'at':
|
|
191
|
+
if (data.id) {
|
|
192
|
+
messages.push(buildTextMessage(`@${String(data.name || data.id)}`));
|
|
193
|
+
}
|
|
194
|
+
break;
|
|
195
|
+
case 'image': {
|
|
196
|
+
const url = resolveMediaUrl(item);
|
|
197
|
+
if (url) {
|
|
198
|
+
messages.push({
|
|
199
|
+
type: 'image',
|
|
200
|
+
originalContentUrl: url,
|
|
201
|
+
previewImageUrl: url,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
case 'video': {
|
|
207
|
+
const url = resolveMediaUrl(item);
|
|
208
|
+
if (url) {
|
|
209
|
+
messages.push({
|
|
210
|
+
type: 'video',
|
|
211
|
+
originalContentUrl: url,
|
|
212
|
+
previewImageUrl: typeof data.previewUrl === 'string' ? data.previewUrl : url,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
case 'audio': {
|
|
218
|
+
const url = resolveMediaUrl(item);
|
|
219
|
+
if (url) {
|
|
220
|
+
messages.push({
|
|
221
|
+
type: 'audio',
|
|
222
|
+
originalContentUrl: url,
|
|
223
|
+
duration: typeof data.duration === 'number' ? data.duration : 0,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
case 'location':
|
|
229
|
+
messages.push({
|
|
230
|
+
type: 'location',
|
|
231
|
+
title: String(data.title || 'Location'),
|
|
232
|
+
address: String(data.address || ''),
|
|
233
|
+
latitude: typeof data.latitude === 'number' ? data.latitude : 0,
|
|
234
|
+
longitude: typeof data.longitude === 'number' ? data.longitude : 0,
|
|
235
|
+
});
|
|
236
|
+
break;
|
|
237
|
+
case 'sticker':
|
|
238
|
+
messages.push({
|
|
239
|
+
type: 'sticker',
|
|
240
|
+
packageId: String(data.package_id || '1'),
|
|
241
|
+
stickerId: String(data.sticker_id || '1'),
|
|
242
|
+
});
|
|
243
|
+
break;
|
|
244
|
+
default:
|
|
245
|
+
messages.push(buildTextMessage(`[${item.type}]`));
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
// LINE allows at most 5 messages per Reply/Push request.
|
|
249
|
+
return messages.slice(0, 5);
|
|
250
|
+
}
|
|
251
|
+
export async function readTextBody(request, options = {}) {
|
|
252
|
+
const limit = options.limit ?? 1_048_576;
|
|
253
|
+
const chunks = [];
|
|
254
|
+
let size = 0;
|
|
255
|
+
for await (const chunk of request) {
|
|
256
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
257
|
+
size += buffer.length;
|
|
258
|
+
if (size > limit) {
|
|
259
|
+
request.destroy();
|
|
260
|
+
throw new Error(`Request body exceeds ${limit} bytes`);
|
|
261
|
+
}
|
|
262
|
+
chunks.push(buffer);
|
|
263
|
+
}
|
|
264
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
265
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { EndpointEventEmitter } from 'zhin.js/adapter';
|
|
2
|
+
import { type getAdapterLogger } from '@zhin.js/logger';
|
|
3
|
+
import { type LineEvent } from './protocol.js';
|
|
4
|
+
export declare function receiveLineSideEvent(emit: EndpointEventEmitter, endpointKey: string, configId: string, event: LineEvent, logger: ReturnType<typeof getAdapterLogger>): void;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { buildNotice, senderFromId } from '@zhin.js/core';
|
|
2
|
+
import { formatCompact } from '@zhin.js/logger';
|
|
3
|
+
import { isLineLifecycleEvent, lineInboundConversation, } from './protocol.js';
|
|
4
|
+
function mapLineLifecycleParts(type) {
|
|
5
|
+
switch (type) {
|
|
6
|
+
case 'follow':
|
|
7
|
+
return { scene_type: 'friend', sub_type: 'increase' };
|
|
8
|
+
case 'unfollow':
|
|
9
|
+
return { scene_type: 'friend', sub_type: 'decrease' };
|
|
10
|
+
case 'join':
|
|
11
|
+
return { scene_type: 'group', sub_type: 'member_increase' };
|
|
12
|
+
case 'leave':
|
|
13
|
+
return { scene_type: 'group', sub_type: 'member_decrease' };
|
|
14
|
+
default:
|
|
15
|
+
return { scene_type: 'line', sub_type: type };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function receiveLineSideEvent(emit, endpointKey, configId, event, logger) {
|
|
19
|
+
if (!isLineLifecycleEvent(event))
|
|
20
|
+
return;
|
|
21
|
+
const parts = mapLineLifecycleParts(event.type);
|
|
22
|
+
const conversation = lineInboundConversation(endpointKey, event.source);
|
|
23
|
+
const userId = event.source.userId || conversation.id;
|
|
24
|
+
void emit('notice.receive', buildNotice(event, {
|
|
25
|
+
$id: `line:${event.type}:${event.timestamp}:${userId}`,
|
|
26
|
+
$adapter: 'line',
|
|
27
|
+
$endpoint: configId,
|
|
28
|
+
$type: 'notice',
|
|
29
|
+
$scene_id: conversation.id,
|
|
30
|
+
$scene_type: parts.scene_type,
|
|
31
|
+
$sub_type: parts.sub_type,
|
|
32
|
+
$actor: senderFromId(userId),
|
|
33
|
+
$timestamp: event.timestamp,
|
|
34
|
+
})).catch((err) => {
|
|
35
|
+
logger.warn(formatCompact({
|
|
36
|
+
op: 'line_side_event_failed',
|
|
37
|
+
endpoint: configId,
|
|
38
|
+
event: event.type,
|
|
39
|
+
error: err instanceof Error ? err.message : String(err),
|
|
40
|
+
}));
|
|
41
|
+
});
|
|
42
|
+
}
|
package/lib/webhook.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LINE webhook HTTP: signature → parse → admit.
|
|
3
|
+
*/
|
|
4
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
5
|
+
import type { HttpHost, HttpRouteRegistration } from '@zhin.js/host-http';
|
|
6
|
+
import { type LineEvent, type ResolvedLineConfig } from './protocol.js';
|
|
7
|
+
export interface LineWebhookHandler {
|
|
8
|
+
readonly config: ResolvedLineConfig;
|
|
9
|
+
readonly isOpen: boolean;
|
|
10
|
+
admit(event: LineEvent): void;
|
|
11
|
+
}
|
|
12
|
+
export declare function registerLineWebhookRoutes(http: HttpHost, handler: LineWebhookHandler): HttpRouteRegistration[];
|
|
13
|
+
export declare function handleLineWebhookRequest(request: IncomingMessage, response: ServerResponse, handler: LineWebhookHandler): Promise<void>;
|
package/lib/webhook.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { formatCompact, getLogger } from '@zhin.js/logger';
|
|
2
|
+
import { readTextBody, verifySignature, } from './protocol.js';
|
|
3
|
+
const logger = getLogger('line');
|
|
4
|
+
export function registerLineWebhookRoutes(http, handler) {
|
|
5
|
+
const path = handler.config.webhookPath;
|
|
6
|
+
return [
|
|
7
|
+
http.route('POST', path, async (request, response) => {
|
|
8
|
+
await handleLineWebhookRequest(request, response, handler);
|
|
9
|
+
}, { summary: 'LINE Messaging API webhook', tags: ['line'] }),
|
|
10
|
+
];
|
|
11
|
+
}
|
|
12
|
+
export async function handleLineWebhookRequest(request, response, handler) {
|
|
13
|
+
try {
|
|
14
|
+
const signature = request.headers['x-line-signature'];
|
|
15
|
+
const signatureValue = Array.isArray(signature) ? signature[0] : signature;
|
|
16
|
+
if (!signatureValue) {
|
|
17
|
+
response.writeHead(403, { 'Content-Type': 'application/json' });
|
|
18
|
+
response.end(JSON.stringify({ message: 'Missing signature' }));
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const rawBody = await readTextBody(request);
|
|
22
|
+
if (!verifySignature(handler.config.channelSecret, rawBody, signatureValue)) {
|
|
23
|
+
logger.warn(formatCompact({ op: 'webhook', ok: false, error: 'invalid signature' }));
|
|
24
|
+
response.writeHead(403, { 'Content-Type': 'application/json' });
|
|
25
|
+
response.end(JSON.stringify({ message: 'Invalid signature' }));
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
let body;
|
|
29
|
+
try {
|
|
30
|
+
body = JSON.parse(rawBody);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
34
|
+
response.end(JSON.stringify({ message: 'OK' }));
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (handler.isOpen && Array.isArray(body.events)) {
|
|
38
|
+
for (const event of body.events) {
|
|
39
|
+
handler.admit(event);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
43
|
+
response.end(JSON.stringify({ message: 'OK' }));
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
logger.error('LINE webhook error:', error);
|
|
47
|
+
response.writeHead(200, { 'Content-Type': 'application/json' });
|
|
48
|
+
response.end(JSON.stringify({ message: 'OK' }));
|
|
49
|
+
}
|
|
50
|
+
}
|