@capybara-hq/kernel 0.1.0-rc.93 → 0.1.0-rc.95

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 +180 -30
  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
@@ -11,27 +11,18 @@ import { randomUUID } from "node:crypto";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { sql } from "kysely";
13
13
  import { ApiError } from "../errors.js";
14
- import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
14
  import { KernelDb } from "../infra/database/kernel-db.js";
16
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
17
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
17
  import { audit } from "./audit.js";
19
18
  import { ExternalIdentityLock } from "./external-identity-lock.js";
19
+ import { LoginSourcesService } from "./login-sources.js";
20
+ import { decideSsoCallback } from "./sso-decisions.js";
20
21
  /** `<插件名>:<租户 id>`;插件名同清单规则,租户 id 为非空、不含空白的串。 */
21
22
  const SOURCE_RE = /^([a-z0-9][a-z0-9._-]{0,213}):(\S{1,256})$/;
22
23
  const MAX_EXTERNAL_ID = 256;
23
24
  const MAX_DISPLAY_NAME = 200;
24
25
  const MAX_EMAIL = 320;
25
- /**
26
- * 第三方登录拒绝了这个身份(Ruling A18):身份行经 IM 绑定链接建立,而请求没有带着同一账号的会话。
27
- * 登录页原因码 `sso.identity_not_verified`。
28
- */
29
- export class IdentityNotVerified extends Error {
30
- constructor() {
31
- super("external identity is not verified for sign-in");
32
- this.name = "IdentityNotVerified";
33
- }
34
- }
35
26
  /** 身份源键里的插件名(`source` 中 `:` 之前的部分)。 */
