dsh-message-gateway 0.1.20 → 0.1.22

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/lib/index.js CHANGED
@@ -15,8 +15,8 @@ __export(gateway_store_exports, {
15
15
  saveStore: () => saveStore
16
16
  });
17
17
  import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
18
- import { homedir } from "node:os";
19
- import { join } from "node:path";
18
+ import { homedir as homedir2 } from "node:os";
19
+ import { join as join2 } from "node:path";
20
20
  async function loadStore() {
21
21
  try {
22
22
  const text = await readFile(FILE, "utf8");
@@ -30,7 +30,7 @@ async function loadStore() {
30
30
  }
31
31
  }
32
32
  async function saveStore(data) {
33
- await mkdir(join(homedir(), ".dsh"), { recursive: true });
33
+ await mkdir(join2(homedir2(), ".dsh"), { recursive: true });
34
34
  const tmp = `${FILE}.tmp`;
35
35
  await writeFile(tmp, JSON.stringify(data, null, 2), { mode: 384 });
36
36
  await chmod(tmp, 384);
@@ -40,7 +40,7 @@ var FILE;
40
40
  var init_gateway_store = __esm({
41
41
  "src/host/gateway-store.ts"() {
42
42
  "use strict";
43
- FILE = join(homedir(), ".dsh", "gateway.json");
43
+ FILE = join2(homedir2(), ".dsh", "gateway.json");
44
44
  }
45
45
  });
46
46
 
@@ -3203,59 +3203,103 @@ function sanitizeSecrets(text) {
3203
3203
  import { WSClient } from "@wecom/aibot-node-sdk";
3204
3204
 
3205
3205
  // src/host/wecom-smartsheet.ts
3206
+ import { createRequire } from "node:module";
3207
+ import { execFile } from "node:child_process";
3208
+ import { createHash } from "node:crypto";
3209
+ import { existsSync, mkdirSync } from "node:fs";
3210
+ import { homedir } from "node:os";
3211
+ import { join, dirname } from "node:path";
3212
+ function configDirFor(botId, secret) {
3213
+ const fp = createHash("sha256").update(`${botId}:${secret}`, "utf8").digest("hex").slice(0, 8);
3214
+ return join(homedir(), ".local", "share", "dsh-message-gateway", "wecom-cli", `${botId.replace(/[^A-Za-z0-9_-]/g, "_")}-${fp}`);
3215
+ }
3216
+ function resolveCliBinary() {
3217
+ const require2 = createRequire(import.meta.url);
3218
+ const platformMap = {
3219
+ "darwin-arm64": "@wecom/cli-darwin-arm64",
3220
+ "darwin-x64": "@wecom/cli-darwin-x64",
3221
+ "linux-arm64": "@wecom/cli-linux-arm64",
3222
+ "linux-x64": "@wecom/cli-linux-x64",
3223
+ "win32-x64": "@wecom/cli-win32-x64"
3224
+ };
3225
+ const key = `${process.platform}-${process.arch}`;
3226
+ const pkg = platformMap[key];
3227
+ if (!pkg) throw new Error(`wecom-cli: unsupported platform ${key}`);
3228
+ const binaryName = process.platform === "win32" ? "wecom-cli.exe" : "wecom-cli";
3229
+ try {
3230
+ const pkgDir = require2.resolve(`${pkg}/package.json`);
3231
+ return join(dirname(pkgDir), "bin", binaryName);
3232
+ } catch {
3233
+ throw new Error("wecom-cli: cannot locate platform binary, reinstall @wecom/cli (do not use --no-optional)");
3234
+ }
3235
+ }
3236
+ function runCli(bin, argv, configDir, timeoutMs = 9e4) {
3237
+ return new Promise((resolve, reject) => {
3238
+ const env = {
3239
+ ...process.env,
3240
+ WECOM_CLI_CONFIG_DIR: configDir,
3241
+ WECOM_CLI_LOG_LEVEL: "warn"
3242
+ };
3243
+ const child = execFile(bin, argv, { env, timeout: timeoutMs, windowsHide: true }, (error, stdout, stderr) => {
3244
+ if (error && error.code === "ETIMEDOUT") {
3245
+ reject(new Error(`wecom-cli \u6267\u884C\u8D85\u65F6\uFF1A${argv.join(" ")}`));
3246
+ return;
3247
+ }
3248
+ const code = error === null ? 0 : typeof error.code === "number" ? error.code : 1;
3249
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
3250
+ });
3251
+ child.stdin?.end();
3252
+ });
3253
+ }
3254
+ function isAuthorized(dir) {
3255
+ return existsSync(join(dir, "credentials.enc")) && existsSync(join(dir, ".encryption_key"));
3256
+ }
3206
3257
  var WecomSmartsheetClient = class {
3207
3258
  constructor(creds) {
3208
3259
  this.creds = creds;
3209
- }
3210
- token = null;
3211
- tokenExpiresAt = 0;
3212
- /**
3213
- * 获取有效的 access_token(自动内存缓存与续期)。
3214
- */
3215
- async getAccessToken() {
3216
- const now = Date.now();
3217
- if (this.token && now < this.tokenExpiresAt - 6e4) {
3218
- return this.token;
3219
- }
3220
- const corpId = this.creds.corpId || this.creds.botId || "";
3221
- const secret = this.creds.secret || "";
3222
- if (!corpId || !secret) {
3223
- throw new Error("\u4F01\u4E1A\u5FAE\u4FE1\u51ED\u636E\u4E0D\u5B8C\u6574\uFF08\u7F3A\u5C11 botId/corpId \u6216 secret\uFF09");
3224
- }
3225
- const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${encodeURIComponent(corpId)}&corpsecret=${encodeURIComponent(secret)}`;
3226
- const res = await fetch(url, { signal: AbortSignal.timeout(1e4) });
3227
- const data = await res.json();
3228
- if (data.errcode !== 0 || !data.access_token) {
3229
- throw new Error(`\u83B7\u53D6\u4F01\u4E1A\u5FAE\u4FE1 access_token \u5931\u8D25 [${data.errcode}]: ${data.errmsg || "\u672A\u77E5\u9519\u8BEF"}`);
3260
+ this.bin = resolveCliBinary();
3261
+ const botId = creds.botId ?? "";
3262
+ const secret = creds.secret ?? "";
3263
+ if (!botId || !secret) throw new Error("\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u51ED\u636E\u4E0D\u5B8C\u6574\uFF08\u7F3A\u5C11 botId \u6216 secret\uFF09");
3264
+ this.dir = configDirFor(botId, secret);
3265
+ }
3266
+ bin;
3267
+ dir;
3268
+ authDone = false;
3269
+ /** 确保已授权(幂等短路,避免重复鉴权触发频率限制)。 */
3270
+ async ensureAuthorized() {
3271
+ if (this.authDone && isAuthorized(this.dir)) return;
3272
+ mkdirSync(this.dir, { recursive: true });
3273
+ if (!isAuthorized(this.dir)) {
3274
+ const res = await runCli(this.bin, ["auth", "init", "--bot-id", this.creds.botId ?? "", "--secret", this.creds.secret ?? ""], this.dir, 6e4);
3275
+ if (res.code !== 0) {
3276
+ throw new Error(`\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u6388\u6743\u5931\u8D25\uFF1A${res.stderr.trim() || res.stdout.trim() || `exit ${res.code}`}`);
3277
+ }
3230
3278
  }
3231
- this.token = data.access_token;
3232
- this.tokenExpiresAt = now + (data.expires_in ?? 7200) * 1e3;
3233
- return this.token;
3279
+ this.authDone = true;
3234
3280
  }
3235
- /**
3236
- * 映射字段类型为企微官方标准枚举。
3237
- */
3281
+ /** 映射字段类型为企微官方字段类型标识。 */
3238
3282
  mapFieldType(type) {
3239
3283
  switch (type?.toLowerCase()) {
3240
3284
  case "number":
3241
- return "FIELD_TYPE_NUMBER";
3285
+ return "number";
3242
3286
  case "single_select":
3243
3287
  case "select":
3244
- return "FIELD_TYPE_SINGLE_SELECT";
3288
+ return "single_select";
3245
3289
  case "multi_select":
3246
- return "FIELD_TYPE_MULTI_SELECT";
3290
+ return "select";
3247
3291
  case "date":
3248
3292
  case "date_time":
3249
3293
  case "datetime":
3250
- return "FIELD_TYPE_DATE_TIME";
3294
+ return "date_time";
3251
3295
  case "user":
3252
3296
  case "member":
3253
- return "FIELD_TYPE_USER";
3297
+ return "user";
3254
3298
  case "checkbox":
3255
- return "FIELD_TYPE_CHECKBOX";
3299
+ return "checkbox";
3256
3300
  case "text":
3257
3301
  default:
3258
- return "FIELD_TYPE_TEXT";
3302
+ return "text";
3259
3303
  }
3260
3304
  }
3261
3305
  /**
@@ -3263,92 +3307,65 @@ var WecomSmartsheetClient = class {
3263
3307
  */
3264
3308
  async createSmartsheet(options) {
3265
3309
  try {
3266
- const token = await this.getAccessToken();
3267
- const url = `https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/create?access_token=${encodeURIComponent(token)}`;
3268
- const fields = options.fields && options.fields.length > 0 ? options.fields.map((f) => {
3310
+ await this.ensureAuthorized();
3311
+ const fields = (options.fields && options.fields.length > 0 ? options.fields : [
3312
+ { title: "\u6807\u9898", type: "text" },
3313
+ { title: "\u72B6\u6001", type: "single_select", options: ["\u672A\u5F00\u59CB", "\u8FDB\u884C\u4E2D", "\u5DF2\u5B8C\u6210"] },
3314
+ { title: "\u8D1F\u8D23\u4EBA", type: "user" },
3315
+ { title: "\u622A\u6B62\u65E5\u671F", type: "date_time" }
3316
+ ]).map((f, idx) => {
3269
3317
  const fieldType = this.mapFieldType(f.type);
3270
3318
  const item = {
3271
3319
  field_title: f.title,
3272
3320
  field_type: fieldType
3273
3321
  };
3274
- if ((fieldType === "FIELD_TYPE_SINGLE_SELECT" || fieldType === "FIELD_TYPE_MULTI_SELECT") && f.options) {
3275
- item.property = {
3276
- options: f.options.map((opt) => ({ text: String(opt) }))
3322
+ if ((fieldType === "single_select" || fieldType === "select") && f.options) {
3323
+ item[fieldType === "select" ? "property_select" : "property_single_select"] = {
3324
+ options: f.options.map((text, oi) => ({ id: String(oi + 1), text: String(text) }))
3277
3325
  };
3278
3326
  }
3327
+ void idx;
3279
3328
  return item;
3280
- }) : [
3281
- { field_title: "\u6807\u9898", field_type: "FIELD_TYPE_TEXT" },
3282
- { field_title: "\u72B6\u6001", field_type: "FIELD_TYPE_SINGLE_SELECT", property: { options: [{ text: "\u672A\u5F00\u59CB" }, { text: "\u8FDB\u884C\u4E2D" }, { text: "\u5DF2\u5B8C\u6210" }] } },
3283
- { field_title: "\u8D1F\u8D23\u4EBA", field_type: "FIELD_TYPE_USER" },
3284
- { field_title: "\u622A\u6B62\u65E5\u671F", field_type: "FIELD_TYPE_DATE_TIME" }
3285
- ];
3286
- const payload = {
3287
- doc_name: options.title || "\u65B0\u5EFA\u667A\u80FD\u8868\u683C",
3288
- sheet_title: options.sheetTitle || "\u6570\u636E\u8868",
3289
- fields
3290
- };
3291
- if (options.adminUsers && options.adminUsers.length > 0) {
3292
- payload.admin_users = options.adminUsers;
3293
- }
3294
- const res = await fetch(url, {
3295
- method: "POST",
3296
- headers: { "content-type": "application/json" },
3297
- body: JSON.stringify(payload),
3298
- signal: AbortSignal.timeout(15e3)
3299
3329
  });
3300
- const data = await res.json();
3301
- if (data.errcode !== 0 || !data.docid) {
3302
- return {
3303
- ok: false,
3304
- error: `\u521B\u5EFA\u667A\u80FD\u8868\u683C\u5931\u8D25 [${data.errcode}]: ${data.errmsg || "\u672A\u77E5\u9519\u8BEF"}`
3305
- };
3306
- }
3307
- if (options.records && options.records.length > 0) {
3308
- await this.addRecords(data.docid, options.records).catch((err) => {
3309
- console.warn("[WecomSmartsheetClient] \u5199\u5165\u521D\u59CB\u6570\u636E\u5931\u8D25\uFF08\u8868\u683C\u5DF2\u521B\u5EFA\u6210\u529F\uFF09:", err);
3330
+ const rows = (options.records ?? []).map((rec) => {
3331
+ const values = fields.map((f) => {
3332
+ const title = String(f.field_title);
3333
+ const raw = rec[title];
3334
+ const fieldType = String(f.field_type);
3335
+ if (fieldType === "number") {
3336
+ const n = Number(raw ?? 0);
3337
+ return { data_type: "NUMBER", cell_value: { number: Number.isFinite(n) ? n : 0 } };
3338
+ }
3339
+ if (fieldType === "single_select" || fieldType === "select") {
3340
+ const text = String(raw ?? "");
3341
+ const f2 = f;
3342
+ const property = f2.property_single_select ?? f2.property_select ?? {};
3343
+ const options2 = property.options ?? [];
3344
+ const hit = options2.find((o) => o.text === text);
3345
+ return {
3346
+ data_type: "SELECT",
3347
+ cell_value: { select: { value: hit ? [hit.id] : [], options: options2 } }
3348
+ };
3349
+ }
3350
+ return { data_type: "TEXT", cell_value: { text: String(raw ?? "") } };
3310
3351
  });
3311
- }
3312
- return {
3313
- ok: true,
3314
- docid: data.docid,
3315
- url: data.url || `https://doc.weixin.qq.com/smartsheet/${data.docid}`
3316
- };
3317
- } catch (error) {
3318
- return {
3319
- ok: false,
3320
- error: error instanceof Error ? error.message : String(error)
3321
- };
3322
- }
3323
- }
3324
- /**
3325
- * 向指定的智能表格中追加行记录。
3326
- */
3327
- async addRecords(docid, records, sheetId) {
3328
- try {
3329
- const token = await this.getAccessToken();
3330
- const url = `https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/add_records?access_token=${encodeURIComponent(token)}`;
3331
- const recordItems = records.map((rec) => ({
3332
- values: rec
3333
- }));
3334
- const payload = {
3335
- docid,
3336
- records: recordItems
3337
- };
3338
- if (sheetId) {
3339
- payload.sheet_id = sheetId;
3340
- }
3341
- const res = await fetch(url, {
3342
- method: "POST",
3343
- headers: { "content-type": "application/json" },
3344
- body: JSON.stringify(payload),
3345
- signal: AbortSignal.timeout(15e3)
3352
+ return { values };
3353
+ });
3354
+ const body = JSON.stringify({
3355
+ name: options.title || "\u65B0\u5EFA\u667A\u80FD\u8868\u683C",
3356
+ sheet_title: options.sheetTitle || "\u6570\u636E\u8868",
3357
+ fields,
3358
+ ...rows.length > 0 ? { grid_data: { start_row: 0, start_column: 0, rows } } : {}
3346
3359
  });
3347
- const data = await res.json();
3348
- if (data.errcode !== 0) {
3349
- return { ok: false, error: `\u6DFB\u52A0\u8BB0\u5F55\u5931\u8D25 [${data.errcode}]: ${data.errmsg || "\u672A\u77E5\u9519\u8BEF"}` };
3360
+ const res = await runCli(this.bin, ["smartsheet", "create", "--json", body], this.dir, 9e4);
3361
+ if (res.code !== 0) {
3362
+ return { ok: false, error: `\u521B\u5EFA\u667A\u80FD\u8868\u683C\u5931\u8D25\uFF1A${res.stderr.trim() || res.stdout.trim() || `exit ${res.code}`}` };
3363
+ }
3364
+ const parsed = JSON.parse(res.stdout);
3365
+ if (parsed.errcode !== 0 || !parsed.docid) {
3366
+ return { ok: false, error: `\u521B\u5EFA\u667A\u80FD\u8868\u683C\u5931\u8D25 [${parsed.errcode}]: ${parsed.errmsg || "\u672A\u77E5\u9519\u8BEF"}` };
3350
3367
  }
3351
- return { ok: true };
3368
+ return { ok: true, docid: parsed.docid, url: parsed.url || `https://doc.weixin.qq.com/smartsheet/${parsed.docid}` };
3352
3369
  } catch (error) {
3353
3370
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
3354
3371
  }
@@ -6137,7 +6154,7 @@ ${cred.secret}`;
6137
6154
  }
6138
6155
 
6139
6156
  // src/host/callback-bridges.ts
6140
- import { createHash, createDecipheriv, createCipheriv, randomBytes } from "node:crypto";
6157
+ import { createHash as createHash2, createDecipheriv, createCipheriv, randomBytes } from "node:crypto";
6141
6158
  var TOKEN_TTL_MS = 7e6;
6142
6159
  var tokenCache = /* @__PURE__ */ new Map();
6143
6160
  function cachedToken(key) {
@@ -6150,7 +6167,7 @@ function setCachedToken(key, token) {
6150
6167
  }
6151
6168
  function sha1Sorted(parts) {
6152
6169
  const sorted = [...parts].sort();
6153
- return createHash("sha1").update(sorted.join("")).digest("hex");
6170
+ return createHash2("sha1").update(sorted.join("")).digest("hex");
6154
6171
  }
6155
6172
  function xmlField(xml, name) {
6156
6173
  const match = xml.match(new RegExp(`<${name}>(?:<!\\[CDATA\\[)?([\\s\\S]*?)(?:\\]\\]>)?<\\/${name}>`));
@@ -7019,10 +7036,26 @@ function apply(ctx, config = Config({})) {
7019
7036
  },
7020
7037
  fields: {
7021
7038
  type: "array",
7039
+ items: {
7040
+ type: "object",
7041
+ properties: {
7042
+ title: { type: "string", required: true },
7043
+ type: {
7044
+ type: "string",
7045
+ enum: ["text", "number", "single_select", "multi_select", "date_time", "user", "checkbox"]
7046
+ },
7047
+ options: { type: "array", items: { type: "string" } }
7048
+ },
7049
+ additionalProperties: false
7050
+ },
7022
7051
  description: '\u5217\u5B57\u6BB5\u5B9A\u4E49\u5217\u8868\uFF0C\u5982 [{"title": "\u4EFB\u52A1\u540D\u79F0", "type": "text"}, {"title": "\u72B6\u6001", "type": "single_select", "options": ["\u5F85\u529E", "\u8FDB\u884C\u4E2D", "\u5DF2\u5B8C\u6210"]}]'
7023
7052
  },
7024
7053
  records: {
7025
7054
  type: "array",
7055
+ items: {
7056
+ type: "object",
7057
+ additionalProperties: true
7058
+ },
7026
7059
  description: '\u521D\u59CB\u586B\u5165\u7684\u6570\u636E\u884C\u5217\u8868\uFF0C\u5982 [{"\u4EFB\u52A1\u540D\u79F0": "\u9700\u6C42\u8BC4\u5BA1", "\u72B6\u6001": "\u5DF2\u5B8C\u6210"}]'
7027
7060
  }
7028
7061
  },
@@ -7085,6 +7118,7 @@ export {
7085
7118
  WechatMpBridge,
7086
7119
  WecomAppBridge,
7087
7120
  WecomBridge,
7121
+ WecomSmartsheetClient,
7088
7122
  WhatsappBridge,
7089
7123
  apply,
7090
7124
  cleanBody,