@alexsun-top/opencode-chat-room 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/LICENSE +2 -2
- package/README.md +38 -6
- package/README.zh-CN.md +38 -6
- package/cli.ts +27 -1
- package/dist/cli.js +5074 -3212
- package/package.json +23 -3
- package/packages/chat-room-channeld/README.md +98 -25
- package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
- package/packages/chat-room-channeld/src/adapter.ts +36 -2
- package/packages/chat-room-channeld/src/config.ts +63 -1
- package/packages/chat-room-channeld/src/delivery.ts +6 -1
- package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
- package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
- package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
- package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
- package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
- package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
- package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
- package/packages/chat-room-channeld/src/host.ts +120 -2
- package/packages/chat-room-channeld/src/inbound.ts +26 -0
- package/packages/chat-room-channeld/src/state.ts +17 -0
- package/packages/chat-room-channeld/src/stats.ts +43 -1
- package/server/admin-state.ts +13 -13
- package/server/app.ts +95 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +15 -9
- package/server/assets/chat/announcements.js +70 -7
- package/server/assets/chat/doc-preview.js +184 -35
- package/server/assets/chat/events.js +3 -0
- package/server/assets/chat/files.js +46 -4
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/integration-editor.js +163 -0
- package/server/assets/chat/integration-values.js +124 -0
- package/server/assets/chat/integrations.js +498 -0
- package/server/assets/chat/locales/de.js +40 -4
- package/server/assets/chat/locales/es.js +40 -4
- package/server/assets/chat/locales/fr.js +40 -4
- package/server/assets/chat/locales/it.js +40 -4
- package/server/assets/chat/locales/ja.js +40 -4
- package/server/assets/chat/locales/ko.js +40 -4
- package/server/assets/chat/markdown.js +22 -8
- package/server/assets/chat/messages.js +5 -5
- package/server/assets/chat/office-preview.js +69 -0
- package/server/assets/chat/panels.js +36 -0
- package/server/assets/chat/recall.js +58 -7
- package/server/assets/chat/receipts.js +15 -3
- package/server/assets/chat/reminders.js +69 -8
- package/server/assets/chat/resource-format.js +11 -0
- package/server/assets/chat/settings.js +30 -2
- package/server/assets/chat/side-pane.js +1 -2
- package/server/assets/chat/state.js +93 -10
- package/server/assets/chat/system-events.js +32 -0
- package/server/assets/chat/system-messages.js +23 -14
- package/server/assets/chat/task-row.js +0 -6
- package/server/assets/chat/tasks.js +121 -33
- package/server/assets/code-highlight.css +55 -32
- package/server/assets/conversation.css +123 -23
- package/server/assets/doc-preview.css +35 -3
- package/server/assets/files.css +5 -0
- package/server/assets/fluent-icons.svg +2 -0
- package/server/assets/monaco/LICENSE +21 -0
- package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
- package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
- package/server/assets/monaco/editor.worker.js +45 -0
- package/server/assets/monaco/integration-rules.css +1 -0
- package/server/assets/monaco/integration-rules.js +1297 -0
- package/server/assets/monaco/json.worker.js +77 -0
- package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
- package/server/assets/office/docx.bundle.js +33 -0
- package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
- package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
- package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
- package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
- package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
- package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
- package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
- package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
- package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
- package/server/assets/office/pptx.bundle.js +104 -0
- package/server/assets/office/xlsx.bundle.js +141 -0
- package/server/assets/recall.css +5 -4
- package/server/assets/responsive.css +50 -11
- package/server/assets/settings.css +73 -1
- package/server/assets/tasks.css +57 -7
- package/server/channel-integration.ts +519 -0
- package/server/channel-settings.ts +77 -0
- package/server/channels.ts +261 -18
- package/server/chat-server.ts +32 -580
- package/server/chat.html +187 -21
- package/server/http-server.ts +3 -182
- package/server/resource-routes.ts +16 -16
- package/server/routes/inbox.ts +100 -0
- package/server/routes/pages.ts +83 -0
- package/server/routes/questions.ts +39 -0
- package/server/routes/room-actions.ts +162 -0
- package/server/routes/rooms.ts +160 -0
- package/server/startup.ts +84 -0
- package/server/sw.js +4 -0
- package/server/task-routes.ts +1 -1
- package/src/center/center-client.ts +2 -10
- package/src/config/file-config.ts +7 -54
- package/src/platform/http-server.ts +182 -0
- package/src/protocol/addressing.ts +21 -0
- package/src/protocol/config.ts +58 -0
- package/src/protocol/room.ts +51 -0
- package/src/rooms/resources.ts +26 -16
- package/src/rooms/room-service.ts +2 -48
- package/src/rooms/storage.ts +329 -0
- package/src/rooms/tasks.ts +21 -5
- package/src/runtime/watch.ts +1 -1
- package/src/state/pg-database.ts +183 -0
- package/src/state/pg-migrate.ts +175 -0
- package/src/state/pg-sql.mjs +175 -0
- package/src/state/pg-worker.mjs +148 -0
- package/src/state/sqlite-announcements.ts +25 -0
- package/src/state/sqlite-database.ts +121 -0
- package/src/state/sqlite-legacy.ts +90 -0
- package/src/state/sqlite-members.ts +155 -0
- package/src/state/sqlite-messages.ts +288 -0
- package/src/state/sqlite-resources.ts +39 -0
- package/src/state/sqlite-rooms.ts +87 -0
- package/src/state/sqlite-schema.ts +80 -0
- package/src/state/sqlite-state-store.ts +33 -0
- package/src/state/sqlite-state.ts +15 -897
- package/src/state/sqlite-tasks.ts +65 -0
- package/src/state/sqlite-transaction.ts +13 -0
- package/src/state/sqlite.ts +21 -1
- package/src/state/store.ts +5 -1
- package/src/tui/app.mjs +32 -19
- package/src/tui/config.mjs +12 -4
- package/src/tui/i18n.mjs +38 -0
- package/src/tui/info-app.mjs +50 -51
- package/src/tui/info-content.mjs +79 -44
- package/src/tui/join-app.mjs +9 -9
- package/src/tui/locales/en.mjs +349 -0
- package/src/tui/locales/zh-CN.mjs +349 -0
- package/src/tui/main.mjs +85 -37
- package/src/tui/markdown.mjs +3 -2
- package/src/tui/mentions.mjs +3 -1
- package/src/tui/message-app.mjs +22 -21
- package/src/tui/message-view.mjs +2 -1
- package/src/tui/palette-app.mjs +9 -8
- package/src/tui/palette.mjs +30 -24
- package/src/tui/prefs.mjs +92 -0
- package/src/tui/reminder-app.mjs +18 -17
- package/src/tui/room-settings-app.mjs +30 -28
- package/src/tui/settings-app.mjs +153 -0
- package/src/tui/ui-content.mjs +65 -86
- package/src/tui/ui-help.mjs +73 -0
- package/src/tui/ui-overlay-view.mjs +23 -7
- package/src/tui/ui-suggest.mjs +6 -5
- package/src/tui/ui-theme.mjs +37 -33
- package/src/tui/ui-view.mjs +22 -7
- package/src/tui/ui.mjs +15 -3
- package/src/web/editor.worker.ts +1 -0
- package/src/web/integration-rules-editor.ts +439 -0
- package/src/web/integration-rules.ts +22 -0
- package/src/web/integration-schema.ts +228 -0
- package/src/web/json.worker.ts +1 -0
- package/src/web/office-viewer.ts +221 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { CardVersion } from "./feishu-card.ts";
|
|
3
|
+
import { buildCard } from "./feishu-card.ts";
|
|
4
|
+
import type { Endpoint } from "./protocol.ts";
|
|
5
|
+
|
|
6
|
+
const DEFAULT_BASE_URL = "https://open.feishu.cn";
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
8
|
+
const DEFAULT_RATE_LIMIT_MS = 1000;
|
|
9
|
+
const TOKEN_REFRESH_MARGIN_MS = 30 * 60_000;
|
|
10
|
+
const FALLBACK_TOKEN_TTL_SECONDS = 7200;
|
|
11
|
+
const TOKEN_INVALID_CODE = 99991663;
|
|
12
|
+
const RATE_LIMIT_CODES = new Set([230020, 99991400]);
|
|
13
|
+
|
|
14
|
+
export type SendState = "sent" | "retryable" | "rate_limited" | "permanent" | "unsupported" | "unknown";
|
|
15
|
+
|
|
16
|
+
export interface SendReceipt {
|
|
17
|
+
state: SendState;
|
|
18
|
+
providerMessage?: { endpoint: Endpoint; nativeMessageId: string };
|
|
19
|
+
retryAfterMs?: number;
|
|
20
|
+
detail?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface FeishuConfig {
|
|
24
|
+
appId: string;
|
|
25
|
+
appSecret: string;
|
|
26
|
+
baseUrl: string;
|
|
27
|
+
timeoutMs: number;
|
|
28
|
+
cardVersion: CardVersion;
|
|
29
|
+
inbound: boolean;
|
|
30
|
+
inboundChats: ReadonlySet<string>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface SendTarget {
|
|
34
|
+
roomId?: unknown;
|
|
35
|
+
room?: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface SendParams {
|
|
39
|
+
idempotencyKey?: unknown;
|
|
40
|
+
target?: SendTarget;
|
|
41
|
+
payload?: unknown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface RawResponse {
|
|
45
|
+
status: number;
|
|
46
|
+
headers: Headers;
|
|
47
|
+
body?: unknown;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class FeishuTimeoutError extends Error {
|
|
51
|
+
constructor() {
|
|
52
|
+
super("feishu request timed out");
|
|
53
|
+
this.name = "FeishuTimeoutError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class FeishuApiError extends Error {
|
|
58
|
+
readonly code: number;
|
|
59
|
+
readonly msg: string;
|
|
60
|
+
readonly scope: "token" | "send";
|
|
61
|
+
|
|
62
|
+
constructor(code: number, msg: string, scope: "token" | "send") {
|
|
63
|
+
super(`feishu ${scope} code ${code}: ${msg}`);
|
|
64
|
+
this.name = "FeishuApiError";
|
|
65
|
+
this.code = code;
|
|
66
|
+
this.msg = msg;
|
|
67
|
+
this.scope = scope;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function logLine(accountId: string, message: string): void {
|
|
72
|
+
console.error(`feishu adapter ${accountId}: ${message}`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Stable 32-hex SHA-256 prefix used as the Feishu idempotent message uuid. */
|
|
76
|
+
export function deterministicUuid(idempotencyKey: string): string {
|
|
77
|
+
return createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 32);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
81
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function fetchJson(url: string, init: RequestInit, timeoutMs: number): Promise<RawResponse> {
|
|
85
|
+
const controller = new AbortController();
|
|
86
|
+
let timedOut = false;
|
|
87
|
+
const timer = setTimeout(() => {
|
|
88
|
+
timedOut = true;
|
|
89
|
+
controller.abort();
|
|
90
|
+
}, timeoutMs);
|
|
91
|
+
try {
|
|
92
|
+
const response = await fetch(url, { ...init, signal: controller.signal });
|
|
93
|
+
const text = await response.text();
|
|
94
|
+
let body: unknown;
|
|
95
|
+
if (text.trim()) {
|
|
96
|
+
try {
|
|
97
|
+
body = JSON.parse(text);
|
|
98
|
+
} catch {
|
|
99
|
+
body = undefined;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { status: response.status, headers: response.headers, body };
|
|
103
|
+
} catch (error) {
|
|
104
|
+
// A timeout means the request may already be in Feishu's hands.
|
|
105
|
+
if (timedOut) throw new FeishuTimeoutError();
|
|
106
|
+
throw error;
|
|
107
|
+
} finally {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async function requestToken(config: FeishuConfig): Promise<{ token: string; expiresAt: number }> {
|
|
113
|
+
const raw = await fetchJson(
|
|
114
|
+
`${config.baseUrl}/open-apis/auth/v3/tenant_access_token/internal`,
|
|
115
|
+
{
|
|
116
|
+
method: "POST",
|
|
117
|
+
headers: { "Content-Type": "application/json; charset=utf-8" },
|
|
118
|
+
body: JSON.stringify({ app_id: config.appId, app_secret: config.appSecret }),
|
|
119
|
+
},
|
|
120
|
+
config.timeoutMs,
|
|
121
|
+
);
|
|
122
|
+
const body = raw.body;
|
|
123
|
+
if (!isRecord(body) || typeof body.code !== "number") {
|
|
124
|
+
throw new Error("feishu token response was malformed");
|
|
125
|
+
}
|
|
126
|
+
if (body.code !== 0) {
|
|
127
|
+
throw new FeishuApiError(body.code, typeof body.msg === "string" ? body.msg : "", "token");
|
|
128
|
+
}
|
|
129
|
+
if (typeof body.tenant_access_token !== "string" || body.tenant_access_token.length === 0) {
|
|
130
|
+
throw new Error("feishu token response was malformed");
|
|
131
|
+
}
|
|
132
|
+
const expire =
|
|
133
|
+
typeof body.expire === "number" && body.expire > 0 ? body.expire : FALLBACK_TOKEN_TTL_SECONDS;
|
|
134
|
+
return { token: body.tenant_access_token, expiresAt: Date.now() + expire * 1000 };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function ensureToken(config: FeishuConfig, state: TokenState, force = false): Promise<string> {
|
|
138
|
+
if (!force && state.token && state.tokenExpiresAt - Date.now() > TOKEN_REFRESH_MARGIN_MS) {
|
|
139
|
+
return state.token;
|
|
140
|
+
}
|
|
141
|
+
const fresh = await requestToken(config);
|
|
142
|
+
state.token = fresh.token;
|
|
143
|
+
state.tokenExpiresAt = fresh.expiresAt;
|
|
144
|
+
logLine(state.accountId, "tenant token acquired");
|
|
145
|
+
return fresh.token;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function errorCode(error: unknown): string | undefined {
|
|
149
|
+
const direct = (error as { code?: unknown } | null)?.code;
|
|
150
|
+
if (typeof direct === "string") return direct;
|
|
151
|
+
const cause = (error as { cause?: { code?: unknown } } | null)?.cause?.code;
|
|
152
|
+
return typeof cause === "string" ? cause : undefined;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function networkFailure(error: unknown): SendReceipt {
|
|
156
|
+
const code = errorCode(error);
|
|
157
|
+
return { state: "retryable", detail: code ? `feishu network error (${code})` : "feishu network error" };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function failureReceipt(error: unknown): SendReceipt {
|
|
161
|
+
if (error instanceof FeishuTimeoutError) {
|
|
162
|
+
return { state: "unknown", detail: error.message };
|
|
163
|
+
}
|
|
164
|
+
if (error instanceof FeishuApiError) {
|
|
165
|
+
if (RATE_LIMIT_CODES.has(error.code)) {
|
|
166
|
+
return { state: "rate_limited", retryAfterMs: DEFAULT_RATE_LIMIT_MS, detail: `feishu code ${error.code}` };
|
|
167
|
+
}
|
|
168
|
+
return { state: "permanent", detail: error.message };
|
|
169
|
+
}
|
|
170
|
+
if (error instanceof Error && error.message === "feishu token response was malformed") {
|
|
171
|
+
return { state: "permanent", detail: error.message };
|
|
172
|
+
}
|
|
173
|
+
return networkFailure(error);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function parseRetryAfter(value: string | null): number {
|
|
177
|
+
if (!value) return DEFAULT_RATE_LIMIT_MS;
|
|
178
|
+
const seconds = Number(value.trim());
|
|
179
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;
|
|
180
|
+
const date = Date.parse(value);
|
|
181
|
+
if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
|
|
182
|
+
return DEFAULT_RATE_LIMIT_MS;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function apiCode(raw: RawResponse): number | undefined {
|
|
186
|
+
return isRecord(raw.body) && typeof raw.body.code === "number" ? raw.body.code : undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A Feishu business error, as opposed to an HTTP transport failure. */
|
|
190
|
+
function isApiFailure(raw: RawResponse): boolean {
|
|
191
|
+
const code = apiCode(raw);
|
|
192
|
+
return raw.status !== 429 && raw.status < 500 && code !== undefined && code !== 0;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const CLIENT_ERROR_STATUSES = new Set([400, 401, 403, 404]);
|
|
196
|
+
|
|
197
|
+
function apiResponseDetail(body: unknown, status: number): string {
|
|
198
|
+
const code = isRecord(body) && typeof body.code === "number" ? body.code : undefined;
|
|
199
|
+
const msg = isRecord(body) && typeof body.msg === "string" ? body.msg : "";
|
|
200
|
+
if (code !== undefined && code !== 0) return msg ? `feishu code ${code}: ${msg}` : `feishu code ${code}`;
|
|
201
|
+
return `feishu http ${status}`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function mapSendResponse(raw: RawResponse, endpoint: Endpoint): SendReceipt {
|
|
205
|
+
if (raw.status === 429) {
|
|
206
|
+
return { state: "rate_limited", retryAfterMs: parseRetryAfter(raw.headers.get("retry-after")) };
|
|
207
|
+
}
|
|
208
|
+
if (raw.status >= 500) {
|
|
209
|
+
return { state: "retryable", detail: `feishu http ${raw.status}` };
|
|
210
|
+
}
|
|
211
|
+
const body = raw.body;
|
|
212
|
+
const code = apiCode(raw);
|
|
213
|
+
if (code !== undefined && RATE_LIMIT_CODES.has(code)) {
|
|
214
|
+
return {
|
|
215
|
+
state: "rate_limited",
|
|
216
|
+
retryAfterMs: parseRetryAfter(raw.headers.get("retry-after")),
|
|
217
|
+
detail: `feishu code ${code}`,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
if (CLIENT_ERROR_STATUSES.has(raw.status)) {
|
|
221
|
+
return { state: "permanent", detail: apiResponseDetail(body, raw.status) };
|
|
222
|
+
}
|
|
223
|
+
if (!isRecord(body) || typeof body.code !== "number") {
|
|
224
|
+
return { state: "unknown", detail: "feishu response was malformed" };
|
|
225
|
+
}
|
|
226
|
+
if (body.code === 0) {
|
|
227
|
+
const data = isRecord(body.data) ? body.data : undefined;
|
|
228
|
+
const messageId = data && typeof data.message_id === "string" ? data.message_id : undefined;
|
|
229
|
+
if (raw.status >= 200 && raw.status < 300 && messageId) {
|
|
230
|
+
return { state: "sent", providerMessage: { endpoint, nativeMessageId: messageId } };
|
|
231
|
+
}
|
|
232
|
+
return { state: "unknown", detail: "feishu response was malformed" };
|
|
233
|
+
}
|
|
234
|
+
const msg = typeof body.msg === "string" ? body.msg : "";
|
|
235
|
+
return { state: "permanent", detail: msg ? `feishu code ${body.code}: ${msg}` : `feishu code ${body.code}` };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** A Feishu parent reference is usable only for this account's own chat. */
|
|
239
|
+
function replyParentId(payload: unknown, accountId: string): string | undefined {
|
|
240
|
+
if (!isRecord(payload) || !isRecord(payload.parent)) return undefined;
|
|
241
|
+
const parent = payload.parent;
|
|
242
|
+
if (!isRecord(parent.endpoint)) return undefined;
|
|
243
|
+
if (parent.endpoint.platform !== "feishu") return undefined;
|
|
244
|
+
if (typeof parent.endpoint.accountId === "string" && parent.endpoint.accountId !== accountId) {
|
|
245
|
+
return undefined;
|
|
246
|
+
}
|
|
247
|
+
return typeof parent.nativeMessageId === "string" && parent.nativeMessageId
|
|
248
|
+
? parent.nativeMessageId
|
|
249
|
+
: undefined;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function postMessage(
|
|
253
|
+
config: FeishuConfig,
|
|
254
|
+
token: string,
|
|
255
|
+
body: string,
|
|
256
|
+
replyTo?: string,
|
|
257
|
+
): Promise<RawResponse> {
|
|
258
|
+
const path = replyTo
|
|
259
|
+
? `/open-apis/im/v1/messages/${encodeURIComponent(replyTo)}/reply`
|
|
260
|
+
: "/open-apis/im/v1/messages?receive_id_type=chat_id";
|
|
261
|
+
return fetchJson(
|
|
262
|
+
`${config.baseUrl}${path}`,
|
|
263
|
+
{
|
|
264
|
+
method: "POST",
|
|
265
|
+
headers: {
|
|
266
|
+
Authorization: `Bearer ${token}`,
|
|
267
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
268
|
+
},
|
|
269
|
+
body,
|
|
270
|
+
},
|
|
271
|
+
config.timeoutMs,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export async function sendMessage(
|
|
276
|
+
config: FeishuConfig,
|
|
277
|
+
state: TokenState,
|
|
278
|
+
params: SendParams,
|
|
279
|
+
): Promise<SendReceipt> {
|
|
280
|
+
const target = params.target;
|
|
281
|
+
const chatId = target && typeof target.roomId === "string" && target.roomId
|
|
282
|
+
? target.roomId
|
|
283
|
+
: target && typeof target.room === "string"
|
|
284
|
+
? target.room
|
|
285
|
+
: undefined;
|
|
286
|
+
if (!chatId) return { state: "permanent", detail: "send target requires a room" };
|
|
287
|
+
const text = isRecord(params.payload) && typeof params.payload.text === "string"
|
|
288
|
+
? params.payload.text
|
|
289
|
+
: undefined;
|
|
290
|
+
if (text === undefined) return { state: "permanent", detail: "send payload.text must be a string" };
|
|
291
|
+
if (typeof params.idempotencyKey !== "string" || params.idempotencyKey.length === 0) {
|
|
292
|
+
return { state: "permanent", detail: "send requires an idempotency key" };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
const endpoint = target as unknown as Endpoint;
|
|
296
|
+
// Card 2.0 renders block Markdown; card 1.0 keeps the 0.8.0 lark_md payload.
|
|
297
|
+
const card = buildCard(config.cardVersion, text);
|
|
298
|
+
const parentId = replyParentId(params.payload, state.accountId);
|
|
299
|
+
const message = {
|
|
300
|
+
msg_type: "interactive",
|
|
301
|
+
content: JSON.stringify(card),
|
|
302
|
+
uuid: deterministicUuid(params.idempotencyKey),
|
|
303
|
+
};
|
|
304
|
+
const body = JSON.stringify(parentId ? message : { receive_id: chatId, ...message });
|
|
305
|
+
|
|
306
|
+
let token: string;
|
|
307
|
+
let raw: RawResponse;
|
|
308
|
+
try {
|
|
309
|
+
token = await ensureToken(config, state);
|
|
310
|
+
raw = await postMessage(config, token, body, parentId);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
return failureReceipt(error);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (raw.status !== 429 && raw.status < 500 && apiCode(raw) === TOKEN_INVALID_CODE) {
|
|
316
|
+
try {
|
|
317
|
+
token = await ensureToken(config, state, true);
|
|
318
|
+
raw = await postMessage(config, token, body, parentId);
|
|
319
|
+
} catch (error) {
|
|
320
|
+
return failureReceipt(error);
|
|
321
|
+
}
|
|
322
|
+
// A token that is still rejected after a forced refresh will not fix itself.
|
|
323
|
+
if (isApiFailure(raw) && apiCode(raw) === TOKEN_INVALID_CODE) {
|
|
324
|
+
return { state: "permanent", detail: `feishu code ${TOKEN_INVALID_CODE}` };
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return mapSendResponse(raw, endpoint);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function startupFailureDetail(error: unknown): string {
|
|
331
|
+
if (error instanceof FeishuTimeoutError) return error.message;
|
|
332
|
+
if (error instanceof FeishuApiError) return error.message;
|
|
333
|
+
if (error instanceof Error && error.message === "feishu token response was malformed") return error.message;
|
|
334
|
+
const code = errorCode(error);
|
|
335
|
+
return code ? `feishu token request failed (${code})` : "feishu token request failed";
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export interface TokenState {
|
|
339
|
+
accountId: string;
|
|
340
|
+
token?: string;
|
|
341
|
+
tokenExpiresAt: number;
|
|
342
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal protobuf codec for Feishu's pbbp2 WebSocket frame. The schema is fixed
|
|
3
|
+
* (fields 1-9), so a dependency-free codec beats shipping a protobuf runtime.
|
|
4
|
+
*/
|
|
5
|
+
export interface WsHeader {
|
|
6
|
+
key: string;
|
|
7
|
+
value: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface WsFrame {
|
|
11
|
+
SeqID?: number;
|
|
12
|
+
LogID?: number;
|
|
13
|
+
service?: number;
|
|
14
|
+
method?: number;
|
|
15
|
+
headers?: WsHeader[];
|
|
16
|
+
payload_encoding?: string;
|
|
17
|
+
payload_type?: string;
|
|
18
|
+
payload?: Uint8Array;
|
|
19
|
+
LogIDNew?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const utf8 = new TextEncoder();
|
|
23
|
+
|
|
24
|
+
function varint(value: number): number[] {
|
|
25
|
+
let rest = BigInt(Math.max(0, Math.trunc(value)));
|
|
26
|
+
const out: number[] = [];
|
|
27
|
+
while (rest > 0x7fn) {
|
|
28
|
+
out.push(Number((rest & 0x7fn) | 0x80n));
|
|
29
|
+
rest >>= 7n;
|
|
30
|
+
}
|
|
31
|
+
out.push(Number(rest));
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fieldKey(field: number, wire: number): number[] {
|
|
36
|
+
return varint((field << 3) | wire);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function bytesField(field: number, value: Uint8Array): number[] {
|
|
40
|
+
return [...fieldKey(field, 2), ...varint(value.length), ...value];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function stringField(field: number, value: string): number[] {
|
|
44
|
+
return bytesField(field, utf8.encode(value));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function numberField(field: number, value: number): number[] {
|
|
48
|
+
return [...fieldKey(field, 0), ...varint(value)];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function encodeFrame(frame: WsFrame): Uint8Array {
|
|
52
|
+
const out: number[] = [];
|
|
53
|
+
out.push(...numberField(1, frame.SeqID ?? 0));
|
|
54
|
+
out.push(...numberField(2, frame.LogID ?? 0));
|
|
55
|
+
out.push(...numberField(3, frame.service ?? 0));
|
|
56
|
+
out.push(...numberField(4, frame.method ?? 0));
|
|
57
|
+
for (const header of frame.headers ?? []) {
|
|
58
|
+
const entry = [...stringField(1, header.key), ...stringField(2, header.value)];
|
|
59
|
+
out.push(...bytesField(5, Uint8Array.from(entry)));
|
|
60
|
+
}
|
|
61
|
+
if (frame.payload_encoding) out.push(...stringField(6, frame.payload_encoding));
|
|
62
|
+
if (frame.payload_type) out.push(...stringField(7, frame.payload_type));
|
|
63
|
+
if (frame.payload) out.push(...bytesField(8, frame.payload));
|
|
64
|
+
if (frame.LogIDNew) out.push(...stringField(9, frame.LogIDNew));
|
|
65
|
+
return Uint8Array.from(out);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
class Reader {
|
|
69
|
+
#bytes: Uint8Array;
|
|
70
|
+
#offset = 0;
|
|
71
|
+
|
|
72
|
+
constructor(bytes: Uint8Array) {
|
|
73
|
+
this.#bytes = bytes;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
get done(): boolean {
|
|
77
|
+
return this.#offset >= this.#bytes.length;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
varint(): bigint {
|
|
81
|
+
let value = 0n;
|
|
82
|
+
let shift = 0n;
|
|
83
|
+
for (;;) {
|
|
84
|
+
if (this.#offset >= this.#bytes.length) throw new Error("truncated varint");
|
|
85
|
+
const byte = this.#bytes[this.#offset++]!;
|
|
86
|
+
value |= BigInt(byte & 0x7f) << shift;
|
|
87
|
+
if ((byte & 0x80) === 0) return value;
|
|
88
|
+
shift += 7n;
|
|
89
|
+
if (shift > 70n) throw new Error("varint is too long");
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
bytes(length: number): Uint8Array {
|
|
94
|
+
if (this.#offset + length > this.#bytes.length) throw new Error("truncated frame field");
|
|
95
|
+
const slice = this.#bytes.subarray(this.#offset, this.#offset + length);
|
|
96
|
+
this.#offset += length;
|
|
97
|
+
return slice;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
skip(wire: number): void {
|
|
101
|
+
if (wire === 0) this.varint();
|
|
102
|
+
else if (wire === 1) this.bytes(8);
|
|
103
|
+
else if (wire === 2) this.bytes(Number(this.varint()));
|
|
104
|
+
else if (wire === 5) this.bytes(4);
|
|
105
|
+
else throw new Error(`unsupported wire type ${wire}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function decodeHeader(bytes: Uint8Array): WsHeader {
|
|
110
|
+
const reader = new Reader(bytes);
|
|
111
|
+
let key = "";
|
|
112
|
+
let value = "";
|
|
113
|
+
while (!reader.done) {
|
|
114
|
+
const tag = Number(reader.varint());
|
|
115
|
+
const field = tag >> 3;
|
|
116
|
+
const wire = tag & 7;
|
|
117
|
+
if (field === 1 && wire === 2) key = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
118
|
+
else if (field === 2 && wire === 2) value = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
119
|
+
else reader.skip(wire);
|
|
120
|
+
}
|
|
121
|
+
return { key, value };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function decodeFrame(bytes: Uint8Array): WsFrame {
|
|
125
|
+
const reader = new Reader(bytes);
|
|
126
|
+
const frame: WsFrame = {};
|
|
127
|
+
while (!reader.done) {
|
|
128
|
+
const tag = Number(reader.varint());
|
|
129
|
+
const field = tag >> 3;
|
|
130
|
+
const wire = tag & 7;
|
|
131
|
+
switch (field) {
|
|
132
|
+
case 1:
|
|
133
|
+
frame.SeqID = Number(reader.varint());
|
|
134
|
+
break;
|
|
135
|
+
case 2:
|
|
136
|
+
frame.LogID = Number(reader.varint());
|
|
137
|
+
break;
|
|
138
|
+
case 3:
|
|
139
|
+
frame.service = Number(reader.varint());
|
|
140
|
+
break;
|
|
141
|
+
case 4:
|
|
142
|
+
frame.method = Number(reader.varint());
|
|
143
|
+
break;
|
|
144
|
+
case 5:
|
|
145
|
+
frame.headers = [...(frame.headers ?? []), decodeHeader(reader.bytes(Number(reader.varint())))];
|
|
146
|
+
break;
|
|
147
|
+
case 6:
|
|
148
|
+
frame.payload_encoding = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
149
|
+
break;
|
|
150
|
+
case 7:
|
|
151
|
+
frame.payload_type = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
152
|
+
break;
|
|
153
|
+
case 8:
|
|
154
|
+
frame.payload = reader.bytes(Number(reader.varint()));
|
|
155
|
+
break;
|
|
156
|
+
case 9:
|
|
157
|
+
frame.LogIDNew = new TextDecoder().decode(reader.bytes(Number(reader.varint())));
|
|
158
|
+
break;
|
|
159
|
+
default:
|
|
160
|
+
reader.skip(wire);
|
|
161
|
+
break;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return frame;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function headerValue(frame: WsFrame, key: string): string | undefined {
|
|
168
|
+
return frame.headers?.find((header) => header.key === key)?.value;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function jsonPayload(value: unknown): Uint8Array {
|
|
172
|
+
return utf8.encode(JSON.stringify(value));
|
|
173
|
+
}
|
|
@@ -30,6 +30,17 @@ export function validateTargets(config: ChannelConfig): void {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
|
+
for (const route of config.inbound) {
|
|
34
|
+
const account = accounts.get(route.from.account);
|
|
35
|
+
if (!account) {
|
|
36
|
+
throw new Error(`config: inbound route sources unknown account "${route.from.account}"`);
|
|
37
|
+
}
|
|
38
|
+
if (account.platform !== route.from.platform) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`config: inbound route sources platform "${route.from.platform}" but account "${route.from.account}" is "${account.platform}"`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
33
44
|
}
|
|
34
45
|
|
|
35
46
|
export function toEndpoint(config: ChannelConfig, ruleId: string, target: RuleTarget): Endpoint {
|