aai-lark-bridge 0.2.9 → 0.2.11
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/dist/cli.js +657 -25
- package/dist/cli.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -4,7 +4,7 @@ import { Command } from "commander";
|
|
|
4
4
|
// package.json
|
|
5
5
|
var package_default = {
|
|
6
6
|
name: "aai-lark-bridge",
|
|
7
|
-
version: "0.2.
|
|
7
|
+
version: "0.2.11",
|
|
8
8
|
description: "Lark AI Native Bridge - Lark\u57FA\u7840\u8BBE\u65BD\u5C42\u548CCLI\u96C6\u6210",
|
|
9
9
|
type: "module",
|
|
10
10
|
main: "./dist/index.js",
|
|
@@ -14345,6 +14345,108 @@ function activeChannelCount(profile2) {
|
|
|
14345
14345
|
return active2.get(profile2)?.size ?? 0;
|
|
14346
14346
|
}
|
|
14347
14347
|
|
|
14348
|
+
// src/bridge/bot/stream-resilience.ts
|
|
14349
|
+
var DEFAULT_MAX_ATTEMPTS = 3;
|
|
14350
|
+
var DEFAULT_BASE_DELAY_MS = 500;
|
|
14351
|
+
var FEISHU_INTERNAL_ERROR_CODE = 2200;
|
|
14352
|
+
var trackers = /* @__PURE__ */ new WeakMap();
|
|
14353
|
+
function isTransientWriteError(err) {
|
|
14354
|
+
const raw = err;
|
|
14355
|
+
if (raw?.response?.data?.code === FEISHU_INTERNAL_ERROR_CODE) return true;
|
|
14356
|
+
const status = raw?.response?.status;
|
|
14357
|
+
if (typeof status === "number") return status === 429 || status >= 500;
|
|
14358
|
+
return typeof raw?.code === "string";
|
|
14359
|
+
}
|
|
14360
|
+
function installStreamResilience(channel, opts = {}) {
|
|
14361
|
+
const sender = channel.sender;
|
|
14362
|
+
const methods = [
|
|
14363
|
+
"updateCardElementContent",
|
|
14364
|
+
"sendCardByReference",
|
|
14365
|
+
"finishStreamingCard",
|
|
14366
|
+
"patchCard"
|
|
14367
|
+
];
|
|
14368
|
+
if (!sender || methods.some((m) => typeof sender[m] !== "function")) {
|
|
14369
|
+
log.warn("stream", "resilience-unavailable", {
|
|
14370
|
+
reason: "channel \u672A\u66B4\u9732 outbound sender\uFF08SDK \u7248\u672C\u53D8\u52A8\uFF1F\uFF09\uFF0C\u6D41\u5F0F\u5199\u5165\u4E0D\u91CD\u8BD5"
|
|
14371
|
+
});
|
|
14372
|
+
return false;
|
|
14373
|
+
}
|
|
14374
|
+
const s = sender;
|
|
14375
|
+
const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
14376
|
+
const baseDelayMs = opts.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
|
|
14377
|
+
const sleep2 = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
14378
|
+
const tracker = {
|
|
14379
|
+
streamOptsByCard: /* @__PURE__ */ new Map(),
|
|
14380
|
+
lostStreams: /* @__PURE__ */ new WeakSet(),
|
|
14381
|
+
messageIdByStream: /* @__PURE__ */ new WeakMap()
|
|
14382
|
+
};
|
|
14383
|
+
trackers.set(channel, tracker);
|
|
14384
|
+
async function withRetry(op, target, run) {
|
|
14385
|
+
for (let attempt = 1; ; attempt++) {
|
|
14386
|
+
try {
|
|
14387
|
+
return await run();
|
|
14388
|
+
} catch (err) {
|
|
14389
|
+
if (attempt >= maxAttempts || !isTransientWriteError(err)) throw err;
|
|
14390
|
+
const raw = err;
|
|
14391
|
+
log.warn("stream", "write-retry", {
|
|
14392
|
+
op,
|
|
14393
|
+
target,
|
|
14394
|
+
attempt,
|
|
14395
|
+
status: raw?.response?.status,
|
|
14396
|
+
code: raw?.response?.data?.code
|
|
14397
|
+
});
|
|
14398
|
+
await sleep2(baseDelayMs * 3 ** (attempt - 1));
|
|
14399
|
+
}
|
|
14400
|
+
}
|
|
14401
|
+
}
|
|
14402
|
+
const sendCardByReference = s.sendCardByReference.bind(s);
|
|
14403
|
+
s.sendCardByReference = async (to, idType, cardId, streamOpts) => {
|
|
14404
|
+
const messageId = await sendCardByReference(to, idType, cardId, streamOpts);
|
|
14405
|
+
if (streamOpts && typeof streamOpts === "object") {
|
|
14406
|
+
tracker.streamOptsByCard.set(cardId, streamOpts);
|
|
14407
|
+
if (typeof messageId === "string") tracker.messageIdByStream.set(streamOpts, messageId);
|
|
14408
|
+
}
|
|
14409
|
+
return messageId;
|
|
14410
|
+
};
|
|
14411
|
+
const updateCardElementContent = s.updateCardElementContent.bind(s);
|
|
14412
|
+
s.updateCardElementContent = async (cardId, elementId, content, sequence) => {
|
|
14413
|
+
try {
|
|
14414
|
+
await withRetry(
|
|
14415
|
+
"element-content",
|
|
14416
|
+
cardId,
|
|
14417
|
+
() => updateCardElementContent(cardId, elementId, content, sequence)
|
|
14418
|
+
);
|
|
14419
|
+
} catch (err) {
|
|
14420
|
+
const streamOpts = tracker.streamOptsByCard.get(cardId);
|
|
14421
|
+
if (streamOpts) tracker.lostStreams.add(streamOpts);
|
|
14422
|
+
log.warn("stream", "write-lost", {
|
|
14423
|
+
cardId,
|
|
14424
|
+
sequence,
|
|
14425
|
+
tracked: streamOpts !== void 0,
|
|
14426
|
+
err: err instanceof Error ? err.message : String(err)
|
|
14427
|
+
});
|
|
14428
|
+
throw err;
|
|
14429
|
+
}
|
|
14430
|
+
};
|
|
14431
|
+
const finishStreamingCard = s.finishStreamingCard.bind(s);
|
|
14432
|
+
s.finishStreamingCard = async (cardId, sequence, summary) => {
|
|
14433
|
+
try {
|
|
14434
|
+
await withRetry("finish", cardId, () => finishStreamingCard(cardId, sequence, summary));
|
|
14435
|
+
} finally {
|
|
14436
|
+
tracker.streamOptsByCard.delete(cardId);
|
|
14437
|
+
}
|
|
14438
|
+
};
|
|
14439
|
+
const patchCard = s.patchCard.bind(s);
|
|
14440
|
+
s.patchCard = (messageId, card) => withRetry("patch", messageId, () => patchCard(messageId, card));
|
|
14441
|
+
return true;
|
|
14442
|
+
}
|
|
14443
|
+
function streamWritesLost(channel, streamOpts) {
|
|
14444
|
+
return trackers.get(channel)?.lostStreams.has(streamOpts) ?? false;
|
|
14445
|
+
}
|
|
14446
|
+
function streamMessageId(channel, streamOpts) {
|
|
14447
|
+
return trackers.get(channel)?.messageIdByStream.get(streamOpts);
|
|
14448
|
+
}
|
|
14449
|
+
|
|
14348
14450
|
// src/bridge/bot/cot.ts
|
|
14349
14451
|
var ENDPOINTS2 = {
|
|
14350
14452
|
feishu: "https://open.feishu.cn",
|
|
@@ -14836,6 +14938,7 @@ async function startChannel(deps) {
|
|
|
14836
14938
|
respectProxyEnv: true
|
|
14837
14939
|
};
|
|
14838
14940
|
const channel = createLarkChannel(opts);
|
|
14941
|
+
installStreamResilience(channel);
|
|
14839
14942
|
const media = new MediaCache(channel, deps.appPaths?.mediaDir);
|
|
14840
14943
|
const pending = new PendingQueue(DEBOUNCE_MS, (scope, batch) => {
|
|
14841
14944
|
const firstMsg = batch[0];
|
|
@@ -15703,6 +15806,7 @@ async function runAgentBatch(deps) {
|
|
|
15703
15806
|
let latestState = startState;
|
|
15704
15807
|
let producerStarted = false;
|
|
15705
15808
|
let markdownCtrl;
|
|
15809
|
+
const streamOpts = { ...sendOpts };
|
|
15706
15810
|
const progress = createLazyProgressStream(
|
|
15707
15811
|
scope,
|
|
15708
15812
|
replyMode,
|
|
@@ -15717,7 +15821,7 @@ async function runAgentBatch(deps) {
|
|
|
15717
15821
|
await renderDone;
|
|
15718
15822
|
}
|
|
15719
15823
|
},
|
|
15720
|
-
|
|
15824
|
+
streamOpts
|
|
15721
15825
|
)
|
|
15722
15826
|
);
|
|
15723
15827
|
const renderDone = processAgentStream(
|
|
@@ -15750,7 +15854,20 @@ async function runAgentBatch(deps) {
|
|
|
15750
15854
|
}
|
|
15751
15855
|
});
|
|
15752
15856
|
} catch (err) {
|
|
15753
|
-
if (controls.profileConfig.agentKind !== "codex")
|
|
15857
|
+
if (controls.profileConfig.agentKind !== "codex") {
|
|
15858
|
+
await redeliverIfStreamWritesLost({
|
|
15859
|
+
channel,
|
|
15860
|
+
chatId,
|
|
15861
|
+
scope,
|
|
15862
|
+
progress,
|
|
15863
|
+
streamOpts,
|
|
15864
|
+
state: forView(latestState),
|
|
15865
|
+
replyMode,
|
|
15866
|
+
sendOpts,
|
|
15867
|
+
cardRenderOptions
|
|
15868
|
+
});
|
|
15869
|
+
throw err;
|
|
15870
|
+
}
|
|
15754
15871
|
log.fail("stream", err, { mode: replyMode, step: "progress-stream" });
|
|
15755
15872
|
}
|
|
15756
15873
|
await recallIfEmptyStreamedReply(channel, progress, forView(latestState), scope);
|
|
@@ -15780,6 +15897,18 @@ async function runAgentBatch(deps) {
|
|
|
15780
15897
|
sendOpts,
|
|
15781
15898
|
cardRenderOptions
|
|
15782
15899
|
});
|
|
15900
|
+
} else {
|
|
15901
|
+
await redeliverIfStreamWritesLost({
|
|
15902
|
+
channel,
|
|
15903
|
+
chatId,
|
|
15904
|
+
scope,
|
|
15905
|
+
progress,
|
|
15906
|
+
streamOpts,
|
|
15907
|
+
state: forView(latestState),
|
|
15908
|
+
replyMode,
|
|
15909
|
+
sendOpts,
|
|
15910
|
+
cardRenderOptions
|
|
15911
|
+
});
|
|
15783
15912
|
}
|
|
15784
15913
|
} else {
|
|
15785
15914
|
const finalState = await processAgentStream(
|
|
@@ -15813,14 +15942,24 @@ function createLazyProgressStream(scope, mode, open4) {
|
|
|
15813
15942
|
let stream2;
|
|
15814
15943
|
let openedAt;
|
|
15815
15944
|
let givenUp = false;
|
|
15945
|
+
let isSettled = false;
|
|
15816
15946
|
let settle;
|
|
15817
15947
|
const settled = new Promise((resolve3, reject4) => {
|
|
15818
15948
|
settle = (result) => {
|
|
15819
15949
|
result.then(resolve3, reject4);
|
|
15820
15950
|
};
|
|
15821
15951
|
});
|
|
15952
|
+
settled.then(
|
|
15953
|
+
() => {
|
|
15954
|
+
isSettled = true;
|
|
15955
|
+
},
|
|
15956
|
+
() => {
|
|
15957
|
+
isSettled = true;
|
|
15958
|
+
}
|
|
15959
|
+
);
|
|
15822
15960
|
return {
|
|
15823
15961
|
settled,
|
|
15962
|
+
isSettled: () => isSettled,
|
|
15824
15963
|
opened: () => stream2 !== void 0,
|
|
15825
15964
|
openedAt: () => openedAt,
|
|
15826
15965
|
ensureOpen: () => {
|
|
@@ -15872,25 +16011,54 @@ function scheduleProgressTerminalUpdate(channel, progress, state, scope, mode) {
|
|
|
15872
16011
|
void progress.settled.then(async (result) => {
|
|
15873
16012
|
const messageId = result?.messageId;
|
|
15874
16013
|
if (!messageId) return;
|
|
15875
|
-
|
|
15876
|
-
const terminalState = {
|
|
15877
|
-
...state,
|
|
15878
|
-
// Markdown never shows reasoning; a repair must preserve that boundary.
|
|
15879
|
-
reasoning: mode === "markdown" ? { content: "", active: false } : state.reasoning,
|
|
15880
|
-
blocks: state.terminal === "done" ? [...state.blocks, { kind: "text", content: "\u672C\u8F6E\u6267\u884C\u5DF2\u7ED3\u675F\u3002", streaming: false }] : state.blocks
|
|
15881
|
-
};
|
|
15882
|
-
await channel.updateCard(messageId, renderCard(terminalState));
|
|
15883
|
-
log.info("outbound", "progress-terminal-updated", { scope, messageId, terminal: state.terminal });
|
|
15884
|
-
} catch (err) {
|
|
15885
|
-
log.warn("outbound", "progress-terminal-update-failed", {
|
|
15886
|
-
scope,
|
|
15887
|
-
messageId,
|
|
15888
|
-
err: err instanceof Error ? err.message : String(err)
|
|
15889
|
-
});
|
|
15890
|
-
}
|
|
16014
|
+
await repairProgressMessage(channel, messageId, state, scope, mode);
|
|
15891
16015
|
}, () => {
|
|
15892
16016
|
});
|
|
15893
16017
|
}
|
|
16018
|
+
async function repairProgressMessage(channel, messageId, state, scope, mode) {
|
|
16019
|
+
try {
|
|
16020
|
+
const terminalState = {
|
|
16021
|
+
...state,
|
|
16022
|
+
// Markdown never shows reasoning; a repair must preserve that boundary.
|
|
16023
|
+
reasoning: mode === "markdown" ? { content: "", active: false } : state.reasoning,
|
|
16024
|
+
blocks: state.terminal === "done" ? [...state.blocks, { kind: "text", content: "\u672C\u8F6E\u6267\u884C\u5DF2\u7ED3\u675F\u3002", streaming: false }] : state.blocks
|
|
16025
|
+
};
|
|
16026
|
+
await channel.updateCard(messageId, renderCard(terminalState));
|
|
16027
|
+
log.info("outbound", "progress-terminal-updated", { scope, messageId, terminal: state.terminal });
|
|
16028
|
+
} catch (err) {
|
|
16029
|
+
log.warn("outbound", "progress-terminal-update-failed", {
|
|
16030
|
+
scope,
|
|
16031
|
+
messageId,
|
|
16032
|
+
err: err instanceof Error ? err.message : String(err)
|
|
16033
|
+
});
|
|
16034
|
+
}
|
|
16035
|
+
}
|
|
16036
|
+
async function redeliverIfStreamWritesLost(input) {
|
|
16037
|
+
const { channel, progress, scope } = input;
|
|
16038
|
+
if (!progress.opened() || progress.abandoned()) return;
|
|
16039
|
+
const check2 = async () => {
|
|
16040
|
+
const result = await progress.settled.catch(() => void 0);
|
|
16041
|
+
if (!streamWritesLost(channel, input.streamOpts)) return;
|
|
16042
|
+
const messageId = result?.messageId ?? streamMessageId(channel, input.streamOpts);
|
|
16043
|
+
log.warn("stream", "writes-lost-redeliver", { scope, mode: input.replyMode, messageId });
|
|
16044
|
+
await sendFinalReply({
|
|
16045
|
+
channel,
|
|
16046
|
+
chatId: input.chatId,
|
|
16047
|
+
scope,
|
|
16048
|
+
state: tailTextState(input.state),
|
|
16049
|
+
replyMode: input.replyMode,
|
|
16050
|
+
sendOpts: input.sendOpts,
|
|
16051
|
+
cardRenderOptions: input.cardRenderOptions
|
|
16052
|
+
});
|
|
16053
|
+
if (messageId && renderText(input.state).trim() !== "") {
|
|
16054
|
+
await repairProgressMessage(channel, messageId, input.state, scope, input.replyMode);
|
|
16055
|
+
}
|
|
16056
|
+
};
|
|
16057
|
+
const checked = check2().catch(
|
|
16058
|
+
(err) => log.fail("stream", err, { step: "writes-lost-redeliver" })
|
|
16059
|
+
);
|
|
16060
|
+
if (progress.isSettled()) await checked;
|
|
16061
|
+
}
|
|
15894
16062
|
async function recallIfEmptyStreamedReply(channel, progress, finalState, scope) {
|
|
15895
16063
|
if (!progress.opened()) return;
|
|
15896
16064
|
if (progress.abandoned()) {
|
|
@@ -16549,8 +16717,8 @@ function extractArray(v) {
|
|
|
16549
16717
|
function cliError(r, prefix) {
|
|
16550
16718
|
if (r.timedOut) return `${prefix}\uFF1A\u547D\u4EE4\u8D85\u65F6`;
|
|
16551
16719
|
const json = parseJson2(r.stdout) ?? parseJson2(r.stderr);
|
|
16552
|
-
const
|
|
16553
|
-
const detail = findString(json, /message|reason/i) ??
|
|
16720
|
+
const firstLine2 = (s) => s.trim().split("\n")[0]?.trim() || void 0;
|
|
16721
|
+
const detail = findString(json, /message|reason/i) ?? firstLine2(r.stderr) ?? firstLine2(r.stdout) ?? `\u9000\u51FA\u7801 ${r.code}`;
|
|
16554
16722
|
log.warn("user-im", "lark-cli-error", { detail });
|
|
16555
16723
|
return `${prefix}\uFF1A${detail}`;
|
|
16556
16724
|
}
|
|
@@ -17020,10 +17188,10 @@ async function userLoginComplete(profile2, rootDir, body) {
|
|
|
17020
17188
|
return { ok: true };
|
|
17021
17189
|
}
|
|
17022
17190
|
async function userChatsView(profile2, rootDir, channel, opts = {}) {
|
|
17023
|
-
const
|
|
17191
|
+
const query2 = (opts.query ?? "").trim();
|
|
17024
17192
|
let page;
|
|
17025
17193
|
try {
|
|
17026
|
-
page =
|
|
17194
|
+
page = query2 ? await searchUserChats({ profile: profile2, rootDir }, { query: query2, pageToken: opts.pageToken }) : await listUserChats({ profile: profile2, rootDir }, { pageToken: opts.pageToken });
|
|
17027
17195
|
} catch (err) {
|
|
17028
17196
|
throw new ApiError(400, err instanceof Error ? err.message : String(err));
|
|
17029
17197
|
}
|
|
@@ -17445,9 +17613,9 @@ async function route(req, res, deps, url) {
|
|
|
17445
17613
|
if (path === "/api/user-chats" && g) {
|
|
17446
17614
|
const profile2 = url.searchParams.get("profile") ?? await readActiveProfile(deps.rootDir);
|
|
17447
17615
|
if (!profile2) throw new HttpError(400, "no profile");
|
|
17448
|
-
const
|
|
17616
|
+
const query2 = url.searchParams.get("query") ?? void 0;
|
|
17449
17617
|
const pageToken = url.searchParams.get("pageToken") ?? void 0;
|
|
17450
|
-
sendJson(res, 200, await userChatsView(profile2, deps.rootDir, sup.channelFor(profile2), { query, pageToken }));
|
|
17618
|
+
sendJson(res, 200, await userChatsView(profile2, deps.rootDir, sup.channelFor(profile2), { query: query2, pageToken }));
|
|
17451
17619
|
return;
|
|
17452
17620
|
}
|
|
17453
17621
|
if (path === "/api/chats/add-bot" && p3) {
|
|
@@ -18511,6 +18679,467 @@ function openBrowser(url) {
|
|
|
18511
18679
|
}
|
|
18512
18680
|
}
|
|
18513
18681
|
|
|
18682
|
+
// src/bridge/cli/commands/user-gateway.ts
|
|
18683
|
+
import { spawnSync as spawnSync4 } from "child_process";
|
|
18684
|
+
import { existsSync as existsSync9 } from "fs";
|
|
18685
|
+
import { join as join27 } from "path";
|
|
18686
|
+
|
|
18687
|
+
// src/bridge/user-gateway/gateway.ts
|
|
18688
|
+
import { randomBytes as randomBytes8 } from "crypto";
|
|
18689
|
+
import { existsSync as existsSync8 } from "fs";
|
|
18690
|
+
import { mkdir as mkdir18, rm as rm13, writeFile as writeFile9 } from "fs/promises";
|
|
18691
|
+
import { join as join26 } from "path";
|
|
18692
|
+
var USER_READ_SCOPES = [
|
|
18693
|
+
"search:message",
|
|
18694
|
+
"im:message.p2p_msg:get_as_user",
|
|
18695
|
+
"im:message.group_msg:get_as_user",
|
|
18696
|
+
"im:message:readonly",
|
|
18697
|
+
"search:docs:read",
|
|
18698
|
+
"docx:document:readonly",
|
|
18699
|
+
"wiki:node:read",
|
|
18700
|
+
"drive:drive.metadata:readonly",
|
|
18701
|
+
"offline_access"
|
|
18702
|
+
];
|
|
18703
|
+
var READ_APIS = ["search-messages", "get-message", "list-chat-messages", "search-docs", "fetch-doc"];
|
|
18704
|
+
var HANDLE_TTL_MS = 5 * 6e4;
|
|
18705
|
+
var MESSAGE_MAX_AGE_MS = 2 * 6e4;
|
|
18706
|
+
var CLOCK_SKEW_MS = 3e4;
|
|
18707
|
+
var USED_TTL_MS = MESSAGE_MAX_AGE_MS + CLOCK_SKEW_MS + 6e4;
|
|
18708
|
+
var AUTH_POLL_MS = 5e3;
|
|
18709
|
+
var AUTH_MAX_MS = 10 * 6e4;
|
|
18710
|
+
var REVOKE_TEXT = "\u64A4\u9500\u6388\u6743";
|
|
18711
|
+
var MESSAGE_ID = /^om_[A-Za-z0-9_-]{1,100}$/;
|
|
18712
|
+
var CHAT_ID = /^oc_[A-Za-z0-9_-]{1,100}$/;
|
|
18713
|
+
var OPEN_ID = /^ou_[A-Za-z0-9_-]{1,100}$/;
|
|
18714
|
+
var RUN_ID = /^[A-Za-z0-9._:-]{1,200}$/;
|
|
18715
|
+
var PAGE_TOKEN = /^[A-Za-z0-9+/=_-]{1,500}$/;
|
|
18716
|
+
var DOC_REF = /^([A-Za-z0-9]{8,64}|https:\/\/[A-Za-z0-9.-]+\.(larksuite|feishu)\.(com|cn)\/[A-Za-z0-9/_?=&#.-]{1,300})$/;
|
|
18717
|
+
var tail6 = (id) => id.slice(-6);
|
|
18718
|
+
function isRecord6(v) {
|
|
18719
|
+
return Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
18720
|
+
}
|
|
18721
|
+
function parseJson4(text) {
|
|
18722
|
+
const t = text.trim();
|
|
18723
|
+
if (!t) return void 0;
|
|
18724
|
+
try {
|
|
18725
|
+
return JSON.parse(t);
|
|
18726
|
+
} catch {
|
|
18727
|
+
const start = t.search(/[[{]/);
|
|
18728
|
+
if (start < 0) return void 0;
|
|
18729
|
+
try {
|
|
18730
|
+
return JSON.parse(t.slice(start));
|
|
18731
|
+
} catch {
|
|
18732
|
+
return void 0;
|
|
18733
|
+
}
|
|
18734
|
+
}
|
|
18735
|
+
}
|
|
18736
|
+
function firstLine(s) {
|
|
18737
|
+
return s.trim().split("\n")[0]?.trim().slice(0, 300) ?? "";
|
|
18738
|
+
}
|
|
18739
|
+
var BadRequest = class extends Error {
|
|
18740
|
+
};
|
|
18741
|
+
function str2(input, key, re, required = true) {
|
|
18742
|
+
const v = input[key];
|
|
18743
|
+
if (v === void 0 && !required) return void 0;
|
|
18744
|
+
if (typeof v !== "string" || !re.test(v)) throw new BadRequest(`${key} \u683C\u5F0F\u4E0D\u5BF9`);
|
|
18745
|
+
return v;
|
|
18746
|
+
}
|
|
18747
|
+
function query(input) {
|
|
18748
|
+
const v = input.query;
|
|
18749
|
+
if (typeof v !== "string" || !v.trim() || v.length > 200) throw new BadRequest("query \u8981 1\u2013200 \u4E2A\u5B57\u7B26");
|
|
18750
|
+
return v;
|
|
18751
|
+
}
|
|
18752
|
+
function pageSize(input, max) {
|
|
18753
|
+
const v = input.pageSize;
|
|
18754
|
+
if (v === void 0) return void 0;
|
|
18755
|
+
if (!Number.isInteger(v) || v < 1 || v > max) throw new BadRequest(`pageSize \u8981 1\u2013${max}`);
|
|
18756
|
+
return String(v);
|
|
18757
|
+
}
|
|
18758
|
+
function readArgs(api, input) {
|
|
18759
|
+
switch (api) {
|
|
18760
|
+
case "search-messages": {
|
|
18761
|
+
const params = { page_size: pageSize(input, 50) ?? "20" };
|
|
18762
|
+
const token = str2(input, "pageToken", PAGE_TOKEN, false);
|
|
18763
|
+
if (token) params.page_token = token;
|
|
18764
|
+
return ["api", "POST", "/open-apis/im/v1/messages/search", "--as", "user", "--params", JSON.stringify(params), "--data", JSON.stringify({ query: query(input) })];
|
|
18765
|
+
}
|
|
18766
|
+
case "get-message":
|
|
18767
|
+
return ["api", "GET", `/open-apis/im/v1/messages/${str2(input, "messageId", MESSAGE_ID)}`, "--as", "user"];
|
|
18768
|
+
case "list-chat-messages": {
|
|
18769
|
+
const sort = input.sortType ?? "ByCreateTimeDesc";
|
|
18770
|
+
if (sort !== "ByCreateTimeDesc" && sort !== "ByCreateTimeAsc") throw new BadRequest("sortType \u53EA\u80FD\u662F ByCreateTimeDesc \u6216 ByCreateTimeAsc");
|
|
18771
|
+
const params = {
|
|
18772
|
+
container_id_type: "chat",
|
|
18773
|
+
container_id: str2(input, "chatId", CHAT_ID),
|
|
18774
|
+
page_size: pageSize(input, 50) ?? "20",
|
|
18775
|
+
sort_type: sort
|
|
18776
|
+
};
|
|
18777
|
+
const token = str2(input, "pageToken", PAGE_TOKEN, false);
|
|
18778
|
+
if (token) params.page_token = token;
|
|
18779
|
+
return ["api", "GET", "/open-apis/im/v1/messages", "--as", "user", "--params", JSON.stringify(params)];
|
|
18780
|
+
}
|
|
18781
|
+
case "search-docs": {
|
|
18782
|
+
const args = ["docs", "+search", "--as", "user", "--json", "--query", query(input)];
|
|
18783
|
+
const size = pageSize(input, 20);
|
|
18784
|
+
if (size) args.push("--page-size", size);
|
|
18785
|
+
const token = str2(input, "pageToken", PAGE_TOKEN, false);
|
|
18786
|
+
if (token) args.push("--page-token", token);
|
|
18787
|
+
return args;
|
|
18788
|
+
}
|
|
18789
|
+
case "fetch-doc":
|
|
18790
|
+
return ["docs", "+fetch", "--as", "user", "--json", "--doc", str2(input, "doc", DOC_REF), "--doc-format", "markdown"];
|
|
18791
|
+
}
|
|
18792
|
+
}
|
|
18793
|
+
function isReadApi(api) {
|
|
18794
|
+
return READ_APIS.includes(api);
|
|
18795
|
+
}
|
|
18796
|
+
function createGateway(opts) {
|
|
18797
|
+
const now = opts.now ?? Date.now;
|
|
18798
|
+
const sleep2 = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms).unref()));
|
|
18799
|
+
const handles = /* @__PURE__ */ new Map();
|
|
18800
|
+
const used = /* @__PURE__ */ new Map();
|
|
18801
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
18802
|
+
const pendingAuth = /* @__PURE__ */ new Map();
|
|
18803
|
+
const tokenRoot = join26(opts.stateDir, "user-tokens", opts.appId);
|
|
18804
|
+
const userDir = (openId) => join26(tokenRoot, openId);
|
|
18805
|
+
const authorizedMark = (openId) => join26(userDir(openId), ".authorized");
|
|
18806
|
+
const isAuthorized = (openId) => existsSync8(authorizedMark(openId));
|
|
18807
|
+
function env(dir) {
|
|
18808
|
+
return {
|
|
18809
|
+
...buildLarkChannelEnv({ larkCliSourceConfigFile: opts.larkSourceConfig, larkCliConfigDir: dir }),
|
|
18810
|
+
LARKSUITE_CLI_DATA_DIR: dir,
|
|
18811
|
+
LARKSUITE_CLI_NO_UPDATE_NOTIFIER: "1",
|
|
18812
|
+
LARKSUITE_CLI_NO_SKILLS_NOTIFIER: "1"
|
|
18813
|
+
};
|
|
18814
|
+
}
|
|
18815
|
+
const appDir = join26(opts.stateDir, "app");
|
|
18816
|
+
const asApp = (args, timeoutMs = 3e4) => opts.exec(args, env(appDir), timeoutMs);
|
|
18817
|
+
function sweep() {
|
|
18818
|
+
const t = now();
|
|
18819
|
+
for (const [h, v] of handles) if (v.expiresAt <= t) handles.delete(h);
|
|
18820
|
+
for (const [m, until] of used) if (until <= t) used.delete(m);
|
|
18821
|
+
}
|
|
18822
|
+
async function verify(messageId) {
|
|
18823
|
+
sweep();
|
|
18824
|
+
if (used.has(messageId) || inFlight.has(messageId)) {
|
|
18825
|
+
log.warn("user-gateway", "identity.replay", { messageId });
|
|
18826
|
+
return "used";
|
|
18827
|
+
}
|
|
18828
|
+
inFlight.add(messageId);
|
|
18829
|
+
try {
|
|
18830
|
+
return await check2(messageId);
|
|
18831
|
+
} finally {
|
|
18832
|
+
inFlight.delete(messageId);
|
|
18833
|
+
}
|
|
18834
|
+
}
|
|
18835
|
+
async function check2(messageId) {
|
|
18836
|
+
const msg = await asApp(["api", "GET", `/open-apis/im/v1/messages/${messageId}`, "--as", "bot"]);
|
|
18837
|
+
const mjson = parseJson4(msg.stdout);
|
|
18838
|
+
const item = isRecord6(mjson) && isRecord6(mjson.data) && Array.isArray(mjson.data.items) ? mjson.data.items[0] : void 0;
|
|
18839
|
+
if (msg.code !== 0 || !isRecord6(item)) {
|
|
18840
|
+
log.warn("user-gateway", "verify.message-unreadable", { messageId, detail: firstLine(msg.stderr || msg.stdout) });
|
|
18841
|
+
return msg.code === 0 ? "not_found" : "lark_error";
|
|
18842
|
+
}
|
|
18843
|
+
const sender = isRecord6(item.sender) ? item.sender : {};
|
|
18844
|
+
if (sender.sender_type !== "user" || sender.id_type !== "open_id" || typeof sender.id !== "string" || !OPEN_ID.test(sender.id)) {
|
|
18845
|
+
return "not_user";
|
|
18846
|
+
}
|
|
18847
|
+
const created = Number(item.create_time);
|
|
18848
|
+
const t = now();
|
|
18849
|
+
if (!Number.isFinite(created) || t - created > MESSAGE_MAX_AGE_MS || created - t > CLOCK_SKEW_MS) return "stale";
|
|
18850
|
+
const chatId = typeof item.chat_id === "string" ? item.chat_id : "";
|
|
18851
|
+
if (!CHAT_ID.test(chatId)) return "not_found";
|
|
18852
|
+
const chat = await asApp(["api", "GET", `/open-apis/im/v1/chats/${chatId}`, "--as", "bot"]);
|
|
18853
|
+
const cjson = parseJson4(chat.stdout);
|
|
18854
|
+
const mode = isRecord6(cjson) && isRecord6(cjson.data) ? cjson.data.chat_mode : void 0;
|
|
18855
|
+
if (chat.code !== 0) return "lark_error";
|
|
18856
|
+
if (mode !== "p2p") return "not_p2p";
|
|
18857
|
+
used.set(messageId, t + USED_TTL_MS);
|
|
18858
|
+
let text;
|
|
18859
|
+
if (item.msg_type === "text" && isRecord6(item.body) && typeof item.body.content === "string") {
|
|
18860
|
+
const body = parseJson4(item.body.content);
|
|
18861
|
+
if (isRecord6(body) && typeof body.text === "string") text = body.text;
|
|
18862
|
+
}
|
|
18863
|
+
return { openId: sender.id, ...text !== void 0 ? { text } : {} };
|
|
18864
|
+
}
|
|
18865
|
+
async function sendAuthCard(openId, url) {
|
|
18866
|
+
const card = {
|
|
18867
|
+
config: { wide_screen_mode: true },
|
|
18868
|
+
header: { template: "blue", title: { tag: "plain_text", content: "\u6388\u6743 bot \u7528\u4F60\u7684\u8EAB\u4EFD\u53EA\u8BFB" } },
|
|
18869
|
+
elements: [
|
|
18870
|
+
{
|
|
18871
|
+
tag: "markdown",
|
|
18872
|
+
content: `\u6388\u6743\u540E\uFF0C\u4F60\u79C1\u804A\u6211\u63D0\u95EE\u65F6\uFF0C\u6211\u53EF\u4EE5\u7528\u4F60\u7684\u8EAB\u4EFD**\u53EA\u8BFB**\u4F60\u7684\u6D88\u606F\u548C\u6587\u6863\uFF08\u641C\u6D88\u606F\u3001\u770B\u6D88\u606F\u3001\u770B\u4F1A\u8BDD\u5386\u53F2\u3001\u641C\u6587\u6863\u3001\u8BFB\u6587\u6863\uFF09\uFF0C\u4E0D\u80FD\u53D1\u6D88\u606F\u3001\u4E0D\u80FD\u6539\u6587\u6863\u3002
|
|
18873
|
+
\u94FE\u63A5 10 \u5206\u949F\u5185\u6709\u6548\u3002\u4E0D\u60F3\u7528\u4E86\uFF0C\u79C1\u804A\u6211\u53D1\u300C${REVOKE_TEXT}\u300D\u3002`
|
|
18874
|
+
},
|
|
18875
|
+
{ tag: "action", actions: [{ tag: "button", type: "primary", text: { tag: "plain_text", content: "\u53BB\u6388\u6743" }, url }] }
|
|
18876
|
+
]
|
|
18877
|
+
};
|
|
18878
|
+
const r = await asApp([
|
|
18879
|
+
"api",
|
|
18880
|
+
"POST",
|
|
18881
|
+
"/open-apis/im/v1/messages",
|
|
18882
|
+
"--as",
|
|
18883
|
+
"bot",
|
|
18884
|
+
"--params",
|
|
18885
|
+
JSON.stringify({ receive_id_type: "open_id" }),
|
|
18886
|
+
"--data",
|
|
18887
|
+
JSON.stringify({ receive_id: openId, msg_type: "interactive", content: JSON.stringify(card) })
|
|
18888
|
+
]);
|
|
18889
|
+
if (r.code !== 0) throw new Error(`\u53D1\u6388\u6743\u5361\u7247\u5931\u8D25\uFF1A${firstLine(r.stderr || r.stdout)}`);
|
|
18890
|
+
}
|
|
18891
|
+
async function startAuth(openId) {
|
|
18892
|
+
if (pendingAuth.has(openId)) return;
|
|
18893
|
+
let release;
|
|
18894
|
+
const placeholder = new Promise((r) => release = r);
|
|
18895
|
+
pendingAuth.set(openId, placeholder);
|
|
18896
|
+
let poll;
|
|
18897
|
+
try {
|
|
18898
|
+
poll = await beginAuth(openId);
|
|
18899
|
+
} catch (err) {
|
|
18900
|
+
pendingAuth.delete(openId);
|
|
18901
|
+
throw err;
|
|
18902
|
+
} finally {
|
|
18903
|
+
release();
|
|
18904
|
+
}
|
|
18905
|
+
const wait = poll().catch((err) => log.warn("user-gateway", "auth.failed", { sender: tail6(openId), detail: String(err) })).finally(() => {
|
|
18906
|
+
if (pendingAuth.get(openId) === wait) pendingAuth.delete(openId);
|
|
18907
|
+
});
|
|
18908
|
+
pendingAuth.set(openId, wait);
|
|
18909
|
+
}
|
|
18910
|
+
async function beginAuth(openId) {
|
|
18911
|
+
const dir = userDir(openId);
|
|
18912
|
+
await mkdir18(dir, { recursive: true, mode: 448 });
|
|
18913
|
+
const start = await opts.exec(
|
|
18914
|
+
["auth", "login", "--no-wait", "--json", "--scope", USER_READ_SCOPES.join(" ")],
|
|
18915
|
+
env(dir),
|
|
18916
|
+
3e4
|
|
18917
|
+
);
|
|
18918
|
+
const json = parseJson4(start.stdout);
|
|
18919
|
+
const pick = (keys) => {
|
|
18920
|
+
for (const k of keys) if (isRecord6(json) && typeof json[k] === "string" && json[k]) return json[k];
|
|
18921
|
+
return void 0;
|
|
18922
|
+
};
|
|
18923
|
+
const url = pick(["verification_uri_complete", "verificationUriComplete", "verification_url", "verificationUrl", "verification_uri", "verificationUri"]);
|
|
18924
|
+
const deviceCode = pick(["device_code", "deviceCode"]);
|
|
18925
|
+
if (start.code !== 0 || !url || !deviceCode) throw new Error(`\u53D1\u8D77\u6388\u6743\u5931\u8D25\uFF1A${firstLine(start.stderr || start.stdout)}`);
|
|
18926
|
+
await sendAuthCard(openId, url);
|
|
18927
|
+
log.info("user-gateway", "auth.card-sent", { sender: tail6(openId) });
|
|
18928
|
+
return async () => {
|
|
18929
|
+
const deadline = now() + AUTH_MAX_MS;
|
|
18930
|
+
while (now() < deadline) {
|
|
18931
|
+
await sleep2(AUTH_POLL_MS);
|
|
18932
|
+
const r = await opts.exec(["auth", "login", "--device-code", deviceCode, "--json"], env(dir), 3e4);
|
|
18933
|
+
if (r.code === 0) {
|
|
18934
|
+
await writeFile9(authorizedMark(openId), `${new Date(now()).toISOString()}
|
|
18935
|
+
`, { mode: 384 });
|
|
18936
|
+
log.info("user-gateway", "auth.completed", { sender: tail6(openId) });
|
|
18937
|
+
return;
|
|
18938
|
+
}
|
|
18939
|
+
}
|
|
18940
|
+
log.warn("user-gateway", "auth.timeout", { sender: tail6(openId) });
|
|
18941
|
+
};
|
|
18942
|
+
}
|
|
18943
|
+
return {
|
|
18944
|
+
/** POST /handles:核实提问人,发句柄;没授权就发卡片并返回 need_auth。 */
|
|
18945
|
+
async requestHandle(input) {
|
|
18946
|
+
let messageId, runId;
|
|
18947
|
+
try {
|
|
18948
|
+
messageId = str2(input, "messageId", MESSAGE_ID);
|
|
18949
|
+
runId = str2(input, "runId", RUN_ID);
|
|
18950
|
+
} catch {
|
|
18951
|
+
return { status: "bad_request" };
|
|
18952
|
+
}
|
|
18953
|
+
const v = await verify(messageId);
|
|
18954
|
+
if (typeof v === "string") {
|
|
18955
|
+
log.info("user-gateway", "handle.refused", { messageId, runId, result: v });
|
|
18956
|
+
return { status: v };
|
|
18957
|
+
}
|
|
18958
|
+
if (!isAuthorized(v.openId)) {
|
|
18959
|
+
try {
|
|
18960
|
+
await startAuth(v.openId);
|
|
18961
|
+
} catch (err) {
|
|
18962
|
+
log.warn("user-gateway", "auth.start-failed", { sender: tail6(v.openId), messageId, runId, detail: String(err) });
|
|
18963
|
+
return { status: "auth_failed" };
|
|
18964
|
+
}
|
|
18965
|
+
log.info("user-gateway", "handle.need-auth", { sender: tail6(v.openId), messageId, runId });
|
|
18966
|
+
return { status: "need_auth" };
|
|
18967
|
+
}
|
|
18968
|
+
const handle2 = randomBytes8(32).toString("base64url");
|
|
18969
|
+
const expiresAt = now() + HANDLE_TTL_MS;
|
|
18970
|
+
handles.set(handle2, { openId: v.openId, messageId, runId, expiresAt });
|
|
18971
|
+
log.info("user-gateway", "handle.issued", { identity: "user", sender: tail6(v.openId), messageId, runId });
|
|
18972
|
+
return { status: "ok", handle: handle2, expiresAt };
|
|
18973
|
+
},
|
|
18974
|
+
/** DELETE /handles/{runId}:运行结束,作废这次运行的句柄。 */
|
|
18975
|
+
dropHandles(runId) {
|
|
18976
|
+
let n = 0;
|
|
18977
|
+
for (const [h, v] of handles) {
|
|
18978
|
+
if (v.runId === runId) {
|
|
18979
|
+
handles.delete(h);
|
|
18980
|
+
n++;
|
|
18981
|
+
}
|
|
18982
|
+
}
|
|
18983
|
+
if (n) log.info("user-gateway", "handle.dropped", { runId, count: n });
|
|
18984
|
+
return n;
|
|
18985
|
+
},
|
|
18986
|
+
/** POST /read/{api}:凭句柄找到提问人,用他的目录跑 lark-cli。 */
|
|
18987
|
+
async read(handle2, api, input) {
|
|
18988
|
+
sweep();
|
|
18989
|
+
const h = handles.get(handle2);
|
|
18990
|
+
if (!h) return { status: "expired" };
|
|
18991
|
+
let args;
|
|
18992
|
+
try {
|
|
18993
|
+
args = readArgs(api, input);
|
|
18994
|
+
} catch (err) {
|
|
18995
|
+
return { status: "bad_request", detail: err instanceof BadRequest ? err.message : String(err) };
|
|
18996
|
+
}
|
|
18997
|
+
const r = await opts.exec(args, env(userDir(h.openId)), 6e4);
|
|
18998
|
+
const fields = { identity: "user", sender: tail6(h.openId), messageId: h.messageId, runId: h.runId, api };
|
|
18999
|
+
if (r.code !== 0) {
|
|
19000
|
+
log.warn("user-gateway", "read.failed", { ...fields, result: "lark_error" });
|
|
19001
|
+
return { status: "lark_error", detail: r.timedOut ? "\u547D\u4EE4\u8D85\u65F6" : firstLine(r.stderr || r.stdout) };
|
|
19002
|
+
}
|
|
19003
|
+
log.info("user-gateway", "read.ok", { ...fields, result: "ok" });
|
|
19004
|
+
return { status: "ok", data: parseJson4(r.stdout) ?? r.stdout };
|
|
19005
|
+
},
|
|
19006
|
+
/** POST /revoke:核实这条消息是本人私聊发的「撤销授权」,删掉他的目录和句柄。 */
|
|
19007
|
+
async revoke(input) {
|
|
19008
|
+
let messageId;
|
|
19009
|
+
try {
|
|
19010
|
+
messageId = str2(input, "messageId", MESSAGE_ID);
|
|
19011
|
+
} catch {
|
|
19012
|
+
return { status: "bad_request" };
|
|
19013
|
+
}
|
|
19014
|
+
const v = await verify(messageId);
|
|
19015
|
+
if (typeof v === "string") return { status: v };
|
|
19016
|
+
if (v.text?.trim() !== REVOKE_TEXT) return { status: "not_revoke" };
|
|
19017
|
+
for (const [h, x] of handles) if (x.openId === v.openId) handles.delete(h);
|
|
19018
|
+
const had = existsSync8(userDir(v.openId));
|
|
19019
|
+
await rm13(userDir(v.openId), { recursive: true, force: true });
|
|
19020
|
+
log.info("user-gateway", "auth.revoked", { sender: tail6(v.openId), messageId, had });
|
|
19021
|
+
return { status: had ? "revoked" : "not_authorized" };
|
|
19022
|
+
},
|
|
19023
|
+
/** 测试用:等正在进行的授权轮询结束。 */
|
|
19024
|
+
async settle() {
|
|
19025
|
+
await Promise.all([...pendingAuth.values()]);
|
|
19026
|
+
}
|
|
19027
|
+
};
|
|
19028
|
+
}
|
|
19029
|
+
|
|
19030
|
+
// src/bridge/user-gateway/server.ts
|
|
19031
|
+
import { createHash as createHash8, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
19032
|
+
import { createServer as createServer2 } from "http";
|
|
19033
|
+
var MAX_BODY = 16 * 1024;
|
|
19034
|
+
var digest = (s) => createHash8("sha256").update(s).digest();
|
|
19035
|
+
function tokenOk(given, expected) {
|
|
19036
|
+
if (typeof given !== "string" || !given) return false;
|
|
19037
|
+
return timingSafeEqual3(digest(given), expected);
|
|
19038
|
+
}
|
|
19039
|
+
function send2(res, code, body) {
|
|
19040
|
+
const text = JSON.stringify(body);
|
|
19041
|
+
res.writeHead(code, { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(text) });
|
|
19042
|
+
res.end(text);
|
|
19043
|
+
}
|
|
19044
|
+
var BodyError = class extends Error {
|
|
19045
|
+
constructor(code) {
|
|
19046
|
+
super(String(code));
|
|
19047
|
+
this.code = code;
|
|
19048
|
+
}
|
|
19049
|
+
code;
|
|
19050
|
+
};
|
|
19051
|
+
async function readBody(req) {
|
|
19052
|
+
const chunks = [];
|
|
19053
|
+
let size = 0;
|
|
19054
|
+
for await (const chunk of req) {
|
|
19055
|
+
size += chunk.length;
|
|
19056
|
+
if (size > MAX_BODY) throw new BodyError(413);
|
|
19057
|
+
chunks.push(chunk);
|
|
19058
|
+
}
|
|
19059
|
+
if (!size) return {};
|
|
19060
|
+
try {
|
|
19061
|
+
const v = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
19062
|
+
if (v && typeof v === "object" && !Array.isArray(v)) return v;
|
|
19063
|
+
} catch {
|
|
19064
|
+
}
|
|
19065
|
+
throw new BodyError(400);
|
|
19066
|
+
}
|
|
19067
|
+
function createGatewayServer(opts) {
|
|
19068
|
+
if (!opts.gatewayToken) throw new Error("\u7F51\u5173\u53E3\u4EE4\u4E3A\u7A7A\uFF0C\u4E0D\u542F\u52A8");
|
|
19069
|
+
const expected = digest(opts.gatewayToken);
|
|
19070
|
+
const { gateway } = opts;
|
|
19071
|
+
async function route2(req, res) {
|
|
19072
|
+
const url = new URL(req.url ?? "/", "http://gateway");
|
|
19073
|
+
const path = url.pathname;
|
|
19074
|
+
const method = req.method ?? "GET";
|
|
19075
|
+
if (method === "GET" && path === "/healthz") return send2(res, 200, { status: "ok" });
|
|
19076
|
+
const admin = method === "POST" && (path === "/handles" || path === "/revoke") || method === "DELETE" && path.startsWith("/handles/");
|
|
19077
|
+
if (admin) {
|
|
19078
|
+
if (!tokenOk(req.headers["x-gateway-token"], expected)) {
|
|
19079
|
+
log.warn("user-gateway", "request.unauthorized", { method, route: path.startsWith("/handles/") ? "handles/:runId" : path.slice(1) });
|
|
19080
|
+
return send2(res, 401, { status: "unauthorized" });
|
|
19081
|
+
}
|
|
19082
|
+
if (method === "DELETE") {
|
|
19083
|
+
const runId = decodeURIComponent(path.slice("/handles/".length));
|
|
19084
|
+
return send2(res, 200, { status: "ok", dropped: gateway.dropHandles(runId) });
|
|
19085
|
+
}
|
|
19086
|
+
const body = await readBody(req);
|
|
19087
|
+
if (path === "/handles") return send2(res, 200, await gateway.requestHandle(body));
|
|
19088
|
+
return send2(res, 200, await gateway.revoke(body));
|
|
19089
|
+
}
|
|
19090
|
+
const read = method === "POST" ? /^\/read\/([a-z-]+)$/.exec(path) : null;
|
|
19091
|
+
if (read) {
|
|
19092
|
+
const api = read[1] ?? "";
|
|
19093
|
+
if (!isReadApi(api)) return send2(res, 404, { status: "unknown_api" });
|
|
19094
|
+
const auth = req.headers.authorization;
|
|
19095
|
+
const handle2 = typeof auth === "string" && auth.startsWith("Bearer ") ? auth.slice(7).trim() : "";
|
|
19096
|
+
if (!handle2) return send2(res, 200, { status: "expired" });
|
|
19097
|
+
return send2(res, 200, await gateway.read(handle2, api, await readBody(req)));
|
|
19098
|
+
}
|
|
19099
|
+
return send2(res, 404, { status: "not_found" });
|
|
19100
|
+
}
|
|
19101
|
+
return createServer2((req, res) => {
|
|
19102
|
+
route2(req, res).catch((err) => {
|
|
19103
|
+
if (err instanceof BodyError) return send2(res, err.code, { status: err.code === 413 ? "too_large" : "bad_request" });
|
|
19104
|
+
log.warn("user-gateway", "request.failed", { detail: String(err) });
|
|
19105
|
+
if (!res.headersSent) send2(res, 500, { status: "error" });
|
|
19106
|
+
});
|
|
19107
|
+
});
|
|
19108
|
+
}
|
|
19109
|
+
|
|
19110
|
+
// src/bridge/cli/commands/user-gateway.ts
|
|
19111
|
+
function fetchToken(cmd) {
|
|
19112
|
+
const [bin, ...args] = cmd.trim().split(/\s+/);
|
|
19113
|
+
if (!bin) throw new Error("--token-cmd \u4E3A\u7A7A");
|
|
19114
|
+
const r = spawnSync4(bin, args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 3e4 });
|
|
19115
|
+
const value = r.status === 0 ? r.stdout.trim() : "";
|
|
19116
|
+
if (!value) throw new Error(`\u53D6\u7F51\u5173\u53E3\u4EE4\u5931\u8D25\uFF08${bin} \u9000\u51FA\u7801 ${r.status}\uFF09`);
|
|
19117
|
+
return value;
|
|
19118
|
+
}
|
|
19119
|
+
async function runUserGateway(opts) {
|
|
19120
|
+
if (!/^cli_[A-Za-z0-9]+$/.test(opts.appId)) throw new Error("--app-id \u683C\u5F0F\u4E0D\u5BF9");
|
|
19121
|
+
if (!existsSync9(opts.larkSourceConfig)) throw new Error(`\u627E\u4E0D\u5230 lark-cli source \u914D\u7F6E\uFF1A${opts.larkSourceConfig}`);
|
|
19122
|
+
const port = Number(opts.port ?? 8788);
|
|
19123
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("--port \u4E0D\u5BF9");
|
|
19124
|
+
configureLogger({ logsDir: join27(opts.stateDir, "logs") });
|
|
19125
|
+
const gateway = createGateway({
|
|
19126
|
+
appId: opts.appId,
|
|
19127
|
+
stateDir: opts.stateDir,
|
|
19128
|
+
larkSourceConfig: opts.larkSourceConfig,
|
|
19129
|
+
exec: defaultExec
|
|
19130
|
+
});
|
|
19131
|
+
const pass = fetchToken(opts.tokenCmd);
|
|
19132
|
+
const server = createGatewayServer({ gateway, gatewayToken: pass });
|
|
19133
|
+
await new Promise((resolve3) => server.listen(port, opts.host ?? "0.0.0.0", resolve3));
|
|
19134
|
+
log.info("user-gateway", "started", { port });
|
|
19135
|
+
console.log(`user-gateway listening on ${opts.host ?? "0.0.0.0"}:${port}`);
|
|
19136
|
+
await new Promise((resolve3) => {
|
|
19137
|
+
const stop2 = () => server.close(() => resolve3());
|
|
19138
|
+
process.once("SIGTERM", stop2);
|
|
19139
|
+
process.once("SIGINT", stop2);
|
|
19140
|
+
});
|
|
19141
|
+
}
|
|
19142
|
+
|
|
18514
19143
|
// src/bridge/cli/index.ts
|
|
18515
19144
|
var program = new Command();
|
|
18516
19145
|
program.name("aai-lark-bridge").description("Bridge Feishu/Lark messenger with local CLI coding agents").version(package_default.version, "-v, --version");
|
|
@@ -18520,6 +19149,9 @@ program.command("run").description("Run the bridge in the foreground (was `start
|
|
|
18520
19149
|
program.command("migrate").description("Migrate legacy bridge config/state into the current profile layout").option("-c, --config <path>", "path to config file").option("--profile <name>", "target profile name for legacy v1 config migration").option("--agent <kind>", "agent kind for legacy v1 profile migration (claude or codex)").action(async (opts) => {
|
|
18521
19150
|
await runMigrate(opts);
|
|
18522
19151
|
});
|
|
19152
|
+
program.command("user-gateway").description("Run the per-sender user-token gateway (intent 0046); keeps user tokens out of the agent container").requiredOption("--app-id <id>", "App ID whose users authorize").requiredOption("--state-dir <path>", "gateway volume; user tokens live under user-tokens/<appId>/<open_id>/").requiredOption("--lark-source-config <path>", "lark-cli source config with the app id and secret provider").requiredOption("--token-cmd <cmd>", 'command printing the gateway token, e.g. "sdlc-secret gateway-token" (no shell)').option("--host <host>", "listen address", "0.0.0.0").option("--port <port>", "listen port", "8788").action(async (opts) => {
|
|
19153
|
+
await runUserGateway(opts);
|
|
19154
|
+
});
|
|
18523
19155
|
var profile = program.command("profile").description("Manage local bridge profiles");
|
|
18524
19156
|
profile.command("list").description("List configured profiles").action(async () => {
|
|
18525
19157
|
await runProfileList();
|