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