@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.
- package/bootstrap.json +3 -3
- package/dist/admin/login-sources.controller.d.ts +30 -0
- package/dist/admin/login-sources.controller.js +77 -0
- package/dist/admin/login-sources.schemas.d.ts +25 -0
- package/dist/admin/login-sources.schemas.js +49 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +0 -2
- package/dist/config/schema.js +0 -28
- package/dist/ctx/create-ctx.d.ts +5 -1
- package/dist/ctx/create-ctx.js +13 -2
- package/dist/device-access/device-access.service.d.ts +27 -4
- package/dist/device-access/device-access.service.js +180 -30
- package/dist/errors.d.ts +10 -0
- package/dist/errors.js +10 -0
- package/dist/extensions/instance.js +3 -1
- package/dist/http/api.module.js +2 -0
- package/dist/identity/auth.controller.d.ts +2 -0
- package/dist/identity/auth.controller.js +1 -1
- package/dist/identity/external.d.ts +78 -40
- package/dist/identity/external.js +157 -72
- package/dist/identity/identity.module.js +9 -0
- package/dist/identity/linked-accounts.d.ts +42 -0
- package/dist/identity/linked-accounts.js +78 -0
- package/dist/identity/login-sources.d.ts +160 -0
- package/dist/identity/login-sources.js +403 -0
- package/dist/identity/sso-decisions.d.ts +75 -0
- package/dist/identity/sso-decisions.js +42 -0
- package/dist/identity/sso-link.d.ts +61 -0
- package/dist/identity/sso-link.js +157 -0
- package/dist/identity/sso.controller.d.ts +98 -14
- package/dist/identity/sso.controller.js +222 -28
- package/dist/identity/sso.d.ts +75 -30
- package/dist/identity/sso.js +129 -70
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/infra/config/kernel-config.service.js +0 -3
- package/dist/infra/throttler/named-throttlers.d.ts +1 -1
- package/dist/infra/throttler/named-throttlers.js +1 -1
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/operation.js +4 -0
- package/dist/platform/ops/admin.ops.d.ts +3 -1
- package/dist/platform/ops/admin.ops.js +106 -2
- package/dist/platform/ops/extensions-admin.ops.d.ts +24 -2
- package/dist/platform/ops/extensions-admin.ops.js +54 -6
- package/dist/platform/route-schemas.js +2 -0
- package/dist/tools/builtins/sandbox/glob.js +7 -4
- package/dist/tools/builtins/sandbox/grep.d.ts +8 -1
- package/dist/tools/builtins/sandbox/grep.js +27 -33
- package/dist/tools/builtins/sandbox/search-command.d.ts +43 -0
- package/dist/tools/builtins/sandbox/search-command.js +86 -0
- package/dist/tools/call-scope.d.ts +19 -6
- package/dist/tools/call-scope.js +29 -0
- package/dist/tools/pipeline.d.ts +3 -2
- package/dist/tools/pipeline.js +29 -10
- package/dist/tools/questions.service.d.ts +2 -2
- package/dist/tools/questions.service.js +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,403 @@
|
|
|
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 { IDENTITY_SOURCE_EXTENSION_POINT, validateTenantId, } from "@capybara-hq/plugin-sdk";
|
|
11
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { z } from "zod";
|
|
14
|
+
import { ApiError } from "../errors.js";
|
|
15
|
+
import { STALE_RECONCILE_PERIODS } from "../extensions/lifecycle-topics.js";
|
|
16
|
+
import { missingOverridable } from "../extensions/org-levels.js";
|
|
17
|
+
import { ExtensionRegistry } from "../extensions/registry.js";
|
|
18
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
19
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
20
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
21
|
+
import { Transactional } from "../infra/database/transactional.decorator.js";
|
|
22
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
23
|
+
import { audit } from "./audit.js";
|
|
24
|
+
import { ssoCallbackPath } from "./sso-paths.js";
|
|
25
|
+
/** The `deployment_settings` key of the login sources (login extensions spec §1). */
|
|
26
|
+
export const LOGIN_SOURCES_SETTING = "loginSources";
|
|
27
|
+
/** At most this many trusted tenants per source. */
|
|
28
|
+
export const MAX_TRUSTED_TENANTS = 50;
|
|
29
|
+
/** A tenant id is the `<tenant>` of a source key: non-empty, no whitespace, at most 256 chars. */
|
|
30
|
+
export const TENANT_MAX = 256;
|
|
31
|
+
const LoginSourceSettingsSchema = z.object({
|
|
32
|
+
plugin: z.string().min(1).max(214),
|
|
33
|
+
enabled: z.boolean(),
|
|
34
|
+
signUp: z.enum(["link", "create"]),
|
|
35
|
+
trustedTenants: z.array(z.string().min(1).max(TENANT_MAX)).max(MAX_TRUSTED_TENANTS),
|
|
36
|
+
});
|
|
37
|
+
const LoginSourcesValue = z
|
|
38
|
+
.array(LoginSourceSettingsSchema)
|
|
39
|
+
.refine((list) => new Set(list.map((e) => e.plugin)).size === list.length, {
|
|
40
|
+
message: "each plugin appears once",
|
|
41
|
+
});
|
|
42
|
+
/** A new entry: off, unlinked accounts go to the link page, nothing trusted. */
|
|
43
|
+
const defaults = (plugin) => ({
|
|
44
|
+
plugin,
|
|
45
|
+
enabled: false,
|
|
46
|
+
signUp: "link",
|
|
47
|
+
trustedTenants: [],
|
|
48
|
+
});
|
|
49
|
+
/**
|
|
50
|
+
* Parses a stored value: missing → `[]`; invalid → `[]` with a warning (the login page then
|
|
51
|
+
* offers nothing and nothing is trusted; the next write replaces the row).
|
|
52
|
+
*/
|
|
53
|
+
export function parseLoginSources(value, log) {
|
|
54
|
+
if (value === undefined)
|
|
55
|
+
return [];
|
|
56
|
+
const parsed = LoginSourcesValue.safeParse(value);
|
|
57
|
+
if (parsed.success)
|
|
58
|
+
return parsed.data;
|
|
59
|
+
log?.warn("invalid deployment setting; it reads as no login sources", {
|
|
60
|
+
key: LOGIN_SOURCES_SETTING,
|
|
61
|
+
});
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Enabled entries first (in their order), then the disabled ones (in theirs): the login page
|
|
66
|
+
* order is the order of the enabled entries.
|
|
67
|
+
*/
|
|
68
|
+
function enabledFirst(list) {
|
|
69
|
+
return [...list.filter((e) => e.enabled), ...list.filter((e) => !e.enabled)];
|
|
70
|
+
}
|
|
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 async function writeLoginSources(db, list, actorAccountId) {
|
|
77
|
+
const json = JSON.stringify(LoginSourcesValue.parse(list));
|
|
78
|
+
await db
|
|
79
|
+
.insertInto("deployment_settings")
|
|
80
|
+
.values({ key: LOGIN_SOURCES_SETTING, value: json, updated_by: actorAccountId })
|
|
81
|
+
.onConflict((oc) => oc
|
|
82
|
+
.column("key")
|
|
83
|
+
.doUpdateSet({ value: json, updated_by: actorAccountId, updated_at: sql `now()` }))
|
|
84
|
+
.execute();
|
|
85
|
+
}
|
|
86
|
+
const invalidTenant = (plugin, tenant, reason) => new ApiError("login_sources.invalid_tenant", `Trusted tenant "${tenant}" of ${plugin} is not valid: ${reason}`, [{ path: "trustedTenants", message: reason }]);
|
|
87
|
+
const TENANT_REASONS = {
|
|
88
|
+
empty: "a tenant id cannot be blank",
|
|
89
|
+
pattern: "it does not match the tenant format this source declares",
|
|
90
|
+
never_trusted: "this source declares that this tenant may never be trusted",
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* The login sources (login extensions spec §1): one `deployment_settings` row, key
|
|
94
|
+
* `loginSources`, an array of {@link LoginSourceSettings} whose order is the login page order.
|
|
95
|
+
* Read from PG at every call, never cached in process (every replica sees a change at once).
|
|
96
|
+
* An entry whose extension is not loaded or no longer provides `identity-source@1` is kept but
|
|
97
|
+
* not offered. Writes lock the row, run in one transaction and audit `login_sources.updated`.
|
|
98
|
+
*/
|
|
99
|
+
let LoginSourcesService = class LoginSourcesService {
|
|
100
|
+
db;
|
|
101
|
+
txHost;
|
|
102
|
+
registry;
|
|
103
|
+
config;
|
|
104
|
+
log;
|
|
105
|
+
constructor(db, txHost, registry, config, log) {
|
|
106
|
+
this.db = db;
|
|
107
|
+
this.txHost = txHost;
|
|
108
|
+
this.registry = registry;
|
|
109
|
+
this.config = config;
|
|
110
|
+
this.log = log;
|
|
111
|
+
}
|
|
112
|
+
/** Every stored entry, in stored order (in the caller's transaction when there is one). */
|
|
113
|
+
async list() {
|
|
114
|
+
const row = await this.db
|
|
115
|
+
.selectFrom("deployment_settings")
|
|
116
|
+
.select("value")
|
|
117
|
+
.where("key", "=", LOGIN_SOURCES_SETTING)
|
|
118
|
+
.executeTakeFirst();
|
|
119
|
+
return parseLoginSources(row?.value, this.log);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* The entries the login page offers, in order: enabled, loaded, providing the point and with a
|
|
123
|
+
* complete deployment config (the page never offers a button that fails).
|
|
124
|
+
*/
|
|
125
|
+
async enabled() {
|
|
126
|
+
return (await this.list()).flatMap((settings) => {
|
|
127
|
+
if (!settings.enabled)
|
|
128
|
+
return [];
|
|
129
|
+
const source = this.loadedSource(settings.plugin);
|
|
130
|
+
if (!source || this.loadedConfigIncomplete(settings.plugin))
|
|
131
|
+
return [];
|
|
132
|
+
return [{ plugin: settings.plugin, source, settings }];
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
async get(plugin) {
|
|
136
|
+
return (await this.list()).find((e) => e.plugin === plugin);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Whether the source key `<plugin>:<tenant>` is trusted: the tenant is in that plugin's
|
|
140
|
+
* `trustedTenants` (full key match, trust is per tenant, Ruling A19), the plugin is loaded as an
|
|
141
|
+
* identity source and the tenant passes its current tenant declaration (a tenant stored while
|
|
142
|
+
* the extension was away, or before an upgrade added `neverTrusted` or tightened `pattern`, is
|
|
143
|
+
* not trusted). Independent of `enabled`: directory sync reads it for `email_verified` whether
|
|
144
|
+
* or not the login page offers the source.
|
|
145
|
+
*/
|
|
146
|
+
async isTrusted(sourceKey) {
|
|
147
|
+
const i = sourceKey.indexOf(":");
|
|
148
|
+
if (i <= 0)
|
|
149
|
+
return false;
|
|
150
|
+
const plugin = sourceKey.slice(0, i);
|
|
151
|
+
const tenant = sourceKey.slice(i + 1);
|
|
152
|
+
const source = this.loadedSource(plugin);
|
|
153
|
+
if (!source || validateTenantId(source.tenant, tenant) !== "ok")
|
|
154
|
+
return false;
|
|
155
|
+
return (await this.get(plugin))?.trustedTenants.includes(tenant) === true;
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Changes one entry (created with the defaults when missing). `login_sources.unknown_plugin`
|
|
159
|
+
* when the extension is neither loaded as an identity source nor stored; trusted tenants are
|
|
160
|
+
* trimmed, de-duplicated and checked against the source's tenant declaration (only blanks are
|
|
161
|
+
* refused while it is not loaded); turning it on while its deployment config is invalid →
|
|
162
|
+
* `login_sources.needs_config`, and puts it after the last enabled entry.
|
|
163
|
+
*/
|
|
164
|
+
async update(plugin, patch, actorAccountId, via = {}) {
|
|
165
|
+
const current = await this.lockedList();
|
|
166
|
+
const before = current.find((e) => e.plugin === plugin);
|
|
167
|
+
const source = this.loadedSource(plugin);
|
|
168
|
+
const turningOn = patch.enabled === true && before?.enabled !== true;
|
|
169
|
+
// an extension waiting for its config is not loaded: needs_config says what to do next
|
|
170
|
+
if (turningOn && (await this.needsConfig(plugin)))
|
|
171
|
+
throw needsConfig(plugin);
|
|
172
|
+
if (!source && !before) {
|
|
173
|
+
throw new ApiError("login_sources.unknown_plugin", `No extension providing identity-source@1 is named ${plugin}`);
|
|
174
|
+
}
|
|
175
|
+
const next = { ...(before ?? defaults(plugin)) };
|
|
176
|
+
if (patch.enabled !== undefined)
|
|
177
|
+
next.enabled = patch.enabled;
|
|
178
|
+
if (patch.signUp !== undefined)
|
|
179
|
+
next.signUp = patch.signUp;
|
|
180
|
+
if (patch.trustedTenants !== undefined) {
|
|
181
|
+
next.trustedTenants = this.checkTenants(plugin, source, patch.trustedTenants);
|
|
182
|
+
}
|
|
183
|
+
const others = current.filter((e) => e.plugin !== plugin);
|
|
184
|
+
let list;
|
|
185
|
+
if (turningOn || before === undefined) {
|
|
186
|
+
list = enabledFirst([...others, next]);
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
list = enabledFirst(current.map((e) => (e.plugin === plugin ? next : e)));
|
|
190
|
+
}
|
|
191
|
+
await writeLoginSources(this.db.db, list, actorAccountId);
|
|
192
|
+
await audit(this.db.db, {
|
|
193
|
+
actorAccountId,
|
|
194
|
+
...(via.actorTokenId !== undefined && { actorTokenId: via.actorTokenId }),
|
|
195
|
+
action: "login_sources.updated",
|
|
196
|
+
target: plugin,
|
|
197
|
+
detail: { ...via.detail, before: before ?? null, after: next },
|
|
198
|
+
});
|
|
199
|
+
return next;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Sets the login page order: `plugins` must name every enabled stored entry exactly once
|
|
203
|
+
* (available or not); the disabled entries follow in their stored order.
|
|
204
|
+
*/
|
|
205
|
+
async reorder(plugins, actorAccountId, via = {}) {
|
|
206
|
+
const current = await this.lockedList();
|
|
207
|
+
const enabled = current.filter((e) => e.enabled);
|
|
208
|
+
const byPlugin = new Map(enabled.map((e) => [e.plugin, e]));
|
|
209
|
+
if (plugins.length !== enabled.length ||
|
|
210
|
+
new Set(plugins).size !== plugins.length ||
|
|
211
|
+
plugins.some((p) => !byPlugin.has(p))) {
|
|
212
|
+
throw new ApiError("validation_failed", "The order must list every enabled login source exactly once", [
|
|
213
|
+
{
|
|
214
|
+
path: "plugins",
|
|
215
|
+
message: `expected a permutation of: ${[...byPlugin.keys()].join(", ")}`,
|
|
216
|
+
},
|
|
217
|
+
]);
|
|
218
|
+
}
|
|
219
|
+
const list = [
|
|
220
|
+
...plugins.map((p) => byPlugin.get(p)),
|
|
221
|
+
...current.filter((e) => !e.enabled),
|
|
222
|
+
];
|
|
223
|
+
await writeLoginSources(this.db.db, list, actorAccountId);
|
|
224
|
+
await audit(this.db.db, {
|
|
225
|
+
actorAccountId,
|
|
226
|
+
...(via.actorTokenId !== undefined && { actorTokenId: via.actorTokenId }),
|
|
227
|
+
action: "login_sources.updated",
|
|
228
|
+
detail: {
|
|
229
|
+
...via.detail,
|
|
230
|
+
before: current.map((e) => e.plugin),
|
|
231
|
+
after: list.map((e) => e.plugin),
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
return list;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* The admin overview: every loaded identity source and every stored entry, the enabled ones
|
|
238
|
+
* first in login page order, then the rest by plugin name.
|
|
239
|
+
*/
|
|
240
|
+
async overview() {
|
|
241
|
+
const stored = await this.list();
|
|
242
|
+
const byPlugin = new Map(stored.map((e) => [e.plugin, e]));
|
|
243
|
+
const loaded = this.registry
|
|
244
|
+
.list("identity-source")
|
|
245
|
+
.filter((e) => e.capability === IDENTITY_SOURCE_EXTENSION_POINT)
|
|
246
|
+
.map((e) => e.plugin);
|
|
247
|
+
const rest = [...new Set([...stored.filter((e) => !e.enabled).map((e) => e.plugin), ...loaded])]
|
|
248
|
+
.filter((p) => byPlugin.get(p)?.enabled !== true)
|
|
249
|
+
.sort();
|
|
250
|
+
const plugins = [...stored.filter((e) => e.enabled).map((e) => e.plugin), ...rest];
|
|
251
|
+
return Promise.all(plugins.map((p) => this.viewOf(p, byPlugin.get(p))));
|
|
252
|
+
}
|
|
253
|
+
/** One row of {@link overview} (in the caller's transaction when there is one). */
|
|
254
|
+
async view(plugin) {
|
|
255
|
+
return this.viewOf(plugin, await this.get(plugin));
|
|
256
|
+
}
|
|
257
|
+
async viewOf(plugin, stored) {
|
|
258
|
+
const source = this.loadedSource(plugin);
|
|
259
|
+
const base = (this.config.get().http.publicUrl ?? "").replace(/\/+$/, "");
|
|
260
|
+
return {
|
|
261
|
+
...(stored ?? defaults(plugin)),
|
|
262
|
+
label: source ? { zh: source.label.zh, en: source.label.en } : { zh: plugin, en: plugin },
|
|
263
|
+
...(source?.tenant ? { tenant: source.tenant } : {}),
|
|
264
|
+
available: source !== undefined,
|
|
265
|
+
needsConfig: await this.needsConfig(plugin),
|
|
266
|
+
callbackUrl: base === "" ? null : `${base}${ssoCallbackPath(plugin)}`,
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Whether `plugin` provides `identity-source@1`: loaded as one, or (not loaded) its install
|
|
271
|
+
* record's package declares it. A config-declared extension that is not loaded reads false
|
|
272
|
+
* (its manifest is not in PG).
|
|
273
|
+
*/
|
|
274
|
+
async providesIdentitySource(plugin) {
|
|
275
|
+
if (this.loadedSource(plugin))
|
|
276
|
+
return true;
|
|
277
|
+
if (this.registry.current(plugin) || this.registry.declared().has(plugin))
|
|
278
|
+
return false;
|
|
279
|
+
const row = await this.db
|
|
280
|
+
.selectFrom("extension_installs")
|
|
281
|
+
.innerJoin("extension_packages", "extension_packages.sha256", "extension_installs.sha256")
|
|
282
|
+
.select("extension_packages.section")
|
|
283
|
+
.where("extension_installs.name", "=", plugin)
|
|
284
|
+
.executeTakeFirst();
|
|
285
|
+
const provides = row?.section?.manifest
|
|
286
|
+
?.provides;
|
|
287
|
+
return provides?.includes(IDENTITY_SOURCE_EXTENSION_POINT) === true;
|
|
288
|
+
}
|
|
289
|
+
/** The stored list with its row locked FOR UPDATE (created as `[]` first): writes serialize. */
|
|
290
|
+
async lockedList() {
|
|
291
|
+
await this.db
|
|
292
|
+
.insertInto("deployment_settings")
|
|
293
|
+
.values({ key: LOGIN_SOURCES_SETTING, value: "[]" })
|
|
294
|
+
.onConflict((oc) => oc.column("key").doNothing())
|
|
295
|
+
.execute();
|
|
296
|
+
const row = await this.db
|
|
297
|
+
.selectFrom("deployment_settings")
|
|
298
|
+
.select("value")
|
|
299
|
+
.where("key", "=", LOGIN_SOURCES_SETTING)
|
|
300
|
+
.forUpdate()
|
|
301
|
+
.executeTakeFirst();
|
|
302
|
+
return parseLoginSources(row?.value, this.log);
|
|
303
|
+
}
|
|
304
|
+
/** The loaded `identity-source@1` implementation of `plugin` (live from the registry). */
|
|
305
|
+
loadedSource(plugin) {
|
|
306
|
+
const entry = this.registry
|
|
307
|
+
.list("identity-source")
|
|
308
|
+
.find((e) => e.plugin === plugin && e.capability === IDENTITY_SOURCE_EXTENSION_POINT);
|
|
309
|
+
return entry?.impl;
|
|
310
|
+
}
|
|
311
|
+
checkTenants(plugin, source, tenants) {
|
|
312
|
+
const out = [];
|
|
313
|
+
for (const raw of tenants) {
|
|
314
|
+
const id = raw.trim();
|
|
315
|
+
const verdict = validateTenantId(source?.tenant, id);
|
|
316
|
+
if (verdict !== "ok")
|
|
317
|
+
throw invalidTenant(plugin, id, TENANT_REASONS[verdict]);
|
|
318
|
+
if (/\s/.test(id) || id.length > TENANT_MAX) {
|
|
319
|
+
throw invalidTenant(plugin, id, `a tenant id has no spaces and at most ${TENANT_MAX} characters`);
|
|
320
|
+
}
|
|
321
|
+
if (!out.includes(id))
|
|
322
|
+
out.push(id);
|
|
323
|
+
}
|
|
324
|
+
if (out.length > MAX_TRUSTED_TENANTS) {
|
|
325
|
+
throw new ApiError("validation_failed", "Too many trusted tenants", [
|
|
326
|
+
{ path: "trustedTenants", message: `at most ${MAX_TRUSTED_TENANTS}` },
|
|
327
|
+
]);
|
|
328
|
+
}
|
|
329
|
+
return out;
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Whether the loaded extension's running config leaves a required overridable field empty: the
|
|
333
|
+
* host loads with those fields optional, so that is the only way the full schema can refuse it
|
|
334
|
+
* (as in `EffectiveConfigs.get`).
|
|
335
|
+
*/
|
|
336
|
+
loadedConfigIncomplete(plugin) {
|
|
337
|
+
const inst = this.registry.current(plugin);
|
|
338
|
+
const schema = inst?.manifest.config?.deployment;
|
|
339
|
+
return schema !== undefined && missingOverridable(schema, inst?.config).length > 0;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Whether an identity source's deployment config is invalid: loaded as one, see
|
|
343
|
+
* {@link loadedConfigIncomplete}; loaded but not an identity source, false (the caller answers
|
|
344
|
+
* unknown_plugin); not loaded, {@link pendingConfigIdentitySource}.
|
|
345
|
+
*/
|
|
346
|
+
async needsConfig(plugin) {
|
|
347
|
+
if (this.loadedSource(plugin))
|
|
348
|
+
return this.loadedConfigIncomplete(plugin);
|
|
349
|
+
if (this.registry.current(plugin))
|
|
350
|
+
return false;
|
|
351
|
+
return this.pendingConfigIdentitySource(plugin);
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Whether a live replica reports `plugin` pending configuration for the version the deployment
|
|
355
|
+
* wants: an install record's package (its row's sha256 matches the install target, and the
|
|
356
|
+
* package's static manifest provides `identity-source@1`), or a config-declared extension (the
|
|
357
|
+
* startup config names it; its manifest is not in PG, so the point is not checked).
|
|
358
|
+
*/
|
|
359
|
+
async pendingConfigIdentitySource(plugin) {
|
|
360
|
+
const staleSeconds = STALE_RECONCILE_PERIODS * this.config.get().extensionHost.reconcileIntervalSeconds;
|
|
361
|
+
const pending = this.db
|
|
362
|
+
.selectFrom("extension_replica_status")
|
|
363
|
+
.where("extension_replica_status.plugin", "=", plugin)
|
|
364
|
+
.where("extension_replica_status.state", "=", "pending")
|
|
365
|
+
.where("extension_replica_status.reason", "=", "config")
|
|
366
|
+
.where("extension_replica_status.heartbeat_at", ">", sql `now() - make_interval(secs => ${staleSeconds})`);
|
|
367
|
+
if (this.registry.declared().has(plugin)) {
|
|
368
|
+
const row = await pending
|
|
369
|
+
.select("extension_replica_status.plugin")
|
|
370
|
+
.where("extension_replica_status.source", "=", "config")
|
|
371
|
+
.limit(1)
|
|
372
|
+
.executeTakeFirst();
|
|
373
|
+
return row !== undefined;
|
|
374
|
+
}
|
|
375
|
+
const row = await pending
|
|
376
|
+
.innerJoin("extension_installs", (j) => j
|
|
377
|
+
.onRef("extension_installs.name", "=", "extension_replica_status.plugin")
|
|
378
|
+
.onRef("extension_installs.sha256", "=", "extension_replica_status.sha256"))
|
|
379
|
+
.innerJoin("extension_packages", "extension_packages.sha256", "extension_installs.sha256")
|
|
380
|
+
.select("extension_packages.section")
|
|
381
|
+
.limit(1)
|
|
382
|
+
.executeTakeFirst();
|
|
383
|
+
const provides = row?.section?.manifest
|
|
384
|
+
?.provides;
|
|
385
|
+
return provides?.includes(IDENTITY_SOURCE_EXTENSION_POINT) === true;
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
__decorate([
|
|
389
|
+
Transactional()
|
|
390
|
+
], LoginSourcesService.prototype, "update", null);
|
|
391
|
+
__decorate([
|
|
392
|
+
Transactional()
|
|
393
|
+
], LoginSourcesService.prototype, "reorder", null);
|
|
394
|
+
LoginSourcesService = __decorate([
|
|
395
|
+
Injectable(),
|
|
396
|
+
__param(0, Inject(KernelDb)),
|
|
397
|
+
__param(1, Inject(TransactionHost)),
|
|
398
|
+
__param(2, Inject(ExtensionRegistry)),
|
|
399
|
+
__param(3, Inject(KernelConfigService)),
|
|
400
|
+
__param(4, Inject(KERNEL_LOGGER))
|
|
401
|
+
], LoginSourcesService);
|
|
402
|
+
export { LoginSourcesService };
|
|
403
|
+
const needsConfig = (plugin) => new ApiError("login_sources.needs_config", `The deployment config of ${plugin} is not complete; fill it in before offering its sign-in`);
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why a sign-in started: `signin` from the login page, `link` from the linked accounts page by a
|
|
3
|
+
* signed-in person (links to that person's account, never creates one, never switches the session).
|
|
4
|
+
*/
|
|
5
|
+
export type SsoIntent = "signin" | "link";
|
|
6
|
+
/** How an identity row was made (`null`: a legacy row from before migration 0019, read as `sso`). */
|
|
7
|
+
export type SsoRowVia = "bind" | "sso" | "directory" | "local" | null;
|
|
8
|
+
export interface SsoDecisionInput {
|
|
9
|
+
intent: SsoIntent;
|
|
10
|
+
/**
|
|
11
|
+
* The account of the web session that both the start and the callback carried; only for
|
|
12
|
+
* `intent: link` (the caller passes it only when the two match).
|
|
13
|
+
*/
|
|
14
|
+
sessionAccountId?: string;
|
|
15
|
+
/** The identity row of the external account, if any. */
|
|
16
|
+
row?: {
|
|
17
|
+
accountId: string;
|
|
18
|
+
linkedVia: SsoRowVia;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The account a trusted-email merge would link an unlinked identity to (trusted tenant, verified
|
|
22
|
+
* email equal to exactly one account's verified email), if any.
|
|
23
|
+
*/
|
|
24
|
+
mergeTarget?: string;
|
|
25
|
+
/** The login source's setting for an unlinked external account. */
|
|
26
|
+
signUp: "link" | "create";
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* - `signin`: sign in as the row's account (the row is refreshed).
|
|
30
|
+
* - `refresh`: link intent, the row is already the session account's: refresh it, back to the page.
|
|
31
|
+
* - `upgrade`: link intent, the session account's `bind` row becomes `sso` (`identity.verified`).
|
|
32
|
+
* - `linked`: write a new `sso` row for `accountId` (`identity.linked` with `via`); a sign-in
|
|
33
|
+
* (merge) signs in as it, a link intent stays in its session.
|
|
34
|
+
* - `link_page`: send the person to the link page (`existingAccountId`: a `bind` row's account,
|
|
35
|
+
* whose password upgrades it; never shown to the person).
|
|
36
|
+
* - `create`: self sign-up, a new org-less account with this identity.
|
|
37
|
+
* - `error`: refuse with the code.
|
|
38
|
+
*/
|
|
39
|
+
export type SsoDecision = {
|
|
40
|
+
kind: "signin";
|
|
41
|
+
accountId: string;
|
|
42
|
+
} | {
|
|
43
|
+
kind: "refresh";
|
|
44
|
+
accountId: string;
|
|
45
|
+
} | {
|
|
46
|
+
kind: "upgrade";
|
|
47
|
+
accountId: string;
|
|
48
|
+
} | {
|
|
49
|
+
kind: "linked";
|
|
50
|
+
accountId: string;
|
|
51
|
+
via: "oauth" | "verified_email";
|
|
52
|
+
} | {
|
|
53
|
+
kind: "link_page";
|
|
54
|
+
existingAccountId?: string;
|
|
55
|
+
} | {
|
|
56
|
+
kind: "create";
|
|
57
|
+
} | {
|
|
58
|
+
kind: "error";
|
|
59
|
+
code: "identity.taken" | "sso.session_mismatch";
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* The callback's decision on the identity row, spec §4's table cell by cell:
|
|
63
|
+
*
|
|
64
|
+
* | Row | `link` (signed in as A) | `signin` |
|
|
65
|
+
* |---|---|---|
|
|
66
|
+
* | A's (`sso` / `directory` / legacy) | refresh | sign in as A |
|
|
67
|
+
* | A's `bind` | upgrade | link page |
|
|
68
|
+
* | B's | `identity.taken` | sign in as B; B's `bind` row → link page |
|
|
69
|
+
* | none, merge applies | linked to A | linked to the merge target, sign in |
|
|
70
|
+
* | none | linked to A (`oauth`) | `signUp: link` → link page; `create` → create |
|
|
71
|
+
*
|
|
72
|
+
* In `signin` the session plays no part, so "A" and "B" are the same column: only the row's
|
|
73
|
+
* `linked_via` matters. A link intent without its session is a session mismatch.
|
|
74
|
+
*/
|
|
75
|
+
export declare function decideSsoCallback(input: SsoDecisionInput): SsoDecision;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// The decision a third-party sign-in callback takes on the identity row (spec
|
|
2
|
+
// 2026-11-26-login-extensions §4). A leaf module with no service imports: `ExternalIdentities`
|
|
3
|
+
// applies the decision under the identity lock, `SsoFlow` re-exports it, and the unit test covers
|
|
4
|
+
// the table cell by cell.
|
|
5
|
+
/**
|
|
6
|
+
* The callback's decision on the identity row, spec §4's table cell by cell:
|
|
7
|
+
*
|
|
8
|
+
* | Row | `link` (signed in as A) | `signin` |
|
|
9
|
+
* |---|---|---|
|
|
10
|
+
* | A's (`sso` / `directory` / legacy) | refresh | sign in as A |
|
|
11
|
+
* | A's `bind` | upgrade | link page |
|
|
12
|
+
* | B's | `identity.taken` | sign in as B; B's `bind` row → link page |
|
|
13
|
+
* | none, merge applies | linked to A | linked to the merge target, sign in |
|
|
14
|
+
* | none | linked to A (`oauth`) | `signUp: link` → link page; `create` → create |
|
|
15
|
+
*
|
|
16
|
+
* In `signin` the session plays no part, so "A" and "B" are the same column: only the row's
|
|
17
|
+
* `linked_via` matters. A link intent without its session is a session mismatch.
|
|
18
|
+
*/
|
|
19
|
+
export function decideSsoCallback(input) {
|
|
20
|
+
const { row } = input;
|
|
21
|
+
if (input.intent === "link") {
|
|
22
|
+
const me = input.sessionAccountId;
|
|
23
|
+
if (me === undefined)
|
|
24
|
+
return { kind: "error", code: "sso.session_mismatch" };
|
|
25
|
+
if (row === undefined)
|
|
26
|
+
return { kind: "linked", accountId: me, via: "oauth" };
|
|
27
|
+
if (row.accountId !== me)
|
|
28
|
+
return { kind: "error", code: "identity.taken" };
|
|
29
|
+
return row.linkedVia === "bind"
|
|
30
|
+
? { kind: "upgrade", accountId: me }
|
|
31
|
+
: { kind: "refresh", accountId: me };
|
|
32
|
+
}
|
|
33
|
+
if (row !== undefined) {
|
|
34
|
+
return row.linkedVia === "bind"
|
|
35
|
+
? { kind: "link_page", existingAccountId: row.accountId }
|
|
36
|
+
: { kind: "signin", accountId: row.accountId };
|
|
37
|
+
}
|
|
38
|
+
if (input.mergeTarget !== undefined) {
|
|
39
|
+
return { kind: "linked", accountId: input.mergeTarget, via: "verified_email" };
|
|
40
|
+
}
|
|
41
|
+
return input.signUp === "create" ? { kind: "create" } : { kind: "link_page" };
|
|
42
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ExternalIdentity } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import type { Redis } from "ioredis";
|
|
3
|
+
import { ApiError } from "../errors.js";
|
|
4
|
+
/** A pending link's lifetime (seconds). */
|
|
5
|
+
export declare const SSO_LINK_TTL_SECONDS = 600;
|
|
6
|
+
/** Wrong passwords a ticket survives: the fifth burns it. */
|
|
7
|
+
export declare const SSO_LINK_MAX_ATTEMPTS = 5;
|
|
8
|
+
/** The web's link page (next-intl adds the language prefix). */
|
|
9
|
+
export declare const SSO_LINK_PAGE_PATH = "/login/link";
|
|
10
|
+
/** A sign-in that chose the link page, waiting for the person's password (spec §5). */
|
|
11
|
+
export interface PendingSsoLink {
|
|
12
|
+
plugin: string;
|
|
13
|
+
/** The normalized external identity the identity source verified. */
|
|
14
|
+
identity: ExternalIdentity;
|
|
15
|
+
/** The site path to go to after linking. */
|
|
16
|
+
returnTo: string;
|
|
17
|
+
/** SHA-256 of the browser binding value (`cap_sso`) the sign-in was started with. */
|
|
18
|
+
binding: string;
|
|
19
|
+
}
|
|
20
|
+
export declare const linkExpired: () => ApiError;
|
|
21
|
+
/**
|
|
22
|
+
* Link tickets (spec §5): `cap_link_<32 bytes base64url>`, kept in Redis as a hash
|
|
23
|
+
* `capk:sso-link:<sha256(ticket)>` (`rec`: the pending link as JSON, `attempts`: reserved password
|
|
24
|
+
* checks, `failures`: wrong passwords) for 10 minutes.
|
|
25
|
+
* Every read checks the browser binding cookie against the recorded hash. Single use on success
|
|
26
|
+
* ({@link redeem} deletes it atomically, so two concurrent submissions get one winner), burned
|
|
27
|
+
* after {@link SSO_LINK_MAX_ATTEMPTS} wrong passwords (an attempt is reserved atomically before
|
|
28
|
+
* each password check, {@link reserveAttempt}, on the same key, which keeps its TTL). All state is
|
|
29
|
+
* in Redis: any replica serves any step.
|
|
30
|
+
*
|
|
31
|
+
* Deployment assumption: no sibling origin can set cookies for the kernel's host (no untrusted
|
|
32
|
+
* subdomain sharing a parent domain cookie scope), so the `cap_sso` binding value is this
|
|
33
|
+
* browser's own and cannot be planted to tie a victim's browser to an attacker's ticket.
|
|
34
|
+
*/
|
|
35
|
+
export declare class SsoLinkTickets {
|
|
36
|
+
private readonly redis;
|
|
37
|
+
constructor(redis: Redis);
|
|
38
|
+
/** Stores a pending link and returns its ticket. */
|
|
39
|
+
create(link: PendingSsoLink): Promise<string>;
|
|
40
|
+
/**
|
|
41
|
+
* The pending link of `ticket` without consuming it. Unknown, expired, used or burned →
|
|
42
|
+
* `sso.link_expired`; a browser binding value that does not match → `sso.session_mismatch`.
|
|
43
|
+
*/
|
|
44
|
+
peek(ticket: string, binding: string | undefined): Promise<PendingSsoLink>;
|
|
45
|
+
/**
|
|
46
|
+
* Reserves one of the ticket's attempts before a password check; none left, or the ticket gone →
|
|
47
|
+
* `sso.link_expired`.
|
|
48
|
+
*/
|
|
49
|
+
reserveAttempt(ticket: string): Promise<void>;
|
|
50
|
+
/** Gives a reserved attempt back (the check did not find a wrong password). */
|
|
51
|
+
refundAttempt(ticket: string): Promise<void>;
|
|
52
|
+
/** The reserved attempt was a wrong password; the one that reaches the limit burns the ticket. */
|
|
53
|
+
failedAttempt(ticket: string): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Takes the pending link and deletes it in one step: of concurrent callers exactly one gets it,
|
|
56
|
+
* the others `sso.link_expired`. The binding is checked again on the taken record.
|
|
57
|
+
*/
|
|
58
|
+
redeem(ticket: string, binding: string | undefined): Promise<PendingSsoLink>;
|
|
59
|
+
/** Deletes the ticket (its login source was switched off). */
|
|
60
|
+
discard(ticket: string): Promise<void>;
|
|
61
|
+
}
|