@harrylabsj/kiwi 0.12.6 → 0.12.7

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.
Files changed (65) hide show
  1. package/contracts/kiwi-catalog/1.0/agent-record.schema.json +21 -0
  2. package/contracts/kiwi-contracts.lock.json +2 -2
  3. package/contracts/manifest.json +2 -2
  4. package/dist/a2a/access/workbuddy-address.d.ts +45 -0
  5. package/dist/a2a/access/workbuddy-address.js +88 -0
  6. package/dist/a2a/access/workbuddy-address.js.map +1 -0
  7. package/dist/a2a/client/client.d.ts +6 -0
  8. package/dist/a2a/client/client.js +27 -2
  9. package/dist/a2a/client/client.js.map +1 -1
  10. package/dist/a2a/client/types.d.ts +5 -0
  11. package/dist/a2a/server/server.d.ts +5 -0
  12. package/dist/a2a/server/server.js +10 -2
  13. package/dist/a2a/server/server.js.map +1 -1
  14. package/dist/buyer-core/a2a-knp.d.ts +18 -1
  15. package/dist/buyer-core/a2a-knp.js +29 -5
  16. package/dist/buyer-core/a2a-knp.js.map +1 -1
  17. package/dist/buyer-core/a2a-negotiator.d.ts +4 -0
  18. package/dist/buyer-core/a2a-negotiator.js +3 -0
  19. package/dist/buyer-core/a2a-negotiator.js.map +1 -1
  20. package/dist/buyer-core/a2a-quote-fetcher.d.ts +47 -0
  21. package/dist/buyer-core/a2a-quote-fetcher.js +109 -11
  22. package/dist/buyer-core/a2a-quote-fetcher.js.map +1 -1
  23. package/dist/buyer-core/build-service.d.ts +7 -0
  24. package/dist/buyer-core/build-service.js +67 -0
  25. package/dist/buyer-core/build-service.js.map +1 -1
  26. package/dist/buyer-core/merchant-index.js +3 -0
  27. package/dist/buyer-core/merchant-index.js.map +1 -1
  28. package/dist/buyer-core/protocol-recovery.js +7 -0
  29. package/dist/buyer-core/protocol-recovery.js.map +1 -1
  30. package/dist/buyer-core/service.d.ts +14 -0
  31. package/dist/buyer-core/service.js.map +1 -1
  32. package/dist/cloud/access/workbuddy-share-link.d.ts +92 -0
  33. package/dist/cloud/access/workbuddy-share-link.js +150 -0
  34. package/dist/cloud/access/workbuddy-share-link.js.map +1 -0
  35. package/dist/cloud/bootstrap.js +33 -0
  36. package/dist/cloud/bootstrap.js.map +1 -1
  37. package/dist/cloud/catalog-client.d.ts +66 -0
  38. package/dist/cloud/catalog-client.js +155 -0
  39. package/dist/cloud/catalog-client.js.map +1 -1
  40. package/dist/cloud/config.d.ts +6 -0
  41. package/dist/cloud/config.js +4 -0
  42. package/dist/cloud/config.js.map +1 -1
  43. package/dist/cloud/connect-service.d.ts +68 -0
  44. package/dist/cloud/connect-service.js +198 -0
  45. package/dist/cloud/connect-service.js.map +1 -1
  46. package/dist/cloud/http-router.d.ts +5 -0
  47. package/dist/cloud/http-router.js +7 -0
  48. package/dist/cloud/http-router.js.map +1 -1
  49. package/dist/discovery/catalog-source/kiwi-record.d.ts +10 -0
  50. package/dist/discovery/catalog-source/kiwi-record.js.map +1 -1
  51. package/dist/discovery/catalog-source/merchant-access.d.ts +77 -0
  52. package/dist/discovery/catalog-source/merchant-access.js +279 -0
  53. package/dist/discovery/catalog-source/merchant-access.js.map +1 -0
  54. package/dist/http/merchant-management/api.d.ts +21 -0
  55. package/dist/http/merchant-management/api.js +79 -0
  56. package/dist/http/merchant-management/api.js.map +1 -1
  57. package/dist/http/merchant-management/page.js +81 -1
  58. package/dist/http/merchant-management/page.js.map +1 -1
  59. package/dist/tools/trusted-buyer-keys.d.ts +31 -0
  60. package/dist/tools/trusted-buyer-keys.js +98 -0
  61. package/dist/tools/trusted-buyer-keys.js.map +1 -0
  62. package/dist/tools/workbuddy-echo.d.ts +69 -0
  63. package/dist/tools/workbuddy-echo.js +132 -0
  64. package/dist/tools/workbuddy-echo.js.map +1 -0
  65. package/package.json +15 -10
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Copyright 2026 harrylabsj
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /**
17
+ * MerchantAccessSource —— 经 Catalog 受控获取 WorkBuddy 分享配置(B-01/B-02)。
18
+ *
19
+ * GET {baseUrl}/v1/me/merchant-access/{catalog_agent_id} (cookie kiwi_session)
20
+ * → { catalog_agent_id, runtime_origin, provider, access_mode, parameter_name,
21
+ * secret_value, config_version, adapter_version, auth_mode,
22
+ * validated_at, updated_at }
23
+ *
24
+ * 契约来源:kiwi-catalog `api/handlers/buyer_follows.py::get_merchant_access`
25
+ * 与 G1 契约 §2.4/§2.5。要点:
26
+ *
27
+ * - **必须经 Catalog**:所有 Kiwi Buyer 通过目录发现商家,并由目录发放分享码;
28
+ * 不走其它途径(产品决定)。
29
+ * - **会话认证**:与 BuyerFollowsSource 同一形态(cookie kiwi_session),
30
+ * 服务端从会话解析主体并要求对商家有 **active follow**;匿名不发放。
31
+ * - **no-store**:目录对响应禁止缓存;本模块自带短 TTL 内存缓存(默认 60s),
32
+ * 键含 `catalog_agent_id + runtime_origin + adapter_version`,单飞刷新,
33
+ * 换码/撤销/版本变化都会让旧条目失效。
34
+ * - **严格校验**:未知 provider/adapter/auth_mode、缺失秘密、origin 与发现记录
35
+ * 不一致,一律 `contract_violation`——绝不"尽力使用"。
36
+ * - **秘密不外泄**:分享码只在返回值里;本模块不写日志,错误信息不含它。
37
+ */
38
+ import { isRedirectResponse, readJsonBody, SafeHttpError } from "../../net/safe-http.js";
39
+ import { PRODUCT_VERSION } from "../../product-cli.js";
40
+ import { CatalogSourceError } from "./errors.js";
41
+ import { validateBaseUrl } from "./source.js";
42
+ const DEFAULT_TIMEOUT_MS = 15_000;
43
+ /** 配置缓存默认 TTL(G1 §2.5.5)。 */
44
+ const DEFAULT_CACHE_TTL_MS = 60_000;
45
+ export const WORKBUDDY_ADAPTER = "workbuddy-share-v1";
46
+ function requireObject(value, what) {
47
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
48
+ throw new CatalogSourceError("contract_violation", `${what} must be a JSON object`);
49
+ }
50
+ return value;
51
+ }
52
+ function requireString(record, field, what) {
53
+ const value = record[field];
54
+ if (typeof value !== "string" || value === "") {
55
+ throw new CatalogSourceError("contract_violation", `${what} missing non-empty string field "${field}"`);
56
+ }
57
+ return value;
58
+ }
59
+ /**
60
+ * 校验目录下发的访问配置。`expectedOrigin` 来自发现记录:目录不得把配置
61
+ * 指向另一个 origin(那是把分享码投递给错误部署的路径)。
62
+ */
63
+ export function validateMerchantAccess(value, expected) {
64
+ const what = "MerchantAccess";
65
+ const record = requireObject(value, what);
66
+ const catalogAgentId = requireString(record, "catalog_agent_id", what);
67
+ if (catalogAgentId !== expected.catalogAgentId) {
68
+ throw new CatalogSourceError("contract_violation", `${what} belongs to another agent`);
69
+ }
70
+ const runtimeOrigin = requireString(record, "runtime_origin", what);
71
+ if (!/^https:\/\/[^/?#]+$/.test(runtimeOrigin)) {
72
+ throw new CatalogSourceError("contract_violation", `${what}.runtime_origin must be an https origin`);
73
+ }
74
+ if (expected.runtimeOrigin !== undefined && runtimeOrigin !== expected.runtimeOrigin) {
75
+ throw new CatalogSourceError("contract_violation", `${what}.runtime_origin does not match the discovered merchant`);
76
+ }
77
+ if (record["provider"] !== "workbuddy") {
78
+ throw new CatalogSourceError("contract_violation", `${what}.provider is not supported`);
79
+ }
80
+ if (record["access_mode"] !== "share_parameter") {
81
+ throw new CatalogSourceError("contract_violation", `${what}.access_mode is not supported`);
82
+ }
83
+ if (record["parameter_name"] !== "sharecode") {
84
+ throw new CatalogSourceError("contract_violation", `${what}.parameter_name is not supported`);
85
+ }
86
+ if (record["adapter_version"] !== WORKBUDDY_ADAPTER) {
87
+ throw new CatalogSourceError("contract_violation", `${what}.adapter_version is not supported`);
88
+ }
89
+ if (record["auth_mode"] !== "signature") {
90
+ throw new CatalogSourceError("contract_violation", `${what}.auth_mode is not supported`);
91
+ }
92
+ const configVersion = record["config_version"];
93
+ if (typeof configVersion !== "number" || !Number.isInteger(configVersion) || configVersion < 1) {
94
+ throw new CatalogSourceError("contract_violation", `${what}.config_version is invalid`);
95
+ }
96
+ const secret = requireString(record, "secret_value", what);
97
+ return {
98
+ catalog_agent_id: catalogAgentId,
99
+ runtime_origin: runtimeOrigin,
100
+ provider: "workbuddy",
101
+ access_mode: "share_parameter",
102
+ parameter_name: "sharecode",
103
+ secret_value: secret,
104
+ config_version: configVersion,
105
+ adapter_version: WORKBUDDY_ADAPTER,
106
+ auth_mode: "signature",
107
+ validated_at: typeof record["validated_at"] === "string" ? record["validated_at"] : "",
108
+ updated_at: typeof record["updated_at"] === "string" ? record["updated_at"] : "",
109
+ };
110
+ }
111
+ export class MerchantAccessSource {
112
+ baseUrl;
113
+ deps;
114
+ cache = new Map();
115
+ inflight = new Map();
116
+ constructor(deps) {
117
+ this.baseUrl = validateBaseUrl(deps.baseUrl);
118
+ this.deps = deps;
119
+ }
120
+ cacheKey(catalogAgentId, runtimeOrigin) {
121
+ return `${catalogAgentId}|${runtimeOrigin ?? ""}|${WORKBUDDY_ADAPTER}`;
122
+ }
123
+ nowMs() {
124
+ return (this.deps.now?.() ?? new Date()).getTime();
125
+ }
126
+ ttlMs() {
127
+ return this.deps.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
128
+ }
129
+ /** 丢弃某个商家(或全部)的缓存;换码/撤销后由调用方显式触发。 */
130
+ invalidate(catalogAgentId) {
131
+ if (catalogAgentId === undefined) {
132
+ this.cache.clear();
133
+ return;
134
+ }
135
+ for (const key of [...this.cache.keys()]) {
136
+ if (key.startsWith(`${catalogAgentId}|`))
137
+ this.cache.delete(key);
138
+ }
139
+ }
140
+ /**
141
+ * 取配置(带缓存与单飞)。返回 `null` 表示目录没有该商家的 active 配置
142
+ * (404:未关注/不存在/已撤销都按同一防枚举口径处理),调用方据此 fail-closed。
143
+ */
144
+ async get(catalogAgentId, options = {}) {
145
+ if (typeof catalogAgentId !== "string" || catalogAgentId === "") {
146
+ throw new CatalogSourceError("invalid_input", "catalogAgentId must be a non-empty string");
147
+ }
148
+ const key = this.cacheKey(catalogAgentId, options.runtimeOrigin);
149
+ const cached = this.cache.get(key);
150
+ if (cached !== undefined) {
151
+ if (cached.expiresAt > this.nowMs())
152
+ return cached.config;
153
+ this.cache.delete(key);
154
+ }
155
+ const existing = this.inflight.get(key);
156
+ if (existing !== undefined)
157
+ return await existing;
158
+ const task = (async () => {
159
+ const config = await this.fetchAccess(catalogAgentId, options.runtimeOrigin);
160
+ if (config !== null && this.ttlMs() > 0) {
161
+ this.cache.set(key, { config, expiresAt: this.nowMs() + this.ttlMs() });
162
+ }
163
+ return config;
164
+ })();
165
+ this.inflight.set(key, task);
166
+ try {
167
+ return await task;
168
+ }
169
+ finally {
170
+ this.inflight.delete(key);
171
+ }
172
+ }
173
+ /** 强制回源(忽略缓存)。 */
174
+ async refresh(catalogAgentId, options = {}) {
175
+ this.invalidate(catalogAgentId);
176
+ return await this.get(catalogAgentId, options);
177
+ }
178
+ /**
179
+ * 上报一次门禁失败(C-06,尽力而为):目录只记账,不改配置状态;商家在工作台
180
+ * 看到计数后自行决定是否换码。任何失败都吞掉——上报不能影响采购方的主流程。
181
+ */
182
+ async reportFault(catalogAgentId, code) {
183
+ const sessionToken = this.deps.sessionToken;
184
+ if (sessionToken === undefined || sessionToken === "")
185
+ return;
186
+ if (typeof catalogAgentId !== "string" || catalogAgentId === "")
187
+ return;
188
+ const fetchImpl = this.deps.fetchImpl ?? globalThis.fetch;
189
+ const timeoutMs = this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
190
+ const url = `${this.baseUrl}/v1/me/merchant-access/${encodeURIComponent(catalogAgentId)}/fault`;
191
+ try {
192
+ await fetchImpl(url, {
193
+ method: "POST",
194
+ redirect: "manual",
195
+ signal: AbortSignal.timeout(timeoutMs),
196
+ headers: {
197
+ accept: "application/json",
198
+ "content-type": "application/json",
199
+ "user-agent": `kiwi-buyer/${PRODUCT_VERSION}`,
200
+ cookie: `kiwi_session=${sessionToken}`,
201
+ ...(this.deps.buyerId !== undefined ? { "x-buyer-id": this.deps.buyerId } : {}),
202
+ },
203
+ body: JSON.stringify({ code }),
204
+ });
205
+ }
206
+ catch {
207
+ // 上报是旁路:超时/不可达都不影响采购流程。
208
+ }
209
+ }
210
+ async fetchAccess(catalogAgentId, runtimeOrigin) {
211
+ const sessionToken = this.deps.sessionToken;
212
+ if (sessionToken === undefined || sessionToken === "") {
213
+ throw new CatalogSourceError("session_rejected", "kiwi-catalog buyer session token is not configured");
214
+ }
215
+ const fetchImpl = this.deps.fetchImpl ?? globalThis.fetch;
216
+ const timeoutMs = this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
217
+ const url = `${this.baseUrl}/v1/me/merchant-access/${encodeURIComponent(catalogAgentId)}`;
218
+ const controller = new AbortController();
219
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
220
+ try {
221
+ let response;
222
+ let raw;
223
+ try {
224
+ response = await fetchImpl(url, {
225
+ method: "GET",
226
+ // 不跟随重定向:3xx 目标不经过校验,且可能转发会话 cookie。
227
+ redirect: "manual",
228
+ signal: controller.signal,
229
+ headers: {
230
+ accept: "application/json",
231
+ "user-agent": `kiwi-buyer/${PRODUCT_VERSION}`,
232
+ cookie: `kiwi_session=${sessionToken}`,
233
+ ...(this.deps.buyerId !== undefined ? { "x-buyer-id": this.deps.buyerId } : {}),
234
+ },
235
+ });
236
+ }
237
+ catch (err) {
238
+ const name = err?.name;
239
+ throw new CatalogSourceError(name === "AbortError" ? "request_timeout" : "request_failed", name === "AbortError"
240
+ ? `kiwi-catalog merchant access timed out after ${timeoutMs}ms`
241
+ : `kiwi-catalog merchant access failed (${err instanceof Error ? err.message : String(err)})`);
242
+ }
243
+ if (isRedirectResponse(response)) {
244
+ throw new CatalogSourceError("request_failed", `kiwi-catalog merchant access must not follow redirects (HTTP ${response.status})`);
245
+ }
246
+ if (response.status === 404) {
247
+ return null;
248
+ }
249
+ if (response.status === 401 || response.status === 403) {
250
+ throw new CatalogSourceError("session_rejected", `kiwi-catalog merchant access rejected (HTTP ${response.status}); sign in and follow the merchant first`);
251
+ }
252
+ if (response.status === 429) {
253
+ throw new CatalogSourceError("request_failed", "kiwi-catalog merchant access rate limited (HTTP 429)");
254
+ }
255
+ if (!response.ok) {
256
+ throw new CatalogSourceError("request_failed", `kiwi-catalog merchant access returned HTTP ${response.status}`);
257
+ }
258
+ try {
259
+ raw = await readJsonBody(response, { signal: controller.signal });
260
+ }
261
+ catch (err) {
262
+ if (controller.signal.aborted) {
263
+ throw new CatalogSourceError("request_timeout", `kiwi-catalog merchant access timed out after ${timeoutMs}ms while reading response`);
264
+ }
265
+ throw new CatalogSourceError("response_invalid", err instanceof SafeHttpError && err.code === "response_too_large"
266
+ ? `kiwi-catalog merchant access response: ${err.message}`
267
+ : "kiwi-catalog merchant access response is not valid JSON");
268
+ }
269
+ return validateMerchantAccess(raw, {
270
+ catalogAgentId,
271
+ ...(runtimeOrigin !== undefined ? { runtimeOrigin } : {}),
272
+ });
273
+ }
274
+ finally {
275
+ clearTimeout(timer);
276
+ }
277
+ }
278
+ }
279
+ //# sourceMappingURL=merchant-access.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"merchant-access.js","sourceRoot":"","sources":["../../../src/discovery/catalog-source/merchant-access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,eAAe,EAAE,MA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oBAC/D,CAAC,CAAC,0CAA0C,GAAG,CAAC,OAAO,EAAE;oBACzD,CAAC,CAAC,yDAAyD,CAC9D,CAAC;YACJ,CAAC;YACD,OAAO,sBAAsB,CAAC,GAAG,EAAE;gBACjC,cAAc;gBACd,GAAG,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aAC1D,CAAC,CAAC;QACL,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;CACF"}
@@ -39,6 +39,19 @@ import type { PromotionBroadcastWorkflowStore } from "../../merchant/promotion-b
39
39
  import type { WorkbenchReconciliationStore } from "./reconciliation-worker.js";
40
40
  import { type WorkbenchEventProjectionStore } from "./event-projection.js";
41
41
  import { type GrantAction, type GrantResourceType, type MerchantGrantStore } from "../../merchant/grant-store.js";
42
+ /**
43
+ * WorkBuddy 访问配置对工作台可见的脱敏视图(M-04):平台门禁是独立于
44
+ * 运行时健康与 Catalog 绑定的第三个信号,工作台必须分开显示。
45
+ */
46
+ export interface CatalogAccessSummary {
47
+ configured: boolean;
48
+ status: string;
49
+ configVersion: number;
50
+ provider: string | null;
51
+ adapterVersion: string | null;
52
+ authMode: string | null;
53
+ updatedAt: string | null;
54
+ }
42
55
  export interface MerchantManagementApiOptions {
43
56
  /** 本实例商家(服务端绑定;不来自请求)。 */
44
57
  merchantId: string;
@@ -147,6 +160,14 @@ export interface MerchantManagementApiOptions {
147
160
  expires_at: string;
148
161
  } | null>;
149
162
  begin: () => Promise<unknown>;
163
+ /**
164
+ * WorkBuddy 访问配置(M-03/M-04)。全部只返回脱敏投影:分享码由 Catalog
165
+ * 受控保存,运行时与工作台都从不回显。缺省(undefined)时对应路由 503。
166
+ */
167
+ getAccess?: () => Promise<CatalogAccessSummary>;
168
+ refreshAccess?: () => Promise<CatalogAccessSummary>;
169
+ submitAccessShareLink?: (link: string, consentTermsVersion: string) => Promise<CatalogAccessSummary>;
170
+ revokeAccess?: () => Promise<CatalogAccessSummary>;
150
171
  };
151
172
  /** Workbench v1 trusted confirmation authority; absent means strong-confirmation routes fail closed. */
152
173
  workbenchConfirmations?: WorkbenchConfirmationStore;
@@ -213,6 +213,18 @@ export function createMerchantManagementApiHandler(options) {
213
213
  writeJson(res, 200, result, { "x-request-id": requestId });
214
214
  return;
215
215
  }
216
+ if (rest === "/catalog/access") {
217
+ const auth = requireActor(req);
218
+ authorizeOrThrow(auth.ctx, "onboarding:manage");
219
+ if (auth.ctx.role !== "owner")
220
+ throw new ManagementError("forbidden", "only owner can manage Catalog access");
221
+ const channel = options.catalogConnection;
222
+ if (channel?.getAccess === undefined) {
223
+ throw new ManagementError("unavailable", "Catalog access configuration is not configured");
224
+ }
225
+ await runAccessRoute(res, requestId, () => channel.getAccess());
226
+ return;
227
+ }
216
228
  if (rest === "/catalog/connect" || rest === "/catalog/connect/pairing") {
217
229
  const auth = requireActor(req);
218
230
  authorizeOrThrow(auth.ctx, "onboarding:manage");
@@ -621,6 +633,40 @@ export function createMerchantManagementApiHandler(options) {
621
633
  }
622
634
  return;
623
635
  }
636
+ if (rest === "/catalog/access/refresh" ||
637
+ rest === "/catalog/access/share-link" ||
638
+ rest === "/catalog/access/revoke") {
639
+ const auth = requireActor(req);
640
+ assertWriteGuards(req, auth.sessionId);
641
+ authorizeOrThrow(auth.ctx, "onboarding:manage");
642
+ if (auth.ctx.role !== "owner")
643
+ throw new ManagementError("forbidden", "only owner can manage Catalog access");
644
+ const channel = options.catalogConnection;
645
+ if (rest === "/catalog/access/refresh") {
646
+ if (channel?.refreshAccess === undefined) {
647
+ throw new ManagementError("unavailable", "Catalog access configuration is not configured");
648
+ }
649
+ await runAccessRoute(res, requestId, () => channel.refreshAccess());
650
+ return;
651
+ }
652
+ if (rest === "/catalog/access/revoke") {
653
+ if (channel?.revokeAccess === undefined) {
654
+ throw new ManagementError("unavailable", "Catalog access configuration is not configured");
655
+ }
656
+ await runAccessRoute(res, requestId, () => channel.revokeAccess());
657
+ return;
658
+ }
659
+ if (channel?.submitAccessShareLink === undefined) {
660
+ throw new ManagementError("unavailable", "Catalog access configuration is not configured");
661
+ }
662
+ // 分享链接只作为输入被解析;任何回执都不回显链接或其中的分享码。
663
+ // 代管授权是必填项:没有它,服务层会直接拒绝(fail-closed)。
664
+ const fields = objectFields(await readJsonBody(req), ["link", "consent_terms_version"]);
665
+ const link = requireString(fields["link"], "link");
666
+ const consentTermsVersion = requireString(fields["consent_terms_version"], "consent_terms_version");
667
+ await runAccessRoute(res, requestId, () => channel.submitAccessShareLink(link, consentTermsVersion));
668
+ return;
669
+ }
624
670
  if (rest === "/catalog/connect/begin") {
625
671
  const auth = requireActor(req);
626
672
  assertWriteGuards(req, auth.sessionId);
@@ -3066,6 +3112,39 @@ function writeWorkbenchProblem(res, code, requestId, title, detail, details) {
3066
3112
  });
3067
3113
  res.end(JSON.stringify(body));
3068
3114
  }