36
27
  export function identityPlugin(source) {
37
28
  const i = source.indexOf(":");
@@ -73,21 +64,24 @@ const profileOf = (i) => JSON.stringify({
73
64
  ...(i.avatarUrl !== undefined && { avatarUrl: i.avatarUrl }),
74
65
  });
75
66
  /**
76
- * 外部身份:按 `(source, externalId)` 映射到账号(登录、渠道入站、通讯录共用同一个键)。
77
- * 首次出现时按「受信任的身份源 + 两侧邮箱均已验证」合并到既有账号,否则新建账号(不建组织)。
78
- * Concurrent first resolves of one identity are serialized by {@link ExternalIdentityLock},
79
- * so only one account is created.
67
+ * External identities: `(source, externalId)` maps to an account (sign-in, channel inbound and the
68
+ * directory share the key). A sign-in of an identity nobody has linked ({@link decideSignIn})
69
+ * merges into an existing account when its tenant is trusted and both emails are verified;
70
+ * otherwise it goes to the link page by default, and creates a new org-less account only when the
71
+ * login source's `signUp` is `create`. Directory sync creates the account for its identity
72
+ * ({@link resolve}). Concurrent first resolves of one identity are serialized by
73
+ * {@link ExternalIdentityLock}, so only one account is created.
80
74
  */
81
75
  let ExternalIdentities = class ExternalIdentities {
82
76
  db;
83
77
  txHost;
84
78
  identityLock;
85
- config;
86
- constructor(db, txHost, identityLock, config) {
79
+ loginSources;
80
+ constructor(db, txHost, identityLock, loginSources) {
87
81
  this.db = db;
88
82
  this.txHost = txHost;
89
83
  this.identityLock = identityLock;
90
- this.config = config;
84
+ this.loginSources = loginSources;
91
85
  }
92
86
  /** The account the external identity is linked to (in the context's transaction when there is one); undefined when unlinked. */
93
87
  async findAccount(source, externalId) {
@@ -100,17 +94,14 @@ let ExternalIdentities = class ExternalIdentities {
100
94
  return row?.account_id;
101
95
  }
102
96
  /**
103
- * 解析外部身份到账号。已绑定 → 该账号(顺带刷新身份行上的邮箱与资料);未绑定 → 合并或新建(见类说明),
104
- * 新身份行记 `linked_via = opts.linkedVia`(合并也是 `sso`)。
105
- * 合并只在 `opts.allowMerge` 时考虑(Ruling A9:只有第三方登录路径传 true;渠道入站、通讯录不传)。
106
- * 第三方登录(`opts.login`,Ruling A18 / A23):已有的身份行若经 IM 绑定建立(`bind`),只证明了某个网页登录者
107
- * 点过绑定链接,不证明他控制该外部身份——此时只有请求已带着**同一账号**的会话(本人在已登录状态下完成第三方登录,
108
- * 证明自己控制该身份)才放行,并把行升级为 `sso`(审计 `identity.verified`);否则抛 {@link IdentityNotVerified}。
109
- * 通讯录建立的行(`directory`)不论租户是否受信任都可直接登录:身份源登录本身就证明登录者控制该身份,
110
- * 而通讯录身份总是指向为它新建的账号(信任只影响合并与 `email_verified`)。旧行(`linked_via` 为 null)按 `sso` 处理。
111
- * 新建账号的 `email_verified` 只在身份源受信任且身份邮箱已验证时为 true——不受信任的身份源可以声称任意邮箱
112
- * 「已验证」,不能让它建出的账号成为日后受信任登录的合并目标。
113
- * 合并写审计 `identity.linked`,新建写 `account.created`。不判断账号状态,由调用方决定(如登录拒绝停用账号)。
97
+ * Resolves an external identity to an account: linked → that account (the row's email and
98
+ * profile are refreshed); unlinked → a new org-less account with this identity, the row
99
+ * recording `linked_via = opts.linkedVia`. It never merges by email and never checks a row for
100
+ * sign-in: the sign-in callback goes through {@link decideSignIn} (which calls this only for a
101
+ * self sign-up); directory sync calls it directly. A created account's `email_verified` is true
102
+ * only when the source is trusted and the identity's email is verified: an untrusted source can
103
+ * claim any email "verified", and its accounts must not become merge targets of a later trusted
104
+ * sign-in. A creation audits `account.created`. The account's status is not checked.
114
105
  * Joins the caller's transaction when there is one; takes the same lock as `link`, and falls back
115
106
  * to `ON CONFLICT DO NOTHING` plus a re-read, so it never throws a unique violation or aborts the
116
107
  * caller's transaction.
@@ -120,24 +111,9 @@ let ExternalIdentities = class ExternalIdentities {
120
111
  await this.lockIdentity(id);
121
112
  const existing = await this.findRow(id);
122
113
  if (existing !== undefined) {
123
- if (opts.login !== undefined)
124
- await this.allowLogin(id, existing, opts.login);
125
114
  await this.refreshIdentity(id);
126
115
  return { accountId: existing.accountId, created: false };
127
116
  }
128
- const merged = opts.allowMerge === true ? await this.mergeTarget(id) : undefined;
129
- if (merged !== undefined) {
130
- if (!(await this.insertIdentity(merged, id, "sso"))) {
131
- return { accountId: await this.mustFind(id), created: false };
132
- }
133
- await audit(this.db.db, {
134
- actorAccountId: merged,
135
- action: "identity.linked",
136
- target: merged,
137
- detail: { source: id.source, externalId: id.externalId, via: "verified_email" },
138
- });
139
- return { accountId: merged, created: false };
140
- }
141
117
  const accountId = randomUUID();
142
118
  await this.db
143
119
  .insertInto("accounts")
@@ -145,11 +121,11 @@ let ExternalIdentities = class ExternalIdentities {
145
121
  id: accountId,
146
122
  display_name: id.displayName,
147
123
  email: id.email ?? null,
148
- email_verified: id.emailVerified && this.trusted(id.source),
124
+ email_verified: id.emailVerified && (await this.trusted(id.source)),
149
125
  })
150
126
  .execute();
151
127
  if (!(await this.insertIdentity(accountId, id, opts.linkedVia))) {
152
- // 不走咨询锁的写入方抢先插入了同一身份:撤销刚建的账号,回读
128
+ // a writer that skipped the lock inserted the same identity first: undo the account, re-read
153
129
  await this.db.deleteFrom("accounts").where("id", "=", accountId).execute();
154
130
  return { accountId: await this.mustFind(id), created: false };
155
131
  }
@@ -161,13 +137,134 @@ let ExternalIdentities = class ExternalIdentities {
161
137
  });
162
138
  return { accountId, created: true };
163
139
  }
140
+ /**
141
+ * The sign-in callback's decision on a verified external identity (spec §4,
142
+ * {@link decideSsoCallback}), taken and applied in one transaction under the identity lock: the
143
+ * row and the merge target are read under the lock, then `signin` / `refresh` refresh the row,
144
+ * `upgrade` and `linked` go through {@link linkVerified}, `create` creates the account
145
+ * ({@link resolve}, no merge: the decision ruled it out). `link_page` and `error` write nothing.
146
+ * A link intent never creates an account. Returns the decision, whether an account was created
147
+ * and the normalized identity (what a link page stores). Throws `identity.taken` when a concurrent writer linked the
148
+ * identity to another account between the read and the write (cannot happen under the lock
149
+ * except for a writer that skips it).
150
+ */
151
+ async decideSignIn(identity, ctx) {
152
+ const id = normalize(identity);
153
+ await this.lockIdentity(id);
154
+ const row = await this.findRow(id);
155
+ // the merge target matters only to a sign-in of an unlinked identity (a link intent links to
156
+ // the session's account whatever the email says)
157
+ const mergeTarget = row === undefined && ctx.intent === "signin" ? await this.mergeTarget(id) : undefined;
158
+ const decision = decideSsoCallback({
159
+ intent: ctx.intent,
160
+ ...(ctx.sessionAccountId !== undefined && { sessionAccountId: ctx.sessionAccountId }),
161
+ ...(row !== undefined && { row }),
162
+ ...(mergeTarget !== undefined && { mergeTarget }),
163
+ signUp: ctx.signUp,
164
+ });
165
+ switch (decision.kind) {
166
+ case "create": {
167
+ const r = await this.resolve(id, { linkedVia: "sso" });
168
+ return {
169
+ decision: { kind: "signin", accountId: r.accountId },
170
+ identity: id,
171
+ created: r.created,
172
+ };
173
+ }
174
+ case "signin":
175
+ case "refresh":
176
+ await this.refreshIdentity(id);
177
+ break;
178
+ case "upgrade":
179
+ await this.linkVerified(decision.accountId, id, "oauth");
180
+ break;
181
+ case "linked":
182
+ // a disabled merge target gets no row: reported as its sign-in, which the caller refuses
183
+ // (auth.account_disabled) as it refuses any disabled account
184
+ if (decision.via === "verified_email" && !(await this.isActive(decision.accountId))) {
185
+ return {
186
+ decision: { kind: "signin", accountId: decision.accountId },
187
+ identity: id,
188
+ created: false,
189
+ };
190
+ }
191
+ await this.linkVerified(decision.accountId, id, decision.via);
192
+ break;
193
+ case "link_page":
194
+ case "error":
195
+ break;
196
+ }
197
+ return { decision, identity: id, created: false };
198
+ }
199
+ async isActive(accountId) {
200
+ const row = await this.db
201
+ .selectFrom("accounts")
202
+ .select("status")
203
+ .where("id", "=", accountId)
204
+ .executeTakeFirst();
205
+ return row?.status === "active";
206
+ }
207
+ /**
208
+ * Links an external identity whose control the person proved (a third-party sign-in, or the
209
+ * link page's password plus the sign-in) to `accountId` as `sso`: no row → a new `sso` row
210
+ * (audit `identity.linked` with `via`); a `bind` row of the same account → upgraded to `sso`
211
+ * (audit `identity.verified`); an `sso` / `directory` / legacy row of the same account → its
212
+ * profile refreshed; a row of another account → `409 identity.taken`. Under the identity lock,
213
+ * in the caller's transaction when there is one.
214
+ */
215
+ async linkVerified(accountId, identity, via) {
216
+ const id = normalize(identity);
217
+ await this.lockIdentity(id);
218
+ const row = await this.findRow(id);
219
+ if (row !== undefined && row.accountId !== accountId)
220
+ throw taken();
221
+ if (row !== undefined) {
222
+ await this.refreshIdentity(id);
223
+ if (row.linkedVia !== "bind")
224
+ return;
225
+ await this.db
226
+ .updateTable("identities")
227
+ .set({ linked_via: "sso" })
228
+ .where("source", "=", id.source)
229
+ .where("external_id", "=", id.externalId)
230
+ .execute();
231
+ await audit(this.db.db, {
232
+ actorAccountId: accountId,
233
+ action: "identity.verified",
234
+ target: accountId,
235
+ detail: { source: id.source, externalId: id.externalId, from: "bind", via },
236
+ });
237
+ return;
238
+ }
239
+ if (!(await this.insertIdentity(accountId, id, "sso"))) {
240
+ if ((await this.mustFind(id)) !== accountId)
241
+ throw taken();
242
+ return;
243
+ }
244
+ await audit(this.db.db, {
245
+ actorAccountId: accountId,
246
+ action: "identity.linked",
247
+ target: accountId,
248
+ detail: { source: id.source, externalId: id.externalId, via },
249
+ });
250
+ }
251
+ /**
252
+ * The account an identity row links to and how it was made, without a lock (the link page's
253
+ * read-only view; any write re-reads under the lock).
254
+ */
255
+ async peekRow(identity) {
256
+ return this.findRow(identity);
257
+ }
164
258
  /** Serializes resolve / link of one identity ({@link ExternalIdentityLock}). */
165
259
  async lockIdentity(id) {
166
260
  await this.identityLock.lock(id);
167
261
  }
168
- /** 身份源键(`<插件名>:<租户 id>`)是否在 `auth.trustedIdentitySources` 中:按完整键比较,信任按租户(Ruling A19)。 */
262
+ /**
263
+ * Whether the source key (`<plugin>:<tenant>`) is trusted: its tenant is among the login
264
+ * source's trusted tenants, full key match, trust is per tenant (Ruling A19).
265
+ */
169
266
  trusted(source) {
170
- return this.config.get().auth.trustedIdentitySources.includes(source);
267
+ return this.loginSources.isTrusted(source);
171
268
  }
172
269
  async findRow(id) {
173
270
  const row = await this.db
@@ -178,26 +275,6 @@ let ExternalIdentities = class ExternalIdentities {
178
275
  .executeTakeFirst();
179
276
  return row && { accountId: row.account_id, linkedVia: row.linked_via };
180
277
  }
181
- /** 第三方登录能否用这一行(见 {@link resolve}):只有 `bind` 行需要同一账号的会话,放行时把行改为 `sso`。 */
182
- async allowLogin(id, row, login) {
183
- const via = row.linkedVia ?? "sso";
184
- if (via !== "bind")
185
- return;
186
- if (login.sessionAccountId !== row.accountId)
187
- throw new IdentityNotVerified();
188
- await this.db
189
- .updateTable("identities")
190
- .set({ linked_via: "sso" })
191
- .where("source", "=", id.source)
192
- .where("external_id", "=", id.externalId)
193
- .execute();
194
- await audit(this.db.db, {
195
- actorAccountId: row.accountId,
196
- action: "identity.verified",
197
- target: row.accountId,
198
- detail: { source: id.source, externalId: id.externalId, from: via },
199
- });
200
- }
201
278
  async mustFind(id) {
202
279
  const owner = await this.findAccount(id.source, id.externalId);
203
280
  if (owner === undefined)
@@ -218,12 +295,14 @@ let ExternalIdentities = class ExternalIdentities {
218
295
  .execute();
219
296
  }
220
297
  /**
221
- * 可合并的既有账号:身份源键在 `auth.trustedIdentitySources` 中、身份邮箱已验证,
222
- * 且恰好有一个邮箱已验证、邮箱相同(不区分大小写)的账号;否则 undefined(多个候选时不猜,新建)。
298
+ * The existing account to merge into: the source key is trusted (a trusted tenant of its login
299
+ * source), the identity's email is verified, and exactly one account has the same verified email
300
+ * (case-insensitive); else undefined (with several candidates it never guesses).
223
301
  */
224
302
  async mergeTarget(id) {
225
- if (!id.emailVerified || id.email === undefined || !this.trusted(id.source))
303
+ if (!id.emailVerified || id.email === undefined || !(await this.trusted(id.source))) {
226
304
  return undefined;
305
+ }
227
306
  const rows = await this.db
228
307
  .selectFrom("accounts")
229
308
  .select("id")
@@ -363,6 +442,12 @@ let ExternalIdentities = class ExternalIdentities {
363
442
  __decorate([
364
443
  Transactional()
365
444
  ], ExternalIdentities.prototype, "resolve", null);
445
+ __decorate([
446
+ Transactional()
447
+ ], ExternalIdentities.prototype, "decideSignIn", null);
448
+ __decorate([
449
+ Transactional()
450
+ ], ExternalIdentities.prototype, "linkVerified", null);
366
451
  __decorate([
367
452
  Transactional()
368
453
  ], ExternalIdentities.prototype, "link", null);
@@ -374,7 +459,7 @@ ExternalIdentities = __decorate([
374
459
  __param(0, Inject(KernelDb)),
375
460
  __param(1, Inject(TransactionHost)),
376
461
  __param(2, Inject(ExternalIdentityLock)),
377
- __param(3, Inject(KernelConfigService))
462
+ __param(3, Inject(LoginSourcesService))
378
463
  ], ExternalIdentities);
379
464
  export { ExternalIdentities };
380
465
  const taken = () => new ApiError("identity.taken", "This external identity is already linked to another account");
@@ -18,9 +18,12 @@ import { IdentityBinding } from "./binding.js";
18
18
  import { ExternalIdentities } from "./external.js";
19
19
  import { ExternalIdentityLock } from "./external-identity-lock.js";
20
20
  import { InitialPasswords } from "./initial-passwords.js";
21
+ import { LinkedAccountsService } from "./linked-accounts.js";
22
+ import { LoginSourcesService } from "./login-sources.js";
21
23
  import { SessionService } from "./sessions.js";
22
24
  import { SettingsService } from "./settings.js";
23
25
  import { SsoFlow } from "./sso.js";
26
+ import { SsoLinkTickets } from "./sso-link.js";
24
27
  import { SuperAdminLockModule } from "./super-admin.js";
25
28
  /**
26
29
  * Identity: accounts, sessions, API tokens, deployment settings and the super admin lock,
@@ -46,9 +49,12 @@ IdentityModule = __decorate([
46
49
  ApiTokenService,
47
50
  SettingsService,
48
51
  ExternalIdentityLock,
52
+ LoginSourcesService,
49
53
  ExternalIdentities,
54
+ LinkedAccountsService,
50
55
  IdentityBinding,
51
56
  SsoFlow,
57
+ SsoLinkTickets,
52
58
  InitialPasswords,
53
59
  AppAuthService,
54
60
  ],
@@ -59,9 +65,12 @@ IdentityModule = __decorate([
59
65
  ApiTokenService,
60
66
  SettingsService,
61
67
  SuperAdminLockModule,
68
+ LoginSourcesService,
62
69
  ExternalIdentities,
70
+ LinkedAccountsService,
63
71
  IdentityBinding,
64
72
  SsoFlow,
73
+ SsoLinkTickets,
65
74
  InitialPasswords,
66
75
  AppAuthService,
67
76
  ],
@@ -0,0 +1,42 @@
1
+ import { type LocalizedName } from "@capybara-hq/plugin-sdk";
2
+ import { ExtensionRegistry } from "../extensions/registry.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { ExternalIdentities, type LinkedIdentity } from "./external.js";
5
+ import { LoginSourcesService } from "./login-sources.js";
6
+ /**
7
+ * What an identity can sign in with (linked accounts page, login extensions spec §6):
8
+ * `unsupported`: its plugin provides no `identity-source@1`; `off`: the login page does not offer
9
+ * that source; `needs_link`: offered, but the row came from an IM bind link (a link intent upgrades
10
+ * it); `on`: offered and the row signs in.
11
+ */
12
+ export type IdentityLogin = "unsupported" | "off" | "needs_link" | "on";
13
+ /** One row of `GET /api/v1/me/identities`. */
14
+ export interface LinkedAccountRow extends LinkedIdentity {
15
+ /** The platform's name: the identity source's label, else the plugin's display name or name. */
16
+ label: LocalizedName;
17
+ /** Its plugin provides `channel@1` (loaded): the identity can talk to agents in IM. */
18
+ channel: boolean;
19
+ login: IdentityLogin;
20
+ }
21
+ /** A login method the account can link (an enabled source it has no identity of). */
22
+ export interface LinkableMethod {
23
+ plugin: string;
24
+ label: LocalizedName;
25
+ }
26
+ /**
27
+ * The linked accounts page's read (`GET /api/v1/me/identities`): the person's identities with
28
+ * their IM and sign-in capabilities, and the enabled login methods they have no identity of, so
29
+ * the page decides nothing itself. Computed at each read from the registry and the login sources
30
+ * setting (never cached in process).
31
+ */
32
+ export declare class LinkedAccountsService {
33
+ private readonly db;
34
+ private readonly external;
35
+ private readonly loginSources;
36
+ private readonly registry;
37
+ constructor(db: KernelDb, external: Pick<ExternalIdentities, "listForAccount">, loginSources: Pick<LoginSourcesService, "enabled" | "providesIdentitySource">, registry: Pick<ExtensionRegistry, "list">);
38
+ list(accountId: string): Promise<{
39
+ identities: LinkedAccountRow[];
40
+ linkable: LinkableMethod[];
41
+ }>;
42
+ }
@@ -0,0 +1,78 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { CHANNEL_EXTENSION_POINT, IDENTITY_SOURCE_EXTENSION_POINT, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { ExtensionRegistry } from "../extensions/registry.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { pluginDisplayNames } from "../tools/display-names.js";
15
+ import { ExternalIdentities, identityPlugin } from "./external.js";
16
+ import { LoginSourcesService } from "./login-sources.js";
17
+ /**
18
+ * The linked accounts page's read (`GET /api/v1/me/identities`): the person's identities with
19
+ * their IM and sign-in capabilities, and the enabled login methods they have no identity of, so
20
+ * the page decides nothing itself. Computed at each read from the registry and the login sources
21
+ * setting (never cached in process).
22
+ */
23
+ let LinkedAccountsService = class LinkedAccountsService {
24
+ db;
25
+ external;
26
+ loginSources;
27
+ registry;
28
+ constructor(db, external, loginSources, registry) {
29
+ this.db = db;
30
+ this.external = external;
31
+ this.loginSources = loginSources;
32
+ this.registry = registry;
33
+ }
34
+ async list(accountId) {
35
+ const rows = await this.external.listForAccount(accountId);
36
+ const enabled = new Map((await this.loginSources.enabled()).map((e) => [e.plugin, e.source.label]));
37
+ const sources = new Map(this.registry
38
+ .list("identity-source")
39
+ .filter((e) => e.capability === IDENTITY_SOURCE_EXTENSION_POINT)
40
+ .map((e) => [e.plugin, e.impl.label]));
41
+ const channels = new Set(this.registry
42
+ .list("channel")
43
+ .filter((e) => e.capability === CHANNEL_EXTENSION_POINT)
44
+ .map((e) => e.plugin));
45
+ const plugins = [...new Set(rows.map((r) => identityPlugin(r.source)))];
46
+ const provides = new Map(await Promise.all(plugins.map(async (p) => [p, await this.loginSources.providesIdentitySource(p)])));
47
+ const names = await pluginDisplayNames(this.db.db, plugins.filter((p) => !sources.has(p)));
48
+ const identities = rows.map((r) => {
49
+ const plugin = identityPlugin(r.source);
50
+ const label = sources.get(plugin) ?? names.get(plugin) ?? { zh: plugin, en: plugin };
51
+ let login;
52
+ if (provides.get(plugin) !== true)
53
+ login = "unsupported";
54
+ else if (!enabled.has(plugin))
55
+ login = "off";
56
+ else
57
+ login = r.linkedVia === "bind" ? "needs_link" : "on";
58
+ return {
59
+ ...r,
60
+ label: { zh: label.zh, en: label.en },
61
+ channel: channels.has(plugin),
62
+ login,
63
+ };
64
+ });
65
+ const linkable = [...enabled]
66
+ .filter(([plugin]) => !plugins.includes(plugin))
67
+ .map(([plugin, label]) => ({ plugin, label: { zh: label.zh, en: label.en } }));
68
+ return { identities, linkable };
69
+ }
70
+ };
71
+ LinkedAccountsService = __decorate([
72
+ Injectable(),
73
+ __param(0, Inject(KernelDb)),
74
+ __param(1, Inject(ExternalIdentities)),
75
+ __param(2, Inject(LoginSourcesService)),
76
+ __param(3, Inject(ExtensionRegistry))
77
+ ], LinkedAccountsService);
78
+ export { LinkedAccountsService };
@@ -0,0 +1,160 @@
1
+ import { type IdentitySource, type IdentitySourceTenant } from "@capybara-hq/plugin-sdk";
2
+ import { z } from "zod";
3
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
4
+ import { ExtensionRegistry } from "../extensions/registry.js";
5
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
6
+ import { KernelDb } from "../infra/database/kernel-db.js";
7
+ import { TransactionHost } from "../infra/database/transaction-host.js";
8
+ import type { KernelLogger } from "../log.js";
9
+ /** The `deployment_settings` key of the login sources (login extensions spec §1). */
10
+ export declare const LOGIN_SOURCES_SETTING = "loginSources";
11
+ /** At most this many trusted tenants per source. */
12
+ export declare const MAX_TRUSTED_TENANTS = 50;
13
+ /** A tenant id is the `<tenant>` of a source key: non-empty, no whitespace, at most 256 chars. */
14
+ export declare const TENANT_MAX = 256;
15
+ declare const LoginSourceSettingsSchema: z.ZodObject<{
16
+ plugin: z.ZodString;
17
+ enabled: z.ZodBoolean;
18
+ signUp: z.ZodEnum<{
19
+ create: "create";
20
+ link: "link";
21
+ }>;
22
+ trustedTenants: z.ZodArray<z.ZodString>;
23
+ }, z.core.$strip>;
24
+ /**
25
+ * One login source: an extension providing `identity-source@1`, whether the login page offers
26
+ * it, what happens to an unlinked external account, and the tenants trusted for email merge.
27
+ */
28
+ export type LoginSourceSettings = z.infer<typeof LoginSourceSettingsSchema>;
29
+ /** The patch {@link LoginSourcesService.update} takes (an absent or undefined field keeps its value). */
30
+ export type LoginSourcePatch = {
31
+ [K in Exclude<keyof LoginSourceSettings, "plugin">]?: LoginSourceSettings[K] | undefined;
32
+ };
33
+ /**
34
+ * How a write was made, for its audit row: the personal access token, and extra detail (a
35
+ * Platform operation's `via: "agent"`).
36
+ */
37
+ export interface AuditVia {
38
+ actorTokenId?: string;
39
+ detail?: Record<string, unknown>;
40
+ }
41
+ /** An enabled login source whose extension is loaded and provides the point. */
42
+ export interface EnabledLoginSource {
43
+ plugin: string;
44
+ source: IdentitySource;
45
+ settings: LoginSourceSettings;
46
+ }
47
+ /**
48
+ * One row of the admin overview (`GET /api/v1/admin/login-sources`): the stored settings (the
49
+ * defaults when none are stored) with what the loaded extension declares and its state.
50
+ */
51
+ export interface LoginSourceView extends LoginSourceSettings {
52
+ /** The source's label; the plugin name for an entry whose extension is not loaded. */
53
+ label: {
54
+ zh: string;
55
+ en: string;
56
+ };
57
+ /** The source's tenant declaration (absent when it declares none or is not loaded). */
58
+ tenant?: IdentitySourceTenant;
59
+ /** Loaded and providing `identity-source@1`. */
60
+ available: boolean;
61
+ /** Its deployment config is invalid: turning it on is refused (`login_sources.needs_config`). */
62
+ needsConfig: boolean;
63
+ /** The redirect URI to register at the identity provider; null while `http.publicUrl` is unset. */
64
+ callbackUrl: string | null;
65
+ }
66
+ /**
67
+ * Parses a stored value: missing → `[]`; invalid → `[]` with a warning (the login page then
68
+ * offers nothing and nothing is trusted; the next write replaces the row).
69
+ */
70
+ export declare function parseLoginSources(value: unknown, log?: Pick<KernelLogger, "warn">): LoginSourceSettings[];
71
+ /**
72
+ * Writes the whole list (upsert by key) through `db`; `actorAccountId` is recorded as the row's
73
+ * `updated_by`. No checks beyond the schema: {@link LoginSourcesService} checks before it writes,
74
+ * and test seeds write through here directly.
75
+ */
76
+ export declare function writeLoginSources(db: KernelSchemaDb, list: LoginSourceSettings[], actorAccountId: string | null): Promise<void>;
77
+ /**
78
+ * The login sources (login extensions spec §1): one `deployment_settings` row, key
79
+ * `loginSources`, an array of {@link LoginSourceSettings} whose order is the login page order.
80
+ * Read from PG at every call, never cached in process (every replica sees a change at once).
81
+ * An entry whose extension is not loaded or no longer provides `identity-source@1` is kept but
82
+ * not offered. Writes lock the row, run in one transaction and audit `login_sources.updated`.
83
+ */
84
+ export declare class LoginSourcesService {
85
+ private readonly db;
86
+ readonly txHost: TransactionHost;
87
+ private readonly registry;
88
+ private readonly config;
89
+ private readonly log;
90
+ constructor(db: KernelDb, txHost: TransactionHost, registry: Pick<ExtensionRegistry, "list" | "current" | "declared">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">);
91
+ /** Every stored entry, in stored order (in the caller's transaction when there is one). */
92
+ list(): Promise<LoginSourceSettings[]>;
93
+ /**
94
+ * The entries the login page offers, in order: enabled, loaded, providing the point and with a
95
+ * complete deployment config (the page never offers a button that fails).
96
+ */
97
+ enabled(): Promise<EnabledLoginSource[]>;
98
+ get(plugin: string): Promise<LoginSourceSettings | undefined>;
99
+ /**
100
+ * Whether the source key `<plugin>:<tenant>` is trusted: the tenant is in that plugin's
101
+ * `trustedTenants` (full key match, trust is per tenant, Ruling A19), the plugin is loaded as an
102
+ * identity source and the tenant passes its current tenant declaration (a tenant stored while
103
+ * the extension was away, or before an upgrade added `neverTrusted` or tightened `pattern`, is
104
+ * not trusted). Independent of `enabled`: directory sync reads it for `email_verified` whether
105
+ * or not the login page offers the source.
106
+ */
107
+ isTrusted(sourceKey: string): Promise<boolean>;
108
+ /**
109
+ * Changes one entry (created with the defaults when missing). `login_sources.unknown_plugin`
110
+ * when the extension is neither loaded as an identity source nor stored; trusted tenants are
111
+ * trimmed, de-duplicated and checked against the source's tenant declaration (only blanks are
112
+ * refused while it is not loaded); turning it on while its deployment config is invalid →
113
+ * `login_sources.needs_config`, and puts it after the last enabled entry.
114
+ */
115
+ update(plugin: string, patch: LoginSourcePatch, actorAccountId: string, via?: AuditVia): Promise<LoginSourceSettings>;
116
+ /**
117
+ * Sets the login page order: `plugins` must name every enabled stored entry exactly once
118
+ * (available or not); the disabled entries follow in their stored order.
119
+ */
120
+ reorder(plugins: string[], actorAccountId: string, via?: AuditVia): Promise<LoginSourceSettings[]>;
121
+ /**
122
+ * The admin overview: every loaded identity source and every stored entry, the enabled ones
123
+ * first in login page order, then the rest by plugin name.
124
+ */
125
+ overview(): Promise<LoginSourceView[]>;
126
+ /** One row of {@link overview} (in the caller's transaction when there is one). */
127
+ view(plugin: string): Promise<LoginSourceView>;
128
+ private viewOf;
129
+ /**
130
+ * Whether `plugin` provides `identity-source@1`: loaded as one, or (not loaded) its install
131
+ * record's package declares it. A config-declared extension that is not loaded reads false
132
+ * (its manifest is not in PG).
133
+ */
134
+ providesIdentitySource(plugin: string): Promise<boolean>;
135
+ /** The stored list with its row locked FOR UPDATE (created as `[]` first): writes serialize. */
136
+ private lockedList;
137
+ /** The loaded `identity-source@1` implementation of `plugin` (live from the registry). */
138
+ private loadedSource;
139
+ private checkTenants;
140
+ /**
141
+ * Whether the loaded extension's running config leaves a required overridable field empty: the
142
+ * host loads with those fields optional, so that is the only way the full schema can refuse it
143
+ * (as in `EffectiveConfigs.get`).
144
+ */
145
+ private loadedConfigIncomplete;
146
+ /**
147
+ * Whether an identity source's deployment config is invalid: loaded as one, see
148
+ * {@link loadedConfigIncomplete}; loaded but not an identity source, false (the caller answers
149
+ * unknown_plugin); not loaded, {@link pendingConfigIdentitySource}.
150
+ */
151
+ private needsConfig;
152
+ /**
153
+ * Whether a live replica reports `plugin` pending configuration for the version the deployment
154
+ * wants: an install record's package (its row's sha256 matches the install target, and the
155
+ * package's static manifest provides `identity-source@1`), or a config-declared extension (the
156
+ * startup config names it; its manifest is not in PG, so the point is not checked).
157
+ */
158
+ private pendingConfigIdentitySource;
159
+ }
160
+ export {};