@capybara-hq/kernel 0.1.0-rc.92 → 0.1.0-rc.94

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 (57) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/login-sources.controller.d.ts +30 -0
  3. package/dist/admin/login-sources.controller.js +77 -0
  4. package/dist/admin/login-sources.schemas.d.ts +25 -0
  5. package/dist/admin/login-sources.schemas.js +49 -0
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/config/schema.d.ts +0 -2
  8. package/dist/config/schema.js +0 -28
  9. package/dist/ctx/create-ctx.d.ts +5 -1
  10. package/dist/ctx/create-ctx.js +13 -2
  11. package/dist/device-access/device-access.service.d.ts +27 -4
  12. package/dist/device-access/device-access.service.js +183 -29
  13. package/dist/errors.d.ts +10 -0
  14. package/dist/errors.js +10 -0
  15. package/dist/extensions/instance.js +3 -1
  16. package/dist/http/api.module.js +2 -0
  17. package/dist/identity/auth.controller.d.ts +2 -0
  18. package/dist/identity/auth.controller.js +1 -1
  19. package/dist/identity/external.d.ts +78 -40
  20. package/dist/identity/external.js +157 -72
  21. package/dist/identity/identity.module.js +9 -0
  22. package/dist/identity/linked-accounts.d.ts +42 -0
  23. package/dist/identity/linked-accounts.js +78 -0
  24. package/dist/identity/login-sources.d.ts +160 -0
  25. package/dist/identity/login-sources.js +403 -0
  26. package/dist/identity/sso-decisions.d.ts +75 -0
  27. package/dist/identity/sso-decisions.js +42 -0
  28. package/dist/identity/sso-link.d.ts +61 -0
  29. package/dist/identity/sso-link.js +157 -0
  30. package/dist/identity/sso.controller.d.ts +98 -14
  31. package/dist/identity/sso.controller.js +222 -28
  32. package/dist/identity/sso.d.ts +75 -30
  33. package/dist/identity/sso.js +129 -70
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/infra/config/kernel-config.service.js +0 -3
  37. package/dist/infra/throttler/named-throttlers.d.ts +1 -1
  38. package/dist/infra/throttler/named-throttlers.js +1 -1
  39. package/dist/platform/exclusions.js +15 -0
  40. package/dist/platform/operation.js +4 -0
  41. package/dist/platform/ops/admin.ops.d.ts +3 -1
  42. package/dist/platform/ops/admin.ops.js +106 -2
  43. package/dist/platform/ops/extensions-admin.ops.d.ts +24 -2
  44. package/dist/platform/ops/extensions-admin.ops.js +54 -6
  45. package/dist/platform/route-schemas.js +2 -0
  46. package/dist/tools/builtins/sandbox/glob.js +7 -4
  47. package/dist/tools/builtins/sandbox/grep.d.ts +8 -1
  48. package/dist/tools/builtins/sandbox/grep.js +27 -33
  49. package/dist/tools/builtins/sandbox/search-command.d.ts +43 -0
  50. package/dist/tools/builtins/sandbox/search-command.js +86 -0
  51. package/dist/tools/call-scope.d.ts +19 -6
  52. package/dist/tools/call-scope.js +29 -0
  53. package/dist/tools/pipeline.d.ts +3 -2
  54. package/dist/tools/pipeline.js +29 -10
  55. package/dist/tools/questions.service.d.ts +2 -2
  56. package/dist/tools/questions.service.js +1 -1
  57. package/package.json +3 -3