3115
+ /**
3116
+ * WorkBuddy 访问配置路由的统一出口:成功只回脱敏摘要,失败按自有码翻译成
3117
+ * Workbench problem(不反射远端原文、不含分享码或带码 URL)。
3118
+ */
3119
+ async function runAccessRoute(res, requestId, run) {
3120
+ try {
3121
+ const access = await run();
3122
+ writeJson(res, 200, { access }, { "x-request-id": requestId });
3123
+ }
3124
+ catch (error) {
3125
+ const rawCode = error?.code;
3126
+ const code = typeof rawCode === "string" ? rawCode : "";
3127
+ const mapping = {
3128
+ ACCESS_VERSION_CONFLICT: "VERSION_CONFLICT",
3129
+ ACCESS_REJECTED: "VALIDATION_ERROR",
3130
+ ACCESS_NOT_CONFIGURED: "VALIDATION_ERROR",
3131
+ ACCESS_NOT_FOUND: "RESOURCE_NOT_FOUND",
3132
+ ACCESS_UNAVAILABLE: "DEPENDENCY_UNAVAILABLE",
3133
+ STATE_INVALID: "VALIDATION_ERROR",
3134
+ MALFORMED_URL: "VALIDATION_ERROR",
3135
+ NOT_HTTPS: "VALIDATION_ERROR",
3136
+ USERINFO: "VALIDATION_ERROR",
3137
+ FRAGMENT: "VALIDATION_ERROR",
3138
+ INVALID_PORT: "VALIDATION_ERROR",
3139
+ MISSING_SHARECODE: "VALIDATION_ERROR",
3140
+ DUPLICATE_SHARECODE: "VALIDATION_ERROR",
3141
+ EMPTY_SHARECODE: "VALIDATION_ERROR",
3142
+ SHARECODE_TOO_LONG: "VALIDATION_ERROR",
3143
+ ORIGIN_MISMATCH: "VALIDATION_ERROR",
3144
+ };
3145
+ writeWorkbenchProblem(res, mapping[code] ?? "DEPENDENCY_UNAVAILABLE", requestId, "访问配置未完成", error instanceof Error && error.message.trim() !== "" ? error.message : "访问配置未完成");
3146
+ }
3147
+ }
3069
3148
  function respondWorkbenchError(res, error, requestId) {
3070
3149
  if (error instanceof WorkbenchEventProjectionError) {
3071
3150
  writeWorkbenchProblem(res, "VALIDATION_ERROR", requestId, "事件游标无效", error.message);