aai-lark-bridge 0.2.10 → 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 +471 -7
- 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",
|
|
@@ -16717,8 +16717,8 @@ function extractArray(v) {
|
|
|
16717
16717
|
function cliError(r, prefix) {
|
|
16718
16718
|
if (r.timedOut) return `${prefix}\uFF1A\u547D\u4EE4\u8D85\u65F6`;
|
|
16719
16719
|
const json = parseJson2(r.stdout) ?? parseJson2(r.stderr);
|
|
16720
|
-
const
|
|
16721
|
-
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}`;
|
|
16722
16722
|
log.warn("user-im", "lark-cli-error", { detail });
|
|
16723
16723
|
return `${prefix}\uFF1A${detail}`;
|
|
16724
16724
|
}
|
|
@@ -17188,10 +17188,10 @@ async function userLoginComplete(profile2, rootDir, body) {
|
|
|
17188
17188
|
return { ok: true };
|
|
17189
17189
|
}
|
|
17190
17190
|
async function userChatsView(profile2, rootDir, channel, opts = {}) {
|
|
17191
|
-
const
|
|
17191
|
+
const query2 = (opts.query ?? "").trim();
|
|
17192
17192
|
let page;
|
|
17193
17193
|
try {
|
|
17194
|
-
page =
|
|
17194
|
+
page = query2 ? await searchUserChats({ profile: profile2, rootDir }, { query: query2, pageToken: opts.pageToken }) : await listUserChats({ profile: profile2, rootDir }, { pageToken: opts.pageToken });
|
|
17195
17195
|
} catch (err) {
|
|
17196
17196
|
throw new ApiError(400, err instanceof Error ? err.message : String(err));
|
|
17197
17197
|
}
|
|
@@ -17613,9 +17613,9 @@ async function route(req, res, deps, url) {
|
|
|
17613
17613
|
if (path === "/api/user-chats" && g) {
|
|
17614
17614
|
const profile2 = url.searchParams.get("profile") ?? await readActiveProfile(deps.rootDir);
|
|
17615
17615
|
if (!profile2) throw new HttpError(400, "no profile");
|
|
17616
|
-
const
|
|
17616
|
+
const query2 = url.searchParams.get("query") ?? void 0;
|
|
17617
17617
|
const pageToken = url.searchParams.get("pageToken") ?? void 0;
|
|
17618
|
-
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 }));
|
|
17619
17619
|
return;
|
|
17620
17620
|
}
|
|
17621
17621
|
if (path === "/api/chats/add-bot" && p3) {
|
|
@@ -18679,6 +18679,467 @@ function openBrowser(url) {
|
|
|
18679
18679
|
}
|
|
18680
18680
|
}
|
|
18681
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
|
+
|
|
18682
19143
|
// src/bridge/cli/index.ts
|
|
18683
19144
|
var program = new Command();
|
|
18684
19145
|
program.name("aai-lark-bridge").description("Bridge Feishu/Lark messenger with local CLI coding agents").version(package_default.version, "-v, --version");
|
|
@@ -18688,6 +19149,9 @@ program.command("run").description("Run the bridge in the foreground (was `start
|
|
|
18688
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) => {
|
|
18689
19150
|
await runMigrate(opts);
|
|
18690
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
|
+
});
|
|
18691
19155
|
var profile = program.command("profile").description("Manage local bridge profiles");
|
|
18692
19156
|
profile.command("list").description("List configured profiles").action(async () => {
|
|
18693
19157
|
await runProfileList();
|