@capybara-hq/kernel 0.1.0-rc.93 → 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 (56) hide show
  1. package/dist/admin/login-sources.controller.d.ts +30 -0
  2. package/dist/admin/login-sources.controller.js +77 -0
  3. package/dist/admin/login-sources.schemas.d.ts +25 -0
  4. package/dist/admin/login-sources.schemas.js +49 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +0 -2
  7. package/dist/config/schema.js +0 -28
  8. package/dist/ctx/create-ctx.d.ts +5 -1
  9. package/dist/ctx/create-ctx.js +13 -2
  10. package/dist/device-access/device-access.service.d.ts +27 -4
  11. package/dist/device-access/device-access.service.js +180 -30
  12. package/dist/errors.d.ts +10 -0
  13. package/dist/errors.js +10 -0
  14. package/dist/extensions/instance.js +3 -1
  15. package/dist/http/api.module.js +2 -0
  16. package/dist/identity/auth.controller.d.ts +2 -0
  17. package/dist/identity/auth.controller.js +1 -1
  18. package/dist/identity/external.d.ts +78 -40
  19. package/dist/identity/external.js +157 -72
  20. package/dist/identity/identity.module.js +9 -0
  21. package/dist/identity/linked-accounts.d.ts +42 -0
  22. package/dist/identity/linked-accounts.js +78 -0
  23. package/dist/identity/login-sources.d.ts +160 -0
  24. package/dist/identity/login-sources.js +403 -0
  25. package/dist/identity/sso-decisions.d.ts +75 -0
  26. package/dist/identity/sso-decisions.js +42 -0
  27. package/dist/identity/sso-link.d.ts +61 -0
  28. package/dist/identity/sso-link.js +157 -0
  29. package/dist/identity/sso.controller.d.ts +98 -14
  30. package/dist/identity/sso.controller.js +222 -28
  31. package/dist/identity/sso.d.ts +75 -30
  32. package/dist/identity/sso.js +129 -70
  33. package/dist/index.d.ts +1 -0
  34. package/dist/index.js +1 -0
  35. package/dist/infra/config/kernel-config.service.js +0 -3
  36. package/dist/infra/throttler/named-throttlers.d.ts +1 -1
  37. package/dist/infra/throttler/named-throttlers.js +1 -1
  38. package/dist/platform/exclusions.js +15 -0
  39. package/dist/platform/operation.js +4 -0
  40. package/dist/platform/ops/admin.ops.d.ts +3 -1
  41. package/dist/platform/ops/admin.ops.js +106 -2
  42. package/dist/platform/ops/extensions-admin.ops.d.ts +24 -2
  43. package/dist/platform/ops/extensions-admin.ops.js +54 -6
  44. package/dist/platform/route-schemas.js +2 -0
  45. package/dist/tools/builtins/sandbox/glob.js +7 -4
  46. package/dist/tools/builtins/sandbox/grep.d.ts +8 -1
  47. package/dist/tools/builtins/sandbox/grep.js +27 -33
  48. package/dist/tools/builtins/sandbox/search-command.d.ts +43 -0
  49. package/dist/tools/builtins/sandbox/search-command.js +86 -0
  50. package/dist/tools/call-scope.d.ts +19 -6
  51. package/dist/tools/call-scope.js +29 -0
  52. package/dist/tools/pipeline.d.ts +3 -2
  53. package/dist/tools/pipeline.js +29 -10
  54. package/dist/tools/questions.service.d.ts +2 -2
  55. package/dist/tools/questions.service.js +1 -1
  56. package/package.json +3 -3
@@ -1,8 +1,12 @@
1
- import { type Logger } from "@capybara-hq/plugin-sdk";
1
+ import { type IdentitySource, type Logger } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { ExtensionRegistry } from "../extensions/registry.js";
4
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
5
  import { ExternalIdentities } from "./external.js";
6
+ import { LoginSourcesService } from "./login-sources.js";
7
+ import type { SsoIntent } from "./sso-decisions.js";
8
+ import { SsoLinkTickets } from "./sso-link.js";
9
+ export { decideSsoCallback, type SsoDecision, type SsoDecisionInput, type SsoIntent, } from "./sso-decisions.js";
6
10
  /** state 的有效期(秒)。 */
7
11
  export declare const SSO_STATE_TTL_SECONDS = 600;
8
12
  /** 浏览器绑定 Cookie:回调必须来自发起登录的同一个浏览器(防登录 CSRF / 把回跳链接转给别人)。 */
@@ -14,73 +18,114 @@ export declare const LOGIN_PATH = "/login";
14
18
  /** 插件 `callback` 的最长等待。 */
15
19
  export declare const SSO_CALLBACK_TIMEOUT_MS = 15000;