@@ -8,8 +8,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomBytes } from "node:crypto";
11
- import { DeviceAccessError, deviceServiceId, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { DEVICE_SERVICE_ROLL_CHECK, DeviceAccessError, deviceServiceFilesDigest, deviceServiceId, parseRollCheck, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
13
14
  import { DeviceAccess } from "../devices/access.js";
14
15
  import { ConversationDevices } from "../devices/conversation-devices.js";
15
16
  import { DevicesService } from "../devices/devices.service.js";
@@ -24,23 +25,38 @@ import { rootConversationOf } from "../runtime/subagents/child.js";
24
25
  import { assertServiceSpec, DeviceServices } from "../sandbox/device-services.js";
25
26
  import { DeviceProviders } from "../sandbox/providers.js";
26
27
  import { CommandReviewService } from "../sandbox/review/review.service.js";
27
- import { attachCallScope, callScopeOf, whileDeviceStarting, } from "../tools/call-scope.js";
28
+ import { mapSandboxError } from "../tools/builtins/sandbox/common.js";
29
+ import { attachCallScope, callScopeOf, serviceHostKey, strongerLayer, whileDeviceStarting, } from "../tools/call-scope.js";
28
30
  import { QuestionsService } from "../tools/questions.service.js";
31
+ /** The layers a service may report a refused host with (`ServiceBlockedHost.layer`). */
32
+ const BLOCK_LAYERS = ["device", "org", "address", "unknown"];
29
33
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
30
34
  export const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
31
35
  /** A viewer ticket's key prefix (`capk:device-stream-ticket:<id>`, single use, GETDEL). */
32
36
  export const DEVICE_STREAM_TICKET_PREFIX = "capk:device-stream-ticket:";
33
37
  /** How long a viewer ticket lives, in seconds. */
34
38
  export const DEVICE_STREAM_TICKET_TTL_SECONDS = 60;
39
+ /**
40
+ * The longest a service's busy answer holds a roll onto the same files, counted from the first
41
+ * busy answer (`capk:device-service-roll-held:<device>:<service>:<digest>`, the first answer's
42
+ * time, a TTL of twice this).
43
+ */
44
+ const ROLL_HOLD_CAP_MS = 60 * 60_000;
45
+ const ROLL_HOLD_PREFIX = "capk:device-service-roll-held:";
46
+ /** How long the roll check waits for a running service's answer ({@link DEVICE_SERVICE_ROLL_CHECK}). */
47
+ const ROLL_CHECK_TIMEOUT_MS = 5_000;
35
48
  /** Maps the device resolution's API errors to the extension's refusal codes. */
36
- function refusal(e) {
37
- if (!(e instanceof ApiError))
38
- return e;
39
- if (e.code === "device.not_found" || e.code === "sandbox.unavailable")
40
- return new DeviceAccessError("no_device", e.message, { cause: e });
41
- if (e.code === "device.unavailable")
42
- return new DeviceAccessError("provider_unavailable", e.message, { cause: e });
43
- return e;
49
+ function refusal(e, log) {
50
+ if (e instanceof ApiError) {
51
+ if (e.code === "device.not_found" || e.code === "sandbox.unavailable")
52
+ return new DeviceAccessError("no_device", e.message, { cause: e });
53
+ if (e.code === "device.unavailable")
54
+ return new DeviceAccessError("provider_unavailable", e.message, { cause: e });
55
+ }
56
+ // every other device or provider failure as the sandbox tools say it (the provider cannot be
57
+ // reached, the machine is offline or outdated, the outcome is unknown, ...): an actionable
58
+ // ToolError the extension passes on, never its own guess
59
+ return mapSandboxError(e, log);
44
60
  }
45
61
  /** How long the refresh of one service after an allowlist change may take. */
46
62
  const REFRESH_TIMEOUT_MS = 30_000;
@@ -137,13 +153,26 @@ let DeviceAccessService = class DeviceAccessService {
137
153
  return asNamed(await this.services.ensure(use, providerSpec, call.signal, { ifRunning }), name);
138
154
  }
139
155
  catch (e) {
140
- throw refusal(e);
156
+ throw refusal(e, this.log);
141
157
  }
142
158
  };
143
159
  // race-free: the provider keeps a running service and never starts a stopped one here
160
+ // a service running other files (the extension was upgraded since it started) gets a start
161
+ // like a stopped one, reviewed below; the provider then restarts it on the spec's files (a
162
+ // roll). The digest is cached per files object (a browser's files are megabytes).
163
+ const digest = deviceServiceFilesDigest(providerSpec.files);
164
+ const runsSpec = (st) => st.filesDigest === undefined || st.filesDigest === digest;
144
165
  const found = await ensure(true);
145
- if (found.state === "running")
146
- return found;
166
+ if (found.state === "running") {
167
+ if (runsSpec(found))
168
+ return found;
169
+ // never a roll back to older files, nor one under a person at work: kept, rolled later
170
+ if (await this.holdRoll(caller, use, providerSpec.name, name, digest, call.signal))
171
+ return found;
172
+ }
173
+ // A stopped service is started on the caller's files even when the caller is draining (its
174
+ // call still needs the service): the next call of the current instance rolls it forward, one
175
+ // restart more during an upgrade.
147
176
  const reviewFacts = await this.devices.reviewFacts(call.orgId, facts.rootConversationId, call.conversationId);
148
177
  if (reviewFacts === null || reviewFacts.deviceId !== use.deviceId)
149
178
  throw new DeviceAccessError("no_device", "The conversation has no device to run in.");
@@ -193,13 +222,47 @@ let DeviceAccessService = class DeviceAccessService {
193
222
  // another call may have started it since the first look (that call audits its own start):
194
223
  // found running now, this call started nothing and audits nothing
195
224
  const raced = await ensure(true);
196
- if (raced.state === "running")
225
+ if (raced.state === "running" && runsSpec(raced))
226
+ return raced;
227
+ // another call started it on other files meanwhile, or the review took long enough for a
228
+ // person to take over: the same holds as at the first look
229
+ if (raced.state === "running" &&
230
+ (await this.holdRoll(caller, use, providerSpec.name, name, digest, call.signal)))
197
231
  return raced;
198
232
  const started = await ensure(false);
199
- // audited only when this ensure started it: the service was stopped (no startedAt) just
200
- // before, and runs with a startedAt now
233
+ // a provider that reports the digest but kept the old files would have every later call
234
+ // reviewed again for nothing: a broken provider, said as such
235
+ if (started.state === "running" && !runsSpec(started)) {
236
+ this.log.error("device provider kept a service on other files after a start", {
237
+ extension: caller.extension,
238
+ service: name,
239
+ deviceId: use.deviceId,
240
+ running: started.filesDigest,
241
+ wanted: digest,
242
+ });
243
+ throw new ToolError(`The device service ${name} still runs its earlier files after a restart was asked for; the device's provider did not restart it. Ask the user to update the device's provider plugin, then retry.`);
244
+ }
245
+ // audited only when this ensure started it: the service was stopped (no startedAt) or ran
246
+ // other files just before, and runs with a new startedAt now; one row per start, also when
247
+ // two replicas' calls both got here (the second finds the first one's process)
201
248
  if (started.state !== "running" || started.startedAt === raced.startedAt)
202
249
  return started;
250
+ // the start's own row, written by whichever call saw it first (a check, then the insert: two
251
+ // replicas reaching it in the same milliseconds may still both write)
252
+ const seen = await this.db
253
+ .selectFrom("audit_events")
254
+ .select("id")
255
+ .where("org_id", "=", call.orgId)
256
+ .where("action", "=", "device.service_started")
257
+ .where("target", "=", use.deviceId)
258
+ .where(sql `detail->>'serviceId'`, "=", providerSpec.name)
259
+ .where(sql `detail->>'startedAt'`, "=", started.startedAt)
260
+ // the start just happened: the (org_id, at) index keeps the range tiny
261
+ .where("at", ">=", sql `now() - interval '10 minutes'`)
262
+ .executeTakeFirst();
263
+ if (seen !== undefined)
264
+ return started;
265
+ const rolled = raced.state === "running";
203
266
  await audit(this.db, {
204
267
  actorAccountId: call.accountId,
205
268
  orgId: call.orgId,
@@ -213,10 +276,93 @@ let DeviceAccessService = class DeviceAccessService {
213
276
  argv,
214
277
  decision: record.decision,
215
278
  rule: record.rule,
279
+ // a roll replaces a process running other files; a start follows a stopped service
280
+ reason: rolled ? "files_changed" : "start",
281
+ startedAt: started.startedAt,
282
+ filesDigest: started.filesDigest ?? digest,
283
+ ...(rolled && {
284
+ replacedStartedAt: raced.startedAt,
285
+ ...(raced.filesDigest !== undefined && { replacedFilesDigest: raced.filesDigest }),
286
+ }),
216
287
  },
217
288
  });
218
289
  return started;
219
290
  }
291
+ /**
292
+ * Whether a roll of a running service onto `digest` is held now ({@link rollHeld}), logged
293
+ * with the reason when it is.
294
+ */
295
+ async holdRoll(caller, use, serviceId, name, digest, signal) {
296
+ const held = await this.rollHeld(caller, use, serviceId, digest, signal);
297
+ if (held === null)
298
+ return false;
299
+ this.log.info("device service roll deferred", {
300
+ extension: caller.extension,
301
+ service: name,
302
+ deviceId: use.deviceId,
303
+ reason: held,
304
+ });
305
+ return true;
306
+ }
307
+ /**
308
+ * Why a running service on other files is kept for now, or null to roll it:
309
+ * - the calling instance is being replaced or is not the one this replica runs now (it drains),
310
+ * or not the version the deployment has enabled (a replica that has not reloaded yet): its
311
+ * files are older, and rolling to them would flip the service back and forth;
312
+ * - the service answers the roll check busy (a person controls it or a handoff waits), for at
313
+ * most {@link ROLL_HOLD_CAP_MS} after the first busy answer for these files (a Redis record
314
+ * with a TTL: a service that stays busy, a handoff nobody ends, never holds an upgrade for
315
+ * good).
316
+ * A failed check (an older service, no answer) lets the roll go ahead.
317
+ */
318
+ async rollHeld(caller, use, serviceId, digest, signal) {
319
+ if (caller.superseded?.() === true)
320
+ return "superseded: the calling instance is draining";
321
+ const sha = caller.sha256 ?? null;
322
+ if (sha !== null) {
323
+ const loaded = this.registry.current(caller.extension);
324
+ if (loaded === undefined || (loaded.sha256 ?? null) !== sha)
325
+ return "superseded: this replica runs another package of the extension";
326
+ // deployment-wide: the extension's install record, not an org's data
327
+ const row = await this.db
328
+ .selectFrom("extension_installs")
329
+ .select("sha256")
330
+ .where("name", "=", caller.extension)
331
+ .where("desired_state", "=", "enabled")
332
+ .executeTakeFirst();
333
+ if (row !== undefined && row.sha256 !== sha)
334
+ return "stale: the deployment enabled another package of the extension";
335
+ }
336
+ try {
337
+ const answer = await this.services.request(use, serviceId, new TextEncoder().encode(DEVICE_SERVICE_ROLL_CHECK), ROLL_CHECK_TIMEOUT_MS, AbortSignal.any([signal, AbortSignal.timeout(ROLL_CHECK_TIMEOUT_MS)]));
338
+ const check = parseRollCheck(answer);
339
+ if (check.busy) {
340
+ const key = `${ROLL_HOLD_PREFIX}${use.deviceId}:${serviceId}:${digest}`;
341
+ const now = Date.now();
342
+ // the first busy answer's time, kept by whichever replica wrote it first (HSETNX)
343
+ if ((await this.redis.hsetnx(key, "first", String(now))) === 1)
344
+ await this.redis.pexpire(key, ROLL_HOLD_CAP_MS * 2);
345
+ const first = Number(await this.redis.hget(key, "first"));
346
+ if (Number.isFinite(first) && now - first >= ROLL_HOLD_CAP_MS) {
347
+ this.log.warn("device service roll no longer held by its busy answer", {
348
+ extension: caller.extension,
349
+ serviceId,
350
+ deviceId: use.deviceId,
351
+ heldMs: now - first,
352
+ reason: check.reason,
353
+ });
354
+ return null;
355
+ }
356
+ return `busy: ${check.reason ?? "the service is in use"}`;
357
+ }
358
+ }
359
+ catch (e) {
360
+ if (signal.aborted)
361
+ throw e;
362
+ // an older service, a slow one: the roll goes ahead
363
+ }
364
+ return null;
365
+ }
220
366
  /** One request to the service's socket in the call's device. */
221
367
  async request(caller, call, req) {
222
368
  assertDeclared(caller, req.service);
@@ -230,28 +376,36 @@ let DeviceAccessService = class DeviceAccessService {
230
376
  return await this.services.request(use, deviceServiceId(caller.extension, req.service), req.body, req.timeoutMs, call.signal);
231
377
  }
232
378
  catch (e) {
233
- throw refusal(e);
379
+ throw refusal(e, this.log);
234
380
  }
235
381
  }
236
382
  /**
237
- * Records refused hosts in the call scope (synchronous: the pipeline reads it once the handler
238
- * returns) on the device this call's own `ctx.deviceAccess` calls resolved, if any.
383
+ * Records refused hosts with their layers in the call scope (synchronous: the pipeline reads it
384
+ * once the handler returns) on the device this call's own `ctx.deviceAccess` calls resolved, if
385
+ * any. A malformed entry (not a non-empty host with a known layer) is dropped; a host reported
386
+ * again keeps its most restrictive layer, so a later report never makes it grantable.
239
387
  */
240
388
  reportBlockedHosts(call, hosts, opts) {
241
389
  assertCallOwner(call);
242
390
  const scope = callScopeOf(call) ?? attachCallScope(call);
243
- const valid = hosts.filter((h) => typeof h === "string" && h.length > 0);
391
+ const valid = (Array.isArray(hosts) ? hosts : []).filter((h) => typeof h === "object" &&
392
+ h !== null &&
393
+ typeof h.host === "string" &&
394
+ h.host.length > 0 &&
395
+ BLOCK_LAYERS.includes(h.layer));
244
396
  if (valid.length === 0)
245
397
  return;
246
398
  const url = typeof opts?.url === "string" && opts.url.length > 0 ? opts.url : null;
247
- if (scope.blocked === null) {
248
- scope.blocked = { deviceId: scope.device, hosts: new Set(valid), url };
249
- return;
250
- }
251
- for (const h of valid)
252
- scope.blocked.hosts.add(h);
253
- if (url !== null)
399
+ if (scope.blocked === null)
400
+ scope.blocked = { deviceId: scope.device, hosts: new Map(), url };
401
+ else if (url !== null)
254
402
  scope.blocked.url = url;
403
+ const seen = scope.blocked.hosts;
404
+ for (const h of valid) {
405
+ const key = serviceHostKey(h.host);
406
+ const had = seen.get(key);
407
+ seen.set(key, had === undefined ? h.layer : strongerLayer(had, h.layer));
408
+ }
255
409
  }
256
410
  /** A single-use viewer ticket for the service (the person's panel opens `url`). */
257
411
  async streamTicket(caller, scope) {
@@ -433,7 +587,7 @@ let DeviceAccessService = class DeviceAccessService {
433
587
  deviceId = await this.devices.forTool(call.orgId, rootConversationId);
434
588
  }
435
589
  catch (e) {
436
- throw refusal(e);
590
+ throw refusal(e, this.log);
437
591
  }
438
592
  scope.device = deviceId;
439
593
  return {
@@ -482,7 +636,7 @@ let DeviceAccessService = class DeviceAccessService {
482
636
  // the device bound to the owner's conversation is not theirs to use: someone else's
483
637
  if (e instanceof ApiError && e.code === "device.not_found")
484
638
  throw new DeviceAccessError("not_owner", DEVICE_ACCESS_NOT_OWNER_TEXT, { cause: e });
485
- throw refusal(e);
639
+ throw refusal(e, this.log);
486
640
  }
487
641
  return {
488
642
  orgId: conv.org_id,
package/dist/errors.d.ts CHANGED
@@ -411,7 +411,17 @@ export declare const ERROR_CODES: {
411
411
  readonly "identity.taken": 409;
412
412
  readonly "identity.not_found": 404;
413
413
  readonly "identity.last_login_method": 409;
414
+ /** A login source update names an extension that is neither a loaded identity source nor stored. */
415
+ readonly "login_sources.unknown_plugin": 404;
416
+ /** A trusted tenant is blank or refused by the source's tenant declaration. */
417
+ readonly "login_sources.invalid_tenant": 400;
418
+ /** Turning a login source on while its extension's deployment config is not complete. */
419
+ readonly "login_sources.needs_config": 409;
414
420
  readonly "bind.invalid": 404;
421
+ /** The link page's ticket is unknown, expired, used, burned, or its login source is off. */
422
+ readonly "sso.link_expired": 410;
423
+ /** The link page's browser binding cookie does not match the sign-in that made the ticket. */
424
+ readonly "sso.session_mismatch": 403;
415
425
  readonly "channel.not_found": 404;
416
426
  readonly "channel.verify_failed": 502;
417
427
  readonly "channel.webhook_not_found": 404;
package/dist/errors.js CHANGED
@@ -411,7 +411,17 @@ export const ERROR_CODES = {
411
411
  "identity.taken": 409,
412
412
  "identity.not_found": 404,
413
413
  "identity.last_login_method": 409,
414
+ /** A login source update names an extension that is neither a loaded identity source nor stored. */
415
+ "login_sources.unknown_plugin": 404,
416
+ /** A trusted tenant is blank or refused by the source's tenant declaration. */
417
+ "login_sources.invalid_tenant": 400,
418
+ /** Turning a login source on while its extension's deployment config is not complete. */
419
+ "login_sources.needs_config": 409,
414
420
  "bind.invalid": 404,
421
+ /** The link page's ticket is unknown, expired, used, burned, or its login source is off. */
422
+ "sso.link_expired": 410,
423
+ /** The link page's browser binding cookie does not match the sign-in that made the ticket. */
424
+ "sso.session_mismatch": 403,
415
425
  "channel.not_found": 404,
416
426
  "channel.verify_failed": 502,
417
427
  "channel.webhook_not_found": 404,
@@ -293,7 +293,9 @@ export function warnUpgrades(log, imports) {
293
293
  /** 在已导入、已核对的清单上建 ctx(记账)并 setup;setup 抛错时撤销已登记的再抛。 */
294
294
  export async function setupInstance(deps, manifest, input) {
295
295
  const live = new LiveConfig(input.config);
296
- const ctx = createExtensionContext(deps.kernel, manifest, live, deps.extensionPointAccess);
296
+ const ctx = createExtensionContext(deps.kernel, manifest, live, deps.extensionPointAccess, {
297
+ sha256: input.sha256,
298
+ });
297
299
  input.onCtx?.(ctx);
298
300
  try {
299
301
  await manifest.setup(ctx);
@@ -12,6 +12,7 @@ import { AdminAgentsController } from "../admin/admin-agents.controller.js";
12
12
  import { AdminConnectorsController } from "../admin/admin-connectors.controller.js";
13
13
  import { AdminAuditController, OrgAuditController } from "../admin/audit.controller.js";
14
14
  import { AdminExtensionsController } from "../admin/extensions.controller.js";
15
+ import { AdminLoginSourcesController } from "../admin/login-sources.controller.js";
15
16
  import { AdminOrgNetworkController } from "../admin/org-network.controller.js";
16
17
  import { OutboxDeadController } from "../admin/outbox-dead.controller.js";
17
18
  import { AdminOverviewController } from "../admin/overview.controller.js";
@@ -137,6 +138,7 @@ const CONTROLLERS = [
137
138
  AdminOverviewController,
138
139
  OutboxDeadController,
139
140
  AdminOrgNetworkController,
141
+ AdminLoginSourcesController,
140
142
  AdminExtensionsController,
141
143
  AdminCatalogController,
142
144
  AdminComponentsController,
@@ -8,6 +8,8 @@ declare const LoginBodySchema: z.ZodObject<{
8
8
  login: z.ZodString;
9
9
  password: z.ZodString;
10
10
  }, z.core.$strip>;
11
+ /** The credential throttlers of a login attempt (R25: per (login, IP), per IP, per login). */
12
+ export declare const LOGIN_THROTTLERS: readonly ["login", "login-ip", "login-account"];
11
13
  /** 会话的客户端信息(记入 sessions 表)。`req.ip` 在 `http.trustProxy` 时取自 X-Forwarded-For。 */
12
14
  export declare function clientMeta(req: FastifyRequest): {
13
15
  userAgent?: string;
@@ -22,7 +22,7 @@ const LoginBodySchema = z.object({ login: z.string().max(256), password: z.strin
22
22
  class LoginBody extends createZodDto(LoginBodySchema, "LoginBody") {
23
23
  }
24
24
  /** The credential throttlers of a login attempt (R25: per (login, IP), per IP, per login). */
25
- const LOGIN_THROTTLERS = ["login", "login-ip", "login-account"];
25
+ export const LOGIN_THROTTLERS = ["login", "login-ip", "login-account"];
26
26
  /** 会话的客户端信息(记入 sessions 表)。`req.ip` 在 `http.trustProxy` 时取自 X-Forwarded-For。 */
27
27
  export function clientMeta(req) {
28
28
  const ua = req.headers["user-agent"];
@@ -1,30 +1,32 @@
1
1
  import type { ExternalIdentity } from "@capybara-hq/plugin-sdk";
2
2
  import type { LinkedVia } from "../db/kernel-schema.js";
3
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
3
  import { KernelDb } from "../infra/database/kernel-db.js";
5
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
5
  import { ExternalIdentityLock } from "./external-identity-lock.js";
6
+ import { LoginSourcesService } from "./login-sources.js";
7
+ import { type SsoDecision, type SsoIntent } from "./sso-decisions.js";
7
8
  export type { LinkedVia };
8
- /**
9
- * 第三方登录拒绝了这个身份(Ruling A18):身份行经 IM 绑定链接建立,而请求没有带着同一账号的会话。
10
- * 登录页原因码 `sso.identity_not_verified`。
11
- */
12
- export declare class IdentityNotVerified extends Error {
13
- constructor();
14
- }
15
- /** {@link ExternalIdentities.resolve} 的选项。 */
9
+ /** The options of {@link ExternalIdentities.resolve}. */
16
10
  export interface ResolveOptions {
17
- /** 只有第三方登录路径传 true(Ruling A9)。 */
18
- allowMerge?: boolean;
19
- /** 新建身份行时记下的建立方式:第三方登录 `sso`,通讯录同步 `directory`。已有的行不改。 */
20
- linkedVia: "sso" | "directory";
21
11
  /**
22
- * 第三方登录路径:已有的身份行须可用于登录(见 {@link ExternalIdentities.resolve})。
23
- * `sessionAccountId` 为请求已带着的 Web 会话的账号(没有会话时省略)。
12
+ * How a new identity row is made: `sso` (a sign-in's self sign-up), `directory` (directory
13
+ * sync). An existing row keeps its kind.
24
14
  */
25
- login?: {
26
- sessionAccountId?: string;
27
- };
15
+ linkedVia: "sso" | "directory";
16
+ }
17
+ /** How a verified link was made (`identity.linked` audit `via`). */
18
+ export type VerifiedLinkVia = "oauth" | "link_page" | "verified_email";
19
+ /** A sign-in decision once applied: a creation is reported as the sign-in of the new account. */
20
+ export type SignInDecision = Exclude<SsoDecision, {
21
+ kind: "create";
22
+ }>;
23
+ /** The sign-in callback's context for {@link ExternalIdentities.decideSignIn}. */
24
+ export interface SignInContext {
25
+ intent: SsoIntent;
26
+ /** Link intent only: the account of the web session the start and the callback both carried. */
27
+ sessionAccountId?: string;
28
+ /** The login source's setting for an unlinked external account. */
29
+ signUp: "link" | "create";
28
30
  }
29
31
  /** 账号已绑定的一个外部身份(不含本地登录名)。 */
30
32
  export interface LinkedIdentity {
@@ -44,31 +46,31 @@ export interface LinkedIdentity {
44
46
  /** 身份源键里的插件名(`source` 中 `:` 之前的部分)。 */
45
47
  export declare function identityPlugin(source: string): string;
46
48
  /**
47
- * 外部身份:按 `(source, externalId)` 映射到账号(登录、渠道入站、通讯录共用同一个键)。
48
- * 首次出现时按「受信任的身份源 + 两侧邮箱均已验证」合并到既有账号,否则新建账号(不建组织)。
49
- * Concurrent first resolves of one identity are serialized by {@link ExternalIdentityLock},
50
- * so only one account is created.
49
+ * External identities: `(source, externalId)` maps to an account (sign-in, channel inbound and the
50
+ * directory share the key). A sign-in of an identity nobody has linked ({@link decideSignIn})
51
+ * merges into an existing account when its tenant is trusted and both emails are verified;
52
+ * otherwise it goes to the link page by default, and creates a new org-less account only when the
53
+ * login source's `signUp` is `create`. Directory sync creates the account for its identity
54
+ * ({@link resolve}). Concurrent first resolves of one identity are serialized by
55
+ * {@link ExternalIdentityLock}, so only one account is created.
51
56
  */
52
57
  export declare class ExternalIdentities {
53
58
  private readonly db;
54
59
  readonly txHost: TransactionHost;
55
60
  private readonly identityLock;
56
- private readonly config;
57
- constructor(db: KernelDb, txHost: TransactionHost, identityLock: ExternalIdentityLock, config: Pick<KernelConfigService, "get">);
61
+ private readonly loginSources;
62
+ constructor(db: KernelDb, txHost: TransactionHost, identityLock: ExternalIdentityLock, loginSources: Pick<LoginSourcesService, "isTrusted">);
58
63
  /** The account the external identity is linked to (in the context's transaction when there is one); undefined when unlinked. */
59
64
  findAccount(source: string, externalId: string): Promise<string | undefined>;
60
65
  /**
61
- * 解析外部身份到账号。已绑定 → 该账号(顺带刷新身份行上的邮箱与资料);未绑定 → 合并或新建(见类说明),
62
- * 新身份行记 `linked_via = opts.linkedVia`(合并也是 `sso`)。
63
- * 合并只在 `opts.allowMerge` 时考虑(Ruling A9:只有第三方登录路径传 true;渠道入站、通讯录不传)。
64
- * 第三方登录(`opts.login`,Ruling A18 / A23):已有的身份行若经 IM 绑定建立(`bind`),只证明了某个网页登录者
65
- * 点过绑定链接,不证明他控制该外部身份——此时只有请求已带着**同一账号**的会话(本人在已登录状态下完成第三方登录,
66
- * 证明自己控制该身份)才放行,并把行升级为 `sso`(审计 `identity.verified`);否则抛 {@link IdentityNotVerified}。
67
- * 通讯录建立的行(`directory`)不论租户是否受信任都可直接登录:身份源登录本身就证明登录者控制该身份,
68
- * 而通讯录身份总是指向为它新建的账号(信任只影响合并与 `email_verified`)。旧行(`linked_via` 为 null)按 `sso` 处理。
69
- * 新建账号的 `email_verified` 只在身份源受信任且身份邮箱已验证时为 true——不受信任的身份源可以声称任意邮箱
70
- * 「已验证」,不能让它建出的账号成为日后受信任登录的合并目标。
71
- * 合并写审计 `identity.linked`,新建写 `account.created`。不判断账号状态,由调用方决定(如登录拒绝停用账号)。
66
+ * Resolves an external identity to an account: linked → that account (the row's email and
67
+ * profile are refreshed); unlinked → a new org-less account with this identity, the row
68
+ * recording `linked_via = opts.linkedVia`. It never merges by email and never checks a row for
69
+ * sign-in: the sign-in callback goes through {@link decideSignIn} (which calls this only for a
70
+ * self sign-up); directory sync calls it directly. A created account's `email_verified` is true
71
+ * only when the source is trusted and the identity's email is verified: an untrusted source can
72
+ * claim any email "verified", and its accounts must not become merge targets of a later trusted
73
+ * sign-in. A creation audits `account.created`. The account's status is not checked.
72
74
  * Joins the caller's transaction when there is one; takes the same lock as `link`, and falls back
73
75
  * to `ON CONFLICT DO NOTHING` plus a re-read, so it never throws a unique violation or aborts the
74
76
  * caller's transaction.
@@ -77,18 +79,54 @@ export declare class ExternalIdentities {
77
79
  accountId: string;
78
80
  created: boolean;
79
81
  }>;
82
+ /**
83
+ * The sign-in callback's decision on a verified external identity (spec §4,
84
+ * {@link decideSsoCallback}), taken and applied in one transaction under the identity lock: the
85
+ * row and the merge target are read under the lock, then `signin` / `refresh` refresh the row,
86
+ * `upgrade` and `linked` go through {@link linkVerified}, `create` creates the account
87
+ * ({@link resolve}, no merge: the decision ruled it out). `link_page` and `error` write nothing.
88
+ * A link intent never creates an account. Returns the decision, whether an account was created
89
+ * and the normalized identity (what a link page stores). Throws `identity.taken` when a concurrent writer linked the
90
+ * identity to another account between the read and the write (cannot happen under the lock
91
+ * except for a writer that skips it).
92
+ */
93
+ decideSignIn(identity: ExternalIdentity, ctx: SignInContext): Promise<{
94
+ decision: SignInDecision;
95
+ identity: ExternalIdentity;
96
+ created: boolean;
97
+ }>;
98
+ private isActive;
99
+ /**
100
+ * Links an external identity whose control the person proved (a third-party sign-in, or the
101
+ * link page's password plus the sign-in) to `accountId` as `sso`: no row → a new `sso` row
102
+ * (audit `identity.linked` with `via`); a `bind` row of the same account → upgraded to `sso`
103
+ * (audit `identity.verified`); an `sso` / `directory` / legacy row of the same account → its
104
+ * profile refreshed; a row of another account → `409 identity.taken`. Under the identity lock,
105
+ * in the caller's transaction when there is one.
106
+ */
107
+ linkVerified(accountId: string, identity: ExternalIdentity, via: VerifiedLinkVia): Promise<void>;
108
+ /**
109
+ * The account an identity row links to and how it was made, without a lock (the link page's
110
+ * read-only view; any write re-reads under the lock).
111
+ */
112
+ peekRow(identity: Pick<ExternalIdentity, "source" | "externalId">): Promise<{
113
+ accountId: string;
114
+ linkedVia: LinkedVia | null;
115
+ } | undefined>;
80
116
  /** Serializes resolve / link of one identity ({@link ExternalIdentityLock}). */
81
117
  private lockIdentity;
82
- /** 身份源键(`<插件名>:<租户 id>`)是否在 `auth.trustedIdentitySources` 中:按完整键比较,信任按租户(Ruling A19)。 */
118
+ /**
119
+ * Whether the source key (`<plugin>:<tenant>`) is trusted: its tenant is among the login
120
+ * source's trusted tenants, full key match, trust is per tenant (Ruling A19).
121
+ */
83
122
  private trusted;
84
123
  private findRow;
85
- /** 第三方登录能否用这一行(见 {@link resolve}):只有 `bind` 行需要同一账号的会话,放行时把行改为 `sso`。 */
86
- private allowLogin;
87
124
  private mustFind;
88
125
  private refreshIdentity;
89
126
  /**
90
- * 可合并的既有账号:身份源键在 `auth.trustedIdentitySources` 中、身份邮箱已验证,
91
- * 且恰好有一个邮箱已验证、邮箱相同(不区分大小写)的账号;否则 undefined(多个候选时不猜,新建)。
127
+ * The existing account to merge into: the source key is trusted (a trusted tenant of its login
128
+ * source), the identity's email is verified, and exactly one account has the same verified email
129
+ * (case-insensitive); else undefined (with several candidates it never guesses).
92
130
  */
93
131
  private mergeTarget;
94
132
  /** 插入身份行;已存在(主键冲突)时什么都不做并返回 false。 */