16
20
  /**
17
- * 登录失败的原因码(放进回跳 URL `/login?error=<code>`,界面按码走 i18n;不回显身份源的任何文本)。
18
- * `auth.account_disabled` 与 API 错误码同名。
21
+ * The reason codes of a failed sign-in (in the redirect `/login?error=<code>`; the page shows its
22
+ * own i18n text per code and never the identity source's text). `auth.account_disabled`,
23
+ * `sso.session_mismatch` and `sso.link_expired` share their names with API error codes (the link
24
+ * page's routes answer them as errors).
19
25
  */
20
- export type SsoLoginError = "sso.unavailable" | "sso.state_invalid" | "sso.session_mismatch" | "sso.access_denied" | "sso.provider_error" | "sso.account_not_allowed" | "sso.identity_not_verified" | "auth.account_disabled";
26
+ export type SsoLoginError = "sso.unavailable" | "sso.state_invalid" | "sso.session_mismatch" | "sso.access_denied" | "sso.provider_error" | "sso.account_not_allowed" | "sso.link_expired" | "auth.account_disabled";
21
27
  /** 一个有效的浏览器绑定值(复用请求里已有的,否则新生成)。 */
22
28
  export declare function ssoBrowserBinding(existing: string | undefined): string;
23
- /** 回跳页面:站内相对路径(以单个 `/` 开头,非 `//`),否则 `/`(防开放重定向)。 */
29
+ /** Appends `error=<code>` to a site path (a link intent's failure back on its page). */
30
+ export declare function withError(path: string, code: string): string;
31
+ /** The return page: a site-relative path (a single leading `/`, not `//`), else `/` (no open redirect). */
24
32
  export declare function safeReturnTo(p: string | undefined): string;
25
- /** 回调结果:成功给账号与回跳页面,失败给原因码。 */
33
+ /**
34
+ * The callback's outcome: `signin` creates a session for the account; `linked` (a link intent)
35
+ * keeps the session it has and goes back to the page; `link_page` sends the person to the link
36
+ * page with a ticket. A failure carries its reason code; `returnTo` is set for a link intent's
37
+ * failure after the session check (back to the page that started it, with the code, rather than
38
+ * the sign-in page a signed-in person would bounce off). `identity.taken` is a link intent's only.
39
+ */
26
40
  export type SsoCallbackResult = {
27
41
  ok: true;
42
+ kind: "signin";
43
+ accountId: string;
44
+ returnTo: string;
45
+ } | {
46
+ ok: true;
47
+ kind: "linked";
28
48
  accountId: string;
29
49
  returnTo: string;
50
+ } | {
51
+ ok: true;
52
+ kind: "link_page";
53
+ ticket: string;
30
54
  } | {
31
55
  ok: false;
32
- error: SsoLoginError;
56
+ error: SsoLoginError | "identity.taken";
57
+ returnTo?: string;
33
58
  };
34
59
  /**
35
- * 第三方登录(`identity-source@1`):发起时生成 state(32 字节随机串,Redis `capk:sso-state:<state>` 10 分钟、
36
- * 单次有效,内含插件名、nonce、PKCE verifier、redirect_uri、回跳页面与浏览器绑定值的哈希),授权地址带 PKCE
37
- * challenge(S256);回调时先取后删 state、核对绑定 Cookie,再交给插件(连同 verifier)换取外部身份并解析到账号。
38
- * 会话由 controller 在成功后创建。状态全部在 Redis,没有进程内状态。
60
+ * Third-party sign-in (`identity-source@1`): the start makes a state (32 random bytes, Redis
61
+ * `capk:sso-state:<state>` for 10 minutes, single use, holding the plugin, nonce, PKCE verifier,
62
+ * redirect_uri, return page, intent, the start's session account and the hash of the browser
63
+ * binding value); the authorize URL carries the PKCE challenge (S256). The callback takes and
64
+ * deletes the state, checks the binding cookie, has the plugin (with the verifier) verify the
65
+ * external identity, then decides on its identity row (spec 2026-11-26-login-extensions §4): sign
66
+ * in, link, upgrade a `bind` row, self sign-up, or the link page ({@link SsoLinkTickets}). The
67
+ * controller creates the session. All state is in Redis, none in process.
39
68
  *
40
- * 已登录的用户也可以发起(「登录状态下绑定」):回调请求带着同一账号的 Web 会话时,经 IM 绑定链接建立的身份
41
- * 由此证明本人控制该外部身份,升级为可登录(Ruling A18,见 `ExternalIdentities.resolve`)。
69
+ * A signed-in person links an external account with `intent: link` (the linked accounts page):
70
+ * the same session at start and callback, linked to that account, never a new account or a
71
+ * switched session; it also upgrades the person's IM `bind` row (Ruling A18).
42
72
  */
43
73
  export declare class SsoFlow {
44
74
  private readonly redis;
45
75
  private readonly config;
46
76
  private readonly registry;
77
+ private readonly loginSources;
47
78
  private readonly external;
79
+ private readonly linkTickets;
48
80
  private readonly log;
49
- constructor(redis: Redis, config: Pick<KernelConfigService, "get">, registry: Pick<ExtensionRegistry, "list" | "deploymentConfig">, external: ExternalIdentities, log: Pick<Logger, "warn">);
50
- /** 已启用的登录方式:`auth.loginSources` 中(按其顺序)且已加载、提供 `identity-source@1` 的插件。 */
51
- sources(): {
81
+ constructor(redis: Redis, config: Pick<KernelConfigService, "get">, registry: Pick<ExtensionRegistry, "deploymentConfig">, loginSources: Pick<LoginSourcesService, "enabled">, external: ExternalIdentities, linkTickets: Pick<SsoLinkTickets, "create">, log: Pick<Logger, "warn">);
82
+ /**
83
+ * The login methods on offer: the enabled login sources whose extension is loaded and provides
84
+ * `identity-source@1`, in login page order (read from PG at each call).
85
+ */
86
+ sources(): Promise<{
52
87
  plugin: string;
53
88
  label: {
54
89
  zh: string;
55
90
  en: string;
56
91
  };
57
- }[];
58
- private provider;
92
+ }[]>;
93
+ /** The enabled login source of `plugin` when it is on offer (see {@link sources}). */
94
+ private entry;
95
+ /** The identity source of `plugin` when its login source is on offer (see {@link sources}). */
96
+ provider(plugin: string): Promise<IdentitySource | undefined>;
59
97
  private redirectUri;
60
98
  /** 绑定 Cookie 是否加 Secure:`auth.cookieSecure`,或 `http.publicUrl` 是 https(浏览器经 https 访问)。 */
61
99
  cookieSecure(): boolean;
62
100
  /** 网页地址:`http.publicUrl` + 站内路径(未配置 publicUrl 时为相对地址)。 */
63
101
  webUrl(path: string): string;
64
- /** 登录页并带原因码。 */
102
+ /** The sign-in page with a reason code. */
65
103
  loginError(code: SsoLoginError): string;
66
104
  /**
67
- * 发起登录,返回 302 目标:插件的授权地址;插件未启用、未配置 `http.publicUrl` 或插件出错 → 登录页 `sso.unavailable`。
68
- * `binding` 为本浏览器的绑定值(由 controller 写入 Cookie);`sessionAccountId` 为发起请求带着的 Web 会话账号。
105
+ * Starts a sign-in and returns the target to navigate to: the source's authorize URL. A sign-in's
106
+ * failure (source not on offer, no `http.publicUrl`, a plugin error: `sso.unavailable`) goes to
107
+ * the sign-in page; a link intent's back to its page with `?error=<code>`. A link intent needs
108
+ * the web session's account and must come from a CSRF-protected request (the controller's
109
+ * `POST …/start`; a cross-site top-level GET carries the Lax session cookie, so a GET start never
110
+ * links). `binding` is this browser's binding value (the controller writes the cookie).
69
111
  */
70
- start(plugin: string, returnTo: string | undefined, binding: string, sessionAccountId?: string): Promise<string>;
112
+ start(plugin: string, returnTo: string | undefined, binding: string, sessionAccountId?: string, intent?: SsoIntent): Promise<string>;
71
113
  /**
72
114
  * Handles the identity source's redirect back. The state is read and deleted in one step (it can
73
115
  * never be used again, whatever the outcome); a state that belongs to another plugin →
74
- * `sso.state_invalid`; a browser binding cookie that does not match → `sso.session_mismatch`.
75
- * Errors from the identity source map only to reason codes: a deliberate refusal
116
+ * `sso.state_invalid`; a browser binding cookie that does not match → `sso.session_mismatch`; a
117
+ * `link` intent whose callback does not carry the session its start carried →
118
+ * `sso.session_mismatch` (before the identity source runs: nothing is created or switched).
119
+ * The login source must still be on offer (`sso.unavailable` once a super admin switched it off
120
+ * mid-flow). Errors from the identity source map only to reason codes: a deliberate refusal
76
121
  * (`IdentitySourceRefused`) → `sso.account_not_allowed`, any other error → `sso.provider_error`.
77
122
  * The source key the plugin returns must be the one the kernel derives
78
- * (`${plugin}:${identity.tenantId}`, Ruling A19), otherwise it is refused as `sso.provider_error`.
79
- * An identity row created through an IM binding link, when the start and the callback were not
80
- * made by the same signed-in account → `sso.identity_not_verified` (Ruling A18). On success it
81
- * resolves to an account (without checking the account's status; the caller handles that).
82
- * `sessionAccountId`: the account of the web session the callback request already carries
83
- * (omitted when signed out).
123
+ * (`${plugin}:${identity.tenantId}`, Ruling A19), otherwise `sso.provider_error`. Then the
124
+ * decision of spec §4 ({@link decideSsoCallback}) is taken and applied under the identity lock
125
+ * (`ExternalIdentities.decideSignIn`); the link page's ticket is stored in Redis. Account status
126
+ * is not checked here (the caller refuses a disabled account).
127
+ * `sessionAccountId`: the account of the web session the callback request carries (omitted when
128
+ * signed out).
84
129
  */
85
130
  callback(plugin: string, query: Record<string, string>, binding: string | undefined, sessionAccountId?: string): Promise<SsoCallbackResult>;
86
131
  }
@@ -8,15 +8,18 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
11
- import { IDENTITY_SOURCE_EXTENSION_POINT, isIdentitySourceRefused, } from "@capybara-hq/plugin-sdk";
11
+ import { isIdentitySourceRefused } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { ApiError } from "../errors.js";
14
14
  import { ExtensionRegistry } from "../extensions/registry.js";
15
15
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
16
  import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
17
17
  import { isSafeReturnPath } from "../tools/oauth/flow-paths.js";
18
- import { ExternalIdentities, IdentityNotVerified } from "./external.js";
18
+ import { ExternalIdentities } from "./external.js";
19
+ import { LoginSourcesService } from "./login-sources.js";
20
+ import { SsoLinkTickets } from "./sso-link.js";
19
21
  import { SSO_PATH_PREFIX, ssoCallbackPath } from "./sso-paths.js";
22
+ export { decideSsoCallback, } from "./sso-decisions.js";
20
23
  /** state 的有效期(秒)。 */
21
24
  export const SSO_STATE_TTL_SECONDS = 600;
22
25
  /** 浏览器绑定 Cookie:回调必须来自发起登录的同一个浏览器(防登录 CSRF / 把回跳链接转给别人)。 */
@@ -42,46 +45,65 @@ function sameHash(a, b) {
42
45
  export function ssoBrowserBinding(existing) {
43
46
  return existing !== undefined && BINDING_RE.test(existing) ? existing : b64url();
44
47
  }
45
- /** 回跳页面:站内相对路径(以单个 `/` 开头,非 `//`),否则 `/`(防开放重定向)。 */
48
+ /** Appends `error=<code>` to a site path (a link intent's failure back on its page). */
49
+ export function withError(path, code) {
50
+ const hash = path.indexOf("#");
51
+ const base = hash < 0 ? path : path.slice(0, hash);
52
+ const frag = hash < 0 ? "" : path.slice(hash);
53
+ return `${base}${base.includes("?") ? "&" : "?"}error=${encodeURIComponent(code)}${frag}`;
54
+ }
55
+ /** The return page: a site-relative path (a single leading `/`, not `//`), else `/` (no open redirect). */
46
56
  export function safeReturnTo(p) {
47
57
  return p !== undefined && isSafeReturnPath(p) ? p : "/";
48
58
  }
49
59
  /**
50
- * 第三方登录(`identity-source@1`):发起时生成 state(32 字节随机串,Redis `capk:sso-state:<state>` 10 分钟、
51
- * 单次有效,内含插件名、nonce、PKCE verifier、redirect_uri、回跳页面与浏览器绑定值的哈希),授权地址带 PKCE
52
- * challenge(S256);回调时先取后删 state、核对绑定 Cookie,再交给插件(连同 verifier)换取外部身份并解析到账号。
53
- * 会话由 controller 在成功后创建。状态全部在 Redis,没有进程内状态。
60
+ * Third-party sign-in (`identity-source@1`): the start makes a state (32 random bytes, Redis
61
+ * `capk:sso-state:<state>` for 10 minutes, single use, holding the plugin, nonce, PKCE verifier,
62
+ * redirect_uri, return page, intent, the start's session account and the hash of the browser
63
+ * binding value); the authorize URL carries the PKCE challenge (S256). The callback takes and
64
+ * deletes the state, checks the binding cookie, has the plugin (with the verifier) verify the
65
+ * external identity, then decides on its identity row (spec 2026-11-26-login-extensions §4): sign
66
+ * in, link, upgrade a `bind` row, self sign-up, or the link page ({@link SsoLinkTickets}). The
67
+ * controller creates the session. All state is in Redis, none in process.
54
68
  *
55
- * 已登录的用户也可以发起(「登录状态下绑定」):回调请求带着同一账号的 Web 会话时,经 IM 绑定链接建立的身份
56
- * 由此证明本人控制该外部身份,升级为可登录(Ruling A18,见 `ExternalIdentities.resolve`)。
69
+ * A signed-in person links an external account with `intent: link` (the linked accounts page):
70
+ * the same session at start and callback, linked to that account, never a new account or a
71
+ * switched session; it also upgrades the person's IM `bind` row (Ruling A18).
57
72
  */
58
73
  let SsoFlow = class SsoFlow {
59
74
  redis;
60
75
  config;
61
76
  registry;
77
+ loginSources;
62
78
  external;
79
+ linkTickets;
63
80
  log;
64
- constructor(redis, config, registry, external, log) {
81
+ constructor(redis, config, registry, loginSources, external, linkTickets, log) {
65
82
  this.redis = redis;
66
83
  this.config = config;
67
84
  this.registry = registry;
85
+ this.loginSources = loginSources;
68
86
  this.external = external;
87
+ this.linkTickets = linkTickets;
69
88
  this.log = log;
70
89
  }
71
- /** 已启用的登录方式:`auth.loginSources` 中(按其顺序)且已加载、提供 `identity-source@1` 的插件。 */
72
- sources() {
73
- return this.config.get().auth.loginSources.flatMap((plugin) => {
74
- const src = this.provider(plugin);
75
- return src ? [{ plugin, label: { zh: src.label.zh, en: src.label.en } }] : [];
76
- });
90
+ /**
91
+ * The login methods on offer: the enabled login sources whose extension is loaded and provides
92
+ * `identity-source@1`, in login page order (read from PG at each call).
93
+ */
94
+ async sources() {
95
+ return (await this.loginSources.enabled()).map(({ plugin, source }) => ({
96
+ plugin,
97
+ label: { zh: source.label.zh, en: source.label.en },
98
+ }));
99
+ }
100
+ /** The enabled login source of `plugin` when it is on offer (see {@link sources}). */
101
+ async entry(plugin) {
102
+ return (await this.loginSources.enabled()).find((e) => e.plugin === plugin);
77
103
  }
78
- provider(plugin) {
79
- if (!this.config.get().auth.loginSources.includes(plugin))
80
- return undefined;
81
- const entry = this.registry
82
- .list("identity-source")
83
- .find((e) => e.plugin === plugin && e.capability === IDENTITY_SOURCE_EXTENSION_POINT);
84
- return entry?.impl;
104
+ /** The identity source of `plugin` when its login source is on offer (see {@link sources}). */
105
+ async provider(plugin) {
106
+ return (await this.entry(plugin))?.source;
85
107
  }
86
108
  redirectUri(plugin) {
87
109
  const base = (this.config.get().http.publicUrl ?? "").replace(/\/+$/, "");
@@ -97,18 +119,27 @@ let SsoFlow = class SsoFlow {
97
119
  const base = (this.config.get().http.publicUrl ?? "").replace(/\/+$/, "");
98
120
  return `${base}${path}`;
99
121
  }
100
- /** 登录页并带原因码。 */
122
+ /** The sign-in page with a reason code. */
101
123
  loginError(code) {
102
124
  return this.webUrl(`${LOGIN_PATH}?error=${encodeURIComponent(code)}`);
103
125
  }
104
126
  /**
105
- * 发起登录,返回 302 目标:插件的授权地址;插件未启用、未配置 `http.publicUrl` 或插件出错 → 登录页 `sso.unavailable`。
106
- * `binding` 为本浏览器的绑定值(由 controller 写入 Cookie);`sessionAccountId` 为发起请求带着的 Web 会话账号。
127
+ * Starts a sign-in and returns the target to navigate to: the source's authorize URL. A sign-in's
128
+ * failure (source not on offer, no `http.publicUrl`, a plugin error: `sso.unavailable`) goes to
129
+ * the sign-in page; a link intent's back to its page with `?error=<code>`. A link intent needs
130
+ * the web session's account and must come from a CSRF-protected request (the controller's
131
+ * `POST …/start`; a cross-site top-level GET carries the Lax session cookie, so a GET start never
132
+ * links). `binding` is this browser's binding value (the controller writes the cookie).
107
133
  */
108
- async start(plugin, returnTo, binding, sessionAccountId) {
109
- const src = this.provider(plugin);
134
+ async start(plugin, returnTo, binding, sessionAccountId, intent = "signin") {
135
+ const back = safeReturnTo(returnTo);
136
+ const fail = (code) => intent === "link" ? this.webUrl(withError(back, code)) : this.loginError(code);
137
+ if (intent === "link" && sessionAccountId === undefined) {
138
+ return this.loginError("sso.session_mismatch");
139
+ }
140
+ const src = await this.provider(plugin);
110
141
  if (!src || !this.config.get().http.publicUrl)
111
- return this.loginError("sso.unavailable");
142
+ return fail("sso.unavailable");
112
143
  const state = b64url();
113
144
  const nonce = b64url();
114
145
  const codeVerifier = b64url();
@@ -129,16 +160,17 @@ let SsoFlow = class SsoFlow {
129
160
  }
130
161
  catch (err) {
131
162
  this.log.warn("identity source authorizeUrl failed", { plugin, err });
132
- return this.loginError("sso.unavailable");
163
+ return fail("sso.unavailable");
133
164
  }
134
165
  const rec = {
135
166
  plugin,
136
167
  nonce,
137
168
  redirectUri,
138
- returnTo: safeReturnTo(returnTo),
169
+ returnTo: back,
139
170
  binding: sha256(binding),
140
171
  codeVerifier,
141
172
  ...(sessionAccountId !== undefined && { sessionAccountId }),
173
+ intent,
142
174
  };
143
175
  await this.redis.set(stateKey(state), JSON.stringify(rec), "EX", SSO_STATE_TTL_SECONDS);
144
176
  return url;
@@ -146,16 +178,19 @@ let SsoFlow = class SsoFlow {
146
178
  /**
147
179
  * Handles the identity source's redirect back. The state is read and deleted in one step (it can
148
180
  * never be used again, whatever the outcome); a state that belongs to another plugin →
149
- * `sso.state_invalid`; a browser binding cookie that does not match → `sso.session_mismatch`.
150
- * Errors from the identity source map only to reason codes: a deliberate refusal
181
+ * `sso.state_invalid`; a browser binding cookie that does not match → `sso.session_mismatch`; a
182
+ * `link` intent whose callback does not carry the session its start carried →
183
+ * `sso.session_mismatch` (before the identity source runs: nothing is created or switched).
184
+ * The login source must still be on offer (`sso.unavailable` once a super admin switched it off
185
+ * mid-flow). Errors from the identity source map only to reason codes: a deliberate refusal
151
186
  * (`IdentitySourceRefused`) → `sso.account_not_allowed`, any other error → `sso.provider_error`.
152
187
  * The source key the plugin returns must be the one the kernel derives
153
- * (`${plugin}:${identity.tenantId}`, Ruling A19), otherwise it is refused as `sso.provider_error`.
154
- * An identity row created through an IM binding link, when the start and the callback were not
155
- * made by the same signed-in account → `sso.identity_not_verified` (Ruling A18). On success it
156
- * resolves to an account (without checking the account's status; the caller handles that).
157
- * `sessionAccountId`: the account of the web session the callback request already carries
158
- * (omitted when signed out).
188
+ * (`${plugin}:${identity.tenantId}`, Ruling A19), otherwise `sso.provider_error`. Then the
189
+ * decision of spec §4 ({@link decideSsoCallback}) is taken and applied under the identity lock
190
+ * (`ExternalIdentities.decideSignIn`); the link page's ticket is stored in Redis. Account status
191
+ * is not checked here (the caller refuses a disabled account).
192
+ * `sessionAccountId`: the account of the web session the callback request carries (omitted when
193
+ * signed out).
159
194
  */
160
195
  async callback(plugin, query, binding, sessionAccountId) {
161
196
  const state = query.state;
@@ -170,18 +205,26 @@ let SsoFlow = class SsoFlow {
170
205
  if (binding === undefined || !sameHash(sha256(binding), rec.binding)) {
171
206
  return { ok: false, error: "sso.session_mismatch" };
172
207
  }
208
+ const intent = rec.intent;
209
+ if (intent === "link" &&
210
+ (rec.sessionAccountId === undefined || rec.sessionAccountId !== sessionAccountId)) {
211
+ return { ok: false, error: "sso.session_mismatch" };
212
+ }
213
+ // a link intent's failures go back to the page that started it
214
+ const fail = (error) => ({
215
+ ok: false,
216
+ error,
217
+ ...(intent === "link" && { returnTo: rec.returnTo }),
218
+ });
173
219
  if (query.error !== undefined) {
174
- return {
175
- ok: false,
176
- error: query.error === "access_denied" ? "sso.access_denied" : "sso.provider_error",
177
- };
220
+ return fail(query.error === "access_denied" ? "sso.access_denied" : "sso.provider_error");
178
221
  }
179
- const src = this.provider(plugin);
180
- if (!src)
181
- return { ok: false, error: "sso.unavailable" };
222
+ const entry = await this.entry(plugin);
223
+ if (!entry)
224
+ return fail("sso.unavailable");
182
225
  let identity;
183
226
  try {
184
- identity = await src.callback({
227
+ identity = await entry.source.callback({
185
228
  config: this.registry.deploymentConfig(plugin),
186
229
  redirectUri: rec.redirectUri,
187
230
  query,
@@ -197,43 +240,57 @@ let SsoFlow = class SsoFlow {
197
240
  plugin,
198
241
  reason: err.message,
199
242
  });
200
- return { ok: false, error: "sso.account_not_allowed" };
243
+ return fail("sso.account_not_allowed");
201
244
  }
202
245
  this.log.warn("identity source callback failed", { plugin, err });
203
- return { ok: false, error: "sso.provider_error" };
246
+ return fail("sso.provider_error");
204
247
  }
205
- // 身份源键由内核推导(Ruling A19):插件只能为自己、为它报出的租户声明身份
248
+ // the kernel derives the source key (Ruling A19): a plugin claims identities only for itself,
249
+ // for the tenant it reports
206
250
  if (typeof identity?.tenantId !== "string" ||
207
251
  identity.source !== `${plugin}:${identity.tenantId}`) {
208
252
  this.log.warn("identity source returned a source key that does not match its tenant", {
209
253
  plugin,
210
254
  });
211
- return { ok: false, error: "sso.provider_error" };
255
+ return fail("sso.provider_error");
212
256
  }
213
- // 升级 bind 身份:发起与回调时是同一个已登录账号才算本人在登录状态下证明了对该身份的控制
214
- const provedBy = rec.sessionAccountId !== undefined && rec.sessionAccountId === sessionAccountId
215
- ? sessionAccountId
216
- : undefined;
217
- let accountId;
257
+ let decided;
218
258
  try {
219
- // 只有登录路径允许按已验证邮箱合并(Ruling A9)
220
- accountId = (await this.external.resolve(identity, {
221
- allowMerge: true,
222
- linkedVia: "sso",
223
- login: provedBy === undefined ? {} : { sessionAccountId: provedBy },
224
- })).accountId;
259
+ decided = await this.external.decideSignIn(identity, {
260
+ intent,
261
+ ...(intent === "link" && sessionAccountId !== undefined && { sessionAccountId }),
262
+ signUp: entry.settings.signUp,
263
+ });
225
264
  }
226
265
  catch (err) {
227
- if (err instanceof IdentityNotVerified) {
228
- this.log.warn("sign-in with an unverified linked identity refused", { plugin });
229
- return { ok: false, error: "sso.identity_not_verified" };
230
- }
231
266
  if (!(err instanceof ApiError))
232
267
  throw err;
268
+ if (err.code === "identity.taken")
269
+ return fail("identity.taken");
233
270
  this.log.warn("external identity rejected", { plugin, err });
234
- return { ok: false, error: "sso.provider_error" };
271
+ return fail("sso.provider_error");
272
+ }
273
+ const d = decided.decision;
274
+ switch (d.kind) {
275
+ case "error":
276
+ return fail(d.code);
277
+ case "link_page": {
278
+ const ticket = await this.linkTickets.create({
279
+ plugin,
280
+ identity: decided.identity,
281
+ returnTo: rec.returnTo,
282
+ binding: rec.binding,
283
+ });
284
+ return { ok: true, kind: "link_page", ticket };
285
+ }
286
+ default:
287
+ return {
288
+ ok: true,
289
+ kind: intent === "link" ? "linked" : "signin",
290
+ accountId: d.accountId,
291
+ returnTo: rec.returnTo,
292
+ };
235
293
  }
236
- return { ok: true, accountId, returnTo: rec.returnTo };
237
294
  }
238
295
  };
239
296
  SsoFlow = __decorate([
@@ -241,7 +298,9 @@ SsoFlow = __decorate([
241
298
  __param(0, Inject(REDIS)),
242
299
  __param(1, Inject(KernelConfigService)),
243
300
  __param(2, Inject(ExtensionRegistry)),
244
- __param(3, Inject(ExternalIdentities)),
245
- __param(4, Inject(KERNEL_LOGGER))
301
+ __param(3, Inject(LoginSourcesService)),
302
+ __param(4, Inject(ExternalIdentities)),
303
+ __param(5, Inject(SsoLinkTickets)),
304
+ __param(6, Inject(KERNEL_LOGGER))
246
305
  ], SsoFlow);
247
306
  export { SsoFlow };
package/dist/index.d.ts CHANGED
@@ -54,6 +54,7 @@ export { type Account, AccountsModule, AccountsService } from "./identity/accoun
54
54
  export { type ApiTokenRecord, ApiTokenService } from "./identity/api-tokens.js";
55
55
  export { audit } from "./identity/audit.js";
56
56
  export { normalizeLogin, validatePassword } from "./identity/login.js";
57
+ export { LOGIN_SOURCES_SETTING, type LoginSourceSettings, LoginSourcesService, writeLoginSources, } from "./identity/login-sources.js";
57
58
  export { DUMMY_PASSWORD_HASH, hashPassword, verifyPassword } from "./identity/passwords.js";
58
59
  export { type IssuedSession, REFRESH_RACE_GRACE_MS, SessionService, } from "./identity/sessions.js";
59
60
  export { DEPLOYMENT_SETTINGS, type DeploymentSettings, SettingsService, } from "./identity/settings.js";
package/dist/index.js CHANGED
@@ -52,6 +52,7 @@ export { AccountsModule, AccountsService } from "./identity/accounts.js";
52
52
  export { ApiTokenService } from "./identity/api-tokens.js";
53
53
  export { audit } from "./identity/audit.js";
54
54
  export { normalizeLogin, validatePassword } from "./identity/login.js";
55
+ export { LOGIN_SOURCES_SETTING, LoginSourcesService, writeLoginSources, } from "./identity/login-sources.js";
55
56
  export { DUMMY_PASSWORD_HASH, hashPassword, verifyPassword } from "./identity/passwords.js";
56
57
  export { REFRESH_RACE_GRACE_MS, SessionService, } from "./identity/sessions.js";
57
58
  export { DEPLOYMENT_SETTINGS, SettingsService, } from "./identity/settings.js";
@@ -27,9 +27,6 @@ const HOT_APPLIERS = {
27
27
  "runtime.orgConcurrency": () => { },
28
28
  // Eval org concurrency is read the same way at every quota request.
29
29
  "evals.orgConcurrency": () => { },
30
- // Login methods and trusted identity sources are read on every request.
31
- "auth.loginSources": () => { },
32
- "auth.trustedIdentitySources": () => { },
33
30
  // The git gateway reads tools.git.enabled through the config service on every request.
34
31
  "tools.git.enabled": () => { },
35
32
  // The hook registry reads the time limit on every run.
@@ -23,7 +23,7 @@ export interface NamedThrottler {
23
23
  *
24
24
  * | route | names (reserved via `CredentialThrottler`) |
25
25
  * |---|---|
26
- * | `POST /api/v1/auth/login` | `login`, `login-ip`, `login-account` |
26
+ * | `POST /api/v1/auth/login`, `POST /api/v1/auth/sso/link` | `login`, `login-ip`, `login-account` |
27
27
  * | `PUT /api/v1/me/password` | `change-password`, `change-password-ip` |
28
28
  * | `POST /api/v1/setup` | `setup-token`, `setup-ip` |
29
29
  * | `POST /api/v1/invitations/:token/accept` | `invitation`, `invitation-ip` |
@@ -24,7 +24,7 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
24
24
  *
25
25
  * | route | names (reserved via `CredentialThrottler`) |
26
26
  * |---|---|
27
- * | `POST /api/v1/auth/login` | `login`, `login-ip`, `login-account` |
27
+ * | `POST /api/v1/auth/login`, `POST /api/v1/auth/sso/link` | `login`, `login-ip`, `login-account` |
28
28
  * | `PUT /api/v1/me/password` | `change-password`, `change-password-ip` |
29
29
  * | `POST /api/v1/setup` | `setup-token`, `setup-ip` |
30
30
  * | `POST /api/v1/invitations/:token/accept` | `invitation`, `invitation-ip` |
@@ -487,6 +487,21 @@ export const PLATFORM_EXCLUSIONS = [
487
487
  category: "secret",
488
488
  reason: "Completes an SSO login from the identity provider",
489
489
  },
490
+ {
491
+ route: "POST /api/v1/auth/sso/:plugin/start",
492
+ category: "human-only",
493
+ reason: "A person links their own external account: the browser goes on to the identity provider's sign-in",
494
+ },
495
+ {
496
+ route: "GET /api/v1/auth/sso/link",
497
+ category: "human-only",
498
+ reason: "A person's own sign-in with a password: the link page's view of a pending link",
499
+ },
500
+ {
501
+ route: "POST /api/v1/auth/sso/link",
502
+ category: "human-only",
503
+ reason: "A person's own sign-in with a password: completes a pending link and signs in",
504
+ },
490
505
  {
491
506
  route: "GET /api/v1/bind/:token",
492
507
  category: "human-only",
@@ -51,6 +51,10 @@ export const PLATFORM_DOMAINS = [
51
51
  id: "orgs",
52
52
  description: "This org (read, rename, members and invitations, its audit log) and, for the super admin, every org and its limits.",
53
53
  },
54
+ {
55
+ id: "login-sources",
56
+ description: "The login page's third-party sign-in methods (super admin): list, turn one on or off, what an unlinked external account does, trusted tenants, the order.",
57
+ },
54
58
  {
55
59
  id: "accounts",
56
60
  description: "Platform accounts (super admin): list, read, create, disable, enable.",
@@ -5,6 +5,7 @@ import { AdminOverviewService } from "../../admin/overview.service.js";
5
5
  import { AdminUsageService } from "../../admin/usage.service.js";
6
6
  import { ExtensionDisplayNames } from "../../extensions/display-name.js";
7
7
  import { ExtensionRegistry } from "../../extensions/registry.js";
8
+ import { LoginSourcesService } from "../../identity/login-sources.js";
8
9
  import { SettingsService } from "../../identity/settings.js";
9
10
  import { ModelEnablement } from "../../models/enablement.js";
10
11
  import { PricesService } from "../../models/prices.js";
@@ -32,7 +33,8 @@ export declare class AdminOperations implements OnModuleInit {
32
33
  private readonly overview;
33
34
  private readonly health;
34
35
  private readonly usage;
35
- constructor(registry: PlatformOperations, settings: SettingsService, providers: ProviderRegistry, displayNames: ExtensionDisplayNames, extensionRegistry: ExtensionRegistry, enablement: ModelEnablement, prices: PricesService, purposes: ModelPurposesService, themes: ThemesService, audit: AuditLogService, overview: AdminOverviewService, health: AdminHealthService, usage: AdminUsageService);
36
+ private readonly loginSources;
37
+ constructor(registry: PlatformOperations, settings: SettingsService, providers: ProviderRegistry, displayNames: ExtensionDisplayNames, extensionRegistry: ExtensionRegistry, enablement: ModelEnablement, prices: PricesService, purposes: ModelPurposesService, themes: ThemesService, audit: AuditLogService, overview: AdminOverviewService, health: AdminHealthService, usage: AdminUsageService, loginSources: LoginSourcesService);
36
38
  private assertProvider;
37
39
  onModuleInit(): void;
38
40
  }