@capybara-hq/kernel 0.1.0-rc.72 → 0.1.0-rc.74

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 (81) hide show
  1. package/bootstrap.json +5 -5
  2. package/dist/catalog/admin-catalog.schemas.d.ts +3 -1
  3. package/dist/catalog/admin-catalog.schemas.js +6 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/catalog/org-catalog.schemas.d.ts +3 -1
  6. package/dist/catalog/org-catalog.schemas.js +3 -1
  7. package/dist/catalog/plugin-package.js +7 -5
  8. package/dist/catalog/reserved-names.js +3 -9
  9. package/dist/channels/actions.js +4 -0
  10. package/dist/channels/cards.d.ts +10 -7
  11. package/dist/channels/cards.js +23 -12
  12. package/dist/channels/phrases.d.ts +24 -2
  13. package/dist/channels/phrases.js +12 -2
  14. package/dist/ctx/secrets.d.ts +4 -2
  15. package/dist/ctx/secrets.js +19 -5
  16. package/dist/db/kernel-schema.d.ts +14 -0
  17. package/dist/devices/conversation-devices.d.ts +3 -2
  18. package/dist/devices/conversation-devices.js +9 -4
  19. package/dist/devices/device-projects.service.d.ts +22 -27
  20. package/dist/devices/device-projects.service.js +36 -41
  21. package/dist/devices/devices.controller.d.ts +3 -5
  22. package/dist/devices/devices.controller.js +4 -17
  23. package/dist/devices/devices.schemas.d.ts +1 -1
  24. package/dist/devices/devices.schemas.js +1 -1
  25. package/dist/devices/devices.service.d.ts +72 -52
  26. package/dist/devices/devices.service.js +158 -93
  27. package/dist/devices/project-rules.d.ts +6 -8
  28. package/dist/devices/project-rules.js +5 -11
  29. package/dist/dial-in/auth.controller.d.ts +1 -1
  30. package/dist/dial-in/auth.controller.js +1 -1
  31. package/dist/dial-in/auth.service.d.ts +4 -0
  32. package/dist/dial-in/auth.service.js +16 -2
  33. package/dist/dial-in/machines.d.ts +5 -4
  34. package/dist/dial-in/machines.js +5 -4
  35. package/dist/errors.d.ts +8 -3
  36. package/dist/errors.js +8 -3
  37. package/dist/extensions/admin-ops.js +2 -1
  38. package/dist/extensions/bootstrap-extra.d.ts +11 -1
  39. package/dist/extensions/bootstrap-extra.js +21 -1
  40. package/dist/extensions/bootstrap-manifest.d.ts +14 -0
  41. package/dist/extensions/bootstrap-manifest.js +23 -0
  42. package/dist/extensions/bootstrap-packages.d.ts +87 -0
  43. package/dist/extensions/bootstrap-packages.js +263 -0
  44. package/dist/extensions/bootstrap.d.ts +27 -71
  45. package/dist/extensions/bootstrap.js +85 -329
  46. package/dist/extensions/guide-places.d.ts +9 -0
  47. package/dist/extensions/guide-places.js +32 -22
  48. package/dist/extensions/permission-set.d.ts +1 -1
  49. package/dist/extensions/permission-set.js +1 -1
  50. package/dist/extensions/plugin-guides.d.ts +20 -2
  51. package/dist/extensions/plugin-guides.js +39 -14
  52. package/dist/identity/sso-paths.d.ts +7 -0
  53. package/dist/identity/sso-paths.js +13 -0
  54. package/dist/identity/sso.js +3 -2
  55. package/dist/index.d.ts +3 -1
  56. package/dist/index.js +3 -1
  57. package/dist/lifecycle/kernel-lifecycle.js +2 -2
  58. package/dist/platform/exclusions.js +2 -7
  59. package/dist/platform/ops/devices.ops.js +11 -7
  60. package/dist/platform/ops/setup.ops.js +1 -1
  61. package/dist/runtime/project/knowledge.service.js +6 -5
  62. package/dist/sandbox/device-sandbox.d.ts +11 -0
  63. package/dist/sandbox/device-sandbox.js +29 -0
  64. package/dist/sandbox/modes.d.ts +16 -4
  65. package/dist/sandbox/modes.js +12 -0
  66. package/dist/sandbox/permission-facts.d.ts +12 -2
  67. package/dist/sandbox/permission-facts.js +14 -4
  68. package/dist/sandbox/sandbox.service.d.ts +18 -11
  69. package/dist/sandbox/sandbox.service.js +51 -24
  70. package/dist/setup/setup-guides.service.d.ts +2 -2
  71. package/dist/setup/setup-guides.service.js +1 -1
  72. package/dist/tools/approvals.service.d.ts +31 -11
  73. package/dist/tools/approvals.service.js +55 -19
  74. package/dist/tools/builtins/sandbox/common.d.ts +2 -2
  75. package/dist/tools/builtins/sandbox/common.js +2 -2
  76. package/dist/tools/network-asks.d.ts +103 -20
  77. package/dist/tools/network-asks.js +133 -18
  78. package/dist/tools/pipeline.d.ts +5 -0
  79. package/dist/tools/pipeline.js +15 -8
  80. package/package.json +3 -3
  81. package/src/migrations/0178_bootstrap_run_extra.sql +17 -0
@@ -8,6 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
+ import { pluginDescription, validateAllowHost, } from "@capybara-hq/plugin-sdk";
11
12
  import { Inject, Injectable } from "@nestjs/common";
12
13
  import { sql } from "kysely";
13
14
  import { DialInHandlers } from "../dial-in/handlers.js";
@@ -15,23 +16,26 @@ import { DialInMachines } from "../dial-in/machines.js";
15
16
  import { DialInRelay } from "../dial-in/relay.js";
16
17
  import { ApiError } from "../errors.js";
17
18
  import { ExtensionDisplayNames } from "../extensions/display-name.js";
19
+ import { PluginGuides } from "../extensions/plugin-guides.js";
18
20
  import { avatarColumns, personAvatarUrl } from "../identity/account-avatar.js";
19
21
  import { audit } from "../identity/audit.js";
20
22
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
21
23
  import { KernelDb } from "../infra/database/kernel-db.js";
22
- import { assertNotSharedAdmission, TransactionHost, withOrderedLocks, } from "../infra/database/transaction-host.js";
24
+ import { assertNotSharedAdmission, currentStore, TransactionHost, withOrderedLocks, } from "../infra/database/transaction-host.js";
23
25
  import { Transactional } from "../infra/database/transactional.decorator.js";
24
26
  import { OutboxService } from "../infra/outbox/outbox.service.js";
25
27
  import { DeviceReports } from "../sandbox/device-reports.js";
26
28
  import { hostGrantable } from "../sandbox/device-sandbox.js";
27
29
  import { oweDeviceDestroy, SandboxJobs } from "../sandbox/jobs.js";
28
30
  import { coversHost } from "../sandbox/modes.js";
31
+ import { assertAuthorityHeld } from "../sandbox/permission-authority-lock.js";
29
32
  import { hostsNarrowed, needsOpenNetwork, PermissionCeilingWrites, } from "../sandbox/permission-ceiling-writes.js";
30
33
  import { ownNetwork, PermissionFacts } from "../sandbox/permission-facts.js";
31
34
  import { DeviceProviders, servesDialIn } from "../sandbox/providers.js";
32
- import { deviceNotFound, SandboxService } from "../sandbox/sandbox.service.js";
35
+ import { SandboxService } from "../sandbox/sandbox.service.js";
33
36
  import { DeviceAccess } from "./access.js";
34
37
  import { DeviceProviderSelection } from "./device-provider-selection.js";
38
+ import { deviceNotFound } from "./errors.js";
35
39
  /** How many recent setting changes a device view lists. */
36
40
  export const RECENT_POLICY_CHANGES = 10;
37
41
  const isUniqueViolation = (e, constraint) => typeof e === "object" &&
@@ -52,6 +56,8 @@ const providerNotOn = (provider, on) => {
52
56
  const message = `Device provider ${provider} is not on in this organization; choose one of: ${providerChoices(on)}`;
53
57
  return new ApiError("validation_failed", message, [{ path: "provider", message }]);
54
58
  };
59
+ /** A new device is created on a dial-in provider: its devices are made by the machine (409). */
60
+ const providerDialIn = (provider) => new ApiError("device.provider_dial_in", `Devices of provider ${provider} are connected from the machine: follow its guide in New device (新建设备) instead of creating one here`);
55
61
  /** A device sign-in names a provider that is no dial-in provider on in the org (403). */
56
62
  export const dialInProviderUnavailable = (provider) => new ApiError("device.provider_unavailable", `Device provider ${provider} cannot take a machine in this organization; choose one of the providers listed on the sign-in page`);
57
63
  const nameTaken = () => new ApiError("device.name_taken", "You already have a device with this name");
@@ -80,6 +86,7 @@ let DevicesService = class DevicesService {
80
86
  displayNames;
81
87
  reports;
82
88
  dialIn;
89
+ guides;
83
90
  constructor(db, txHost, config, selection, sandbox, sandboxJobs,
84
91
  /** Owes a deleted device's destruction in the delete's transaction. */
85
92
  outbox, access,
@@ -90,7 +97,9 @@ let DevicesService = class DevicesService {
90
97
  /** Each device's stored provider report (read only; never asks the provider). */
91
98
  reports,
92
99
  /** The dial-in providers on in an org (a device signed in from a machine). */
93
- dialIn) {
100
+ dialIn,
101
+ /** The providers' device-connection guides. */
102
+ guides) {
94
103
  this.db = db;
95
104
  this.txHost = txHost;
96
105
  this.config = config;
@@ -107,19 +116,31 @@ let DevicesService = class DevicesService {
107
116
  this.displayNames = displayNames;
108
117
  this.reports = reports;
109
118
  this.dialIn = dialIn;
119
+ this.guides = guides;
110
120
  }
111
121
  /**
112
122
  * The person's live devices in the org, the default first, then by creation, with the device
113
123
  * providers on in the org and its default one. With a default provider serving the org the
114
124
  * default device is created first if missing (its first need, spec §4.2 item 7; an existing one
115
- * is only read, whatever its provider's state).
125
+ * is only read, whatever its provider's state). `role` is the caller's role in the org: it
126
+ * decides which setup guides the org's catalog shows them (none without it).
116
127
  */
117
- async list(orgId, accountId) {
128
+ async list(orgId, accountId, role) {
118
129
  const on = await this.selection.onInOrg(orgId);
119
- const names = await this.displayNames.many(on.map((e) => e.plugin));
130
+ const plugins = on.map((e) => e.plugin);
131
+ const [names, descriptions, guides] = await Promise.all([
132
+ this.displayNames.many(plugins),
133
+ this.catalogDescriptions(plugins),
134
+ role === undefined
135
+ ? new Map()
136
+ : this.guides.deviceGuides(plugins, { orgId, role }),
137
+ ]);
120
138
  const providers = on.map((e) => ({
121
139
  plugin: e.plugin,
122
140
  displayName: names.get(e.plugin) ?? null,
141
+ description: descriptions.get(e.plugin) ?? null,
142
+ dialIn: servesDialIn(e),
143
+ guide: guides.get(e.plugin) ?? null,
123
144
  }));
124
145
  const defaultProvider = (await this.selection.defaultFor(orgId))?.plugin ?? null;
125
146
  const defaultId = await this.ensureDefault(orgId, accountId);
@@ -145,6 +166,28 @@ let DevicesService = class DevicesService {
145
166
  defaultProvider,
146
167
  };
147
168
  }
169
+ /** The latest catalog descriptions of `names` (one query); an item without one is absent. */
170
+ async catalogDescriptions(names) {
171
+ const out = new Map();
172
+ if (names.length === 0)
173
+ return out;
174
+ const rows = await this.db
175
+ .selectFrom("catalog_items as i")
176
+ .innerJoin("catalog_item_versions as v", (j) => j.onRef("v.item_id", "=", "i.id").onRef("v.version", "=", "i.latest_version"))
177
+ .select(["i.name", "v.manifest"])
178
+ .where("i.name", "in", names)
179
+ .where("i.deleted_at", "is", null)
180
+ .execute();
181
+ for (const r of rows) {
182
+ const d = r.manifest?.description;
183
+ if (typeof d !== "string" && (typeof d !== "object" || d === null))
184
+ continue;
185
+ const text = pluginDescription(d);
186
+ if (text.en !== "" && !out.has(r.name))
187
+ out.set(r.name, text);
188
+ }
189
+ return out;
190
+ }
148
191
  /** One of the person's live devices; anyone else's (or a missing one) → `not_found`. */
149
192
  async get(orgId, accountId, id) {
150
193
  const [view] = await this.views(orgId, accountId, id);
@@ -174,13 +217,18 @@ let DevicesService = class DevicesService {
174
217
  async providerFor(orgId, named) {
175
218
  const on = await this.selection.onInOrg(orgId);
176
219
  if (named !== undefined) {
177
- if (on.some((e) => e.plugin === named))
178
- return named;
179
- throw providerNotOn(named, on);
220
+ const entry = on.find((e) => e.plugin === named);
221
+ if (!entry)
222
+ throw providerNotOn(named, on);
223
+ if (servesDialIn(entry))
224
+ throw providerDialIn(named);
225
+ return named;
180
226
  }
181
227
  const fallback = await this.selection.defaultFor(orgId);
182
228
  if (!fallback)
183
229
  throw providerRequired(on);
230
+ if (servesDialIn(fallback))
231
+ throw providerDialIn(fallback.plugin);
184
232
  return fallback.plugin;
185
233
  }
186
234
  async insert(orgId, accountId, name, provider, actorTokenId, auditDetail) {
@@ -410,7 +458,8 @@ let DevicesService = class DevicesService {
410
458
  * transaction: a narrowing bumps the device epoch and revokes the admitted or started work it
411
459
  * takes ({@link networkNarrowingRevokes}; the revocations are owed through the outbox) and keeps
412
460
  * Full consent; a widening resets Full consent with a `permission_profile_changed` event.
413
- * Audited `device.network_changed` (`via`: `web`, `token` for an API token, or the agent's).
461
+ * Audited `device.network_changed` (`via`: `opts.via` (a network approval's), else `web`,
462
+ * `token` for an API token, or the agent's in `auditDetail`).
414
463
  */
415
464
  async networkLocked(orgId, accountId, id, want, actorTokenId, opts) {
416
465
  await this.ceilings.lock({ orgId, deviceId: id }, "device");
@@ -438,11 +487,80 @@ let DevicesService = class DevicesService {
438
487
  from,
439
488
  to,
440
489
  by: accountId,
441
- via: actorTokenId !== undefined ? "token" : "web",
490
+ via: opts.via ?? (actorTokenId !== undefined ? "token" : "web"),
442
491
  ...opts.auditDetail,
443
492
  },
444
493
  });
445
494
  }
495
+ /**
496
+ * The ordered prelude of {@link addNetworkHostsIn} in a caller's transaction: the person's
497
+ * membership, the device row and the device's permission write lock (authority levels platform,
498
+ * org shared, device exclusive). A caller that adds hosts inside its own transaction (a network
499
+ * approval's decision) runs this in its own `withOrderedLocks` prelude, after its org row and
500
+ * before any conversation, approval or run row, the place of the authority locks in the global
501
+ * lock order; refuses `device.not_found` for anyone else's or a deleted device.
502
+ */
503
+ async lockNetworkAddSubject(orgId, accountId, deviceId) {
504
+ await this.lockNetworkSubject(orgId, accountId, deviceId);
505
+ }
506
+ /**
507
+ * Adds `hosts` to one of the person's devices' own network list: a network approval decided
508
+ * "add to this device's list" (`via`: where it was decided). In a caller's transaction (the
509
+ * approval decision's) it joins it and requires the device's permission write lock already held
510
+ * there ({@link lockNetworkAddSubject} in the caller's ordered prelude; else it throws before
511
+ * writing); with no transaction it takes that prelude itself ({@link withOrderedLocks}). It
512
+ * takes no distributed lock. The write is a network change like `PATCH` ({@link networkLocked}:
513
+ * audited `device.network_changed` from → to, listed as a recent change, the device epoch bumped
514
+ * and the instance marked for its next use). Refuses with `device.network_not_allowed`, writing
515
+ * nothing, unless the stored network is `allowlist` with a host list of its own (a device
516
+ * following its org's hosts already allows every host its list could name) and every host may
517
+ * join that list (`deviceListAddRefusal`). Hosts its list already covers change nothing; own
518
+ * hosts the org's hosts no longer cover (in effect nowhere) leave the list with the addition.
519
+ */
520
+ async addNetworkHostsIn(orgId, accountId, deviceId, hosts, via) {
521
+ if (currentStore() !== undefined) {
522
+ assertAuthorityHeld("device", deviceId, true);
523
+ await this.addNetworkHostsLocked(orgId, accountId, deviceId, hosts, via);
524
+ return;
525
+ }
526
+ await withOrderedLocks(() => this.lockNetworkSubject(orgId, accountId, deviceId), () => this.addNetworkHostsLocked(orgId, accountId, deviceId, hosts, via));
527
+ }
528
+ /** {@link addNetworkHostsIn} under the locks of its prelude (naming them again re-checks). */
529
+ async addNetworkHostsLocked(orgId, accountId, id, hosts, via) {
530
+ await this.lockOwn(orgId, accountId, id);
531
+ await this.ceilings.lock({ orgId, deviceId: id }, "device");
532
+ const row = await this.db
533
+ .selectFrom("devices")
534
+ .select(["network_mode", "network_hosts"])
535
+ .where("id", "=", id)
536
+ .executeTakeFirstOrThrow();
537
+ const own = ownNetwork(row);
538
+ if (own.networkMode === "none")
539
+ throw new ApiError("device.network_not_allowed", "Network access is turned off for this device's sandbox; its owner changes that on the device page");
540
+ if (own.networkMode !== "allowlist" || own.networkHosts.length === 0)
541
+ throw new ApiError("device.network_not_allowed", "This device has no host list of its own: it follows its organization's hosts, which already include every host its list could name; an organization admin adds another host to the organization's device network list");
542
+ const wanted = [...new Set(hosts.map((h) => h.toLowerCase()))];
543
+ for (const host of wanted) {
544
+ const invalid = validateAllowHost(host);
545
+ if (invalid.length > 0)
546
+ throw new ApiError("validation_failed", `${host}: ${invalid.join("; ")}`, [
547
+ { path: "hosts", message: `${host}: ${invalid.join("; ")}` },
548
+ ]);
549
+ }
550
+ const facts = await this.facts.deviceSandboxFacts(orgId, id);
551
+ for (const host of wanted) {
552
+ const why = facts.listAddRefusal(host);
553
+ if (why !== null)
554
+ throw new ApiError("device.network_not_allowed", `${host} cannot be added to this device's network list: ${why}`);
555
+ }
556
+ const covers = (list, h) => list.some((p) => coversHost(p.toLowerCase(), h));
557
+ // own hosts the org dropped since are in effect nowhere: they would refuse the new list
558
+ const kept = own.networkHosts.filter((h) => covers(facts.orgHosts, h.toLowerCase()));
559
+ const added = wanted.filter((h) => !covers(kept, h));
560
+ if (added.length === 0)
561
+ return;
562
+ await this.networkLocked(orgId, accountId, id, { mode: "allowlist", hosts: [...kept, ...added] }, undefined, { via });
563
+ }
446
564
  /**
447
565
  * The level a sandbox call in the device runs at now, for the model (legacy `device_paths`, auto
448
566
  * mode spec §4.2), the same for every provider: the kernel-internal tier (`SandboxMode`) with
@@ -554,13 +672,6 @@ let DevicesService = class DevicesService {
554
672
  });
555
673
  await oweDeviceDestroy(this.outbox, id, orgId);
556
674
  }
557
- /**
558
- * Disconnects the machine of one of the person's own dial-in devices (it must sign in
559
- * again); see {@link DialInMachines.revoke}.
560
- */
561
- async revokeMachine(orgId, accountId, id, actorTokenId) {
562
- await this.machines.revoke(orgId, accountId, id, actorTokenId);
563
- }
564
675
  /**
565
676
  * Starts one of the person's devices over with empty files (after
566
677
  * `device.files_lost`): records the request (audit), then, after the commit, enqueues the
@@ -591,8 +702,9 @@ let DevicesService = class DevicesService {
591
702
  * The person's default device in the org: the live one if any, whatever its provider's state
592
703
  * (a default whose provider is off stays the default, unavailable, never demoted or replaced),
593
704
  * else a new default (named by the UI, `name` NULL) bound to the org's default provider
594
- * ({@link DeviceProviderSelection.defaultFor}), else null (no default provider on in the org).
595
- * An existing one is read without locking.
705
+ * ({@link DeviceProviderSelection.defaultFor}), else null: no default provider on in the org, or
706
+ * a dial-in one (a machine must sign in to make its device, so nothing is created for the person;
707
+ * spec §6.4). An existing one is read without locking.
596
708
  *
597
709
  * Creating one first takes the person's membership row (`FOR SHARE`, after the org row), so an
598
710
  * offboarding that removes them cannot leave a live default behind; not a member (any more) →
@@ -605,7 +717,7 @@ let DevicesService = class DevicesService {
605
717
  if (live)
606
718
  return live.id;
607
719
  const provider = await this.selection.defaultFor(orgId);
608
- if (!provider)
720
+ if (!provider || servesDialIn(provider))
609
721
  return null;
610
722
  return this.insertDefault(orgId, accountId, provider.plugin);
611
723
  }
@@ -737,6 +849,7 @@ let DevicesService = class DevicesService {
737
849
  // whether each provider serves the org now, evaluated once per provider and request
738
850
  const providerNames = [...new Set(rows.flatMap((r) => (r.provider ? [r.provider] : [])))];
739
851
  const on = new Map(await Promise.all(providerNames.map(async (p) => [p, await this.selection.isOnInOrg(orgId, p)])));
852
+ const providerNamesOf = await this.displayNames.many(providerNames);
740
853
  // each device's sandbox, limits, its instance's pending change and its stored report
741
854
  const perDevice = new Map(await Promise.all(rows.map(async (r) => {
742
855
  const policy = await this.sandbox.devicePolicy({ orgId, deviceId: r.id });
@@ -761,6 +874,7 @@ let DevicesService = class DevicesService {
761
874
  isDefault: r.is_default,
762
875
  ownerKind: "personal",
763
876
  provider,
877
+ providerDisplayName: provider === null ? null : (providerNamesOf.get(provider) ?? null),
764
878
  dialIn: dialIn.has(r.id),
765
879
  // an instance row of another provider (never written by this kernel) is refused on use
766
880
  available: provider !== null &&
@@ -804,8 +918,8 @@ let DevicesService = class DevicesService {
804
918
  return p !== undefined && servesDialIn(p);
805
919
  }
806
920
  /**
807
- * The last {@link RECENT_POLICY_CHANGES} setting changes of each device in the org (audit rows
808
- * {@link SETTING_CHANGE_ACTIONS}), newest first, with the deciding account's display name.
921
+ * The last {@link RECENT_POLICY_CHANGES} setting changes of each device in the org (its
922
+ * `device.network_changed` audit rows), newest first, with the deciding account's display name.
809
923
  */
810
924
  async recentChanges(orgId, deviceIds) {
811
925
  const out = new Map();
@@ -815,21 +929,19 @@ let DevicesService = class DevicesService {
815
929
  .selectFrom("audit_events as a")
816
930
  .select([
817
931
  "a.target",
818
- "a.action",
819
932
  "a.at",
820
933
  "a.detail",
821
934
  "a.actor_account_id",
822
935
  sql `row_number() OVER (PARTITION BY a.target ORDER BY a.at DESC, a.id DESC)`.as("n"),
823
936
  ])
824
937
  .where("a.org_id", "=", orgId)
825
- .where("a.action", "in", [...SETTING_CHANGE_ACTIONS])
938
+ .where("a.action", "=", "device.network_changed")
826
939
  .where("a.target", "in", deviceIds);
827
940
  const rows = await this.db
828
941
  .selectFrom(ranked.as("r"))
829
942
  .leftJoin("accounts as ac", "ac.id", "r.actor_account_id")
830
943
  .select((eb) => [
831
944
  "r.target",
832
- "r.action",
833
945
  "r.at",
834
946
  "r.detail",
835
947
  "r.actor_account_id",
@@ -843,7 +955,7 @@ let DevicesService = class DevicesService {
843
955
  if (r.target === null)
844
956
  continue;
845
957
  const list = out.get(r.target) ?? [];
846
- list.push(settingChangeOf(r.action, r.at, (r.detail ?? {}), r.actor_account_id === null || r.display_name === null
958
+ list.push(settingChangeOf(r.at, (r.detail ?? {}), r.actor_account_id === null || r.display_name === null
847
959
  ? null
848
960
  : {
849
961
  id: r.actor_account_id,
@@ -926,6 +1038,12 @@ __decorate([
926
1038
  __decorate([
927
1039
  Transactional()
928
1040
  ], DevicesService.prototype, "updateIn", null);
1041
+ __decorate([
1042
+ Transactional({ propagation: "mandatory" })
1043
+ ], DevicesService.prototype, "lockNetworkAddSubject", null);
1044
+ __decorate([
1045
+ Transactional()
1046
+ ], DevicesService.prototype, "addNetworkHostsLocked", null);
929
1047
  __decorate([
930
1048
  Transactional({ propagation: "mandatory" })
931
1049
  ], DevicesService.prototype, "lockRemovalSubject", null);
@@ -955,7 +1073,8 @@ DevicesService = __decorate([
955
1073
  __param(12, Inject(PermissionFacts)),
956
1074
  __param(13, Inject(ExtensionDisplayNames)),
957
1075
  __param(14, Inject(DeviceReports)),
958
- __param(15, Inject(DialInHandlers))
1076
+ __param(15, Inject(DialInHandlers)),
1077
+ __param(16, Inject(PluginGuides))
959
1078
  ], DevicesService);
960
1079
  export { DevicesService };
961
1080
  /**
@@ -988,7 +1107,7 @@ function networkWidens(a, b) {
988
1107
  }
989
1108
  const STORED_RANK = { none: 0, allowlist: 1, open: 2 };
990
1109
  /**
991
- * Whether a cloud device's stored network setting widens from `a` to `b`, whatever the network in
1110
+ * Whether a device's stored network setting widens from `a` to `b`, whatever the network in
992
1111
  * effect now (a stored widening takes effect when a ceiling opens later): a wider mode, where
993
1112
  * following the org (null) counts as wider than any explicit mode; or an explicit host list
994
1113
  * replaced by none of its own (follow the org's hosts) or gaining a host.
@@ -1004,7 +1123,7 @@ export function storedNetworkWidens(a, b) {
1004
1123
  return b.hosts.some((h) => !a.hosts.some((p) => coversHost(p.toLowerCase(), h.toLowerCase())));
1005
1124
  }
1006
1125
  /**
1007
- * What a cloud device's new network takes from admitted or started work (`next`: its sandbox
1126
+ * What a device's new network takes from admitted or started work (`next`: its sandbox
1008
1127
  * after the change): open-network work once it is no longer open, and allowlist work naming a host
1009
1128
  * its new hosts no longer cover, unless an independent grant the new per-call ceiling still allows
1010
1129
  * holds it (`hostsNarrowed`).
@@ -1028,31 +1147,7 @@ function networkLayerText(layer) {
1028
1147
  return "its owner";
1029
1148
  }
1030
1149
  }
1031
- /** The audit actions a device's recent setting changes list. */
1032
- const SETTING_CHANGE_ACTIONS = [
1033
- "device.policy_changed",
1034
- "device.policy_unknown",
1035
- "device.policy_failed",
1036
- "device.owner_ceiling_changed",
1037
- "device.network_changed",
1038
- ];
1039
- /** One side of an audited ceiling change; null when the row does not carry a readable one. */
1040
- function ceilingFactsOf(v) {
1041
- if (typeof v !== "object" || v === null)
1042
- return null;
1043
- const o = v;
1044
- // rows written before the rename carry the same fact as `fullAccess`
1045
- const outside = typeof o.outsideSandbox === "boolean" ? o.outsideSandbox : o.fullAccess;
1046
- if (typeof outside !== "boolean")
1047
- return null;
1048
- const reach = o.restrictedProjectReach;
1049
- return {
1050
- outsideSandbox: outside,
1051
- ...((reach === "workspace" || reach === "os-user") && { restrictedProjectReach: reach }),
1052
- ...((o.network === "open" || o.network === "allowlist") && { network: o.network }),
1053
- };
1054
- }
1055
- /** One side of an audited cloud network change. */
1150
+ /** One side of an audited network change. */
1056
1151
  function networkSettingOf(v) {
1057
1152
  const o = (typeof v === "object" && v !== null ? v : {});
1058
1153
  const mode = o.mode;
@@ -1061,45 +1156,15 @@ function networkSettingOf(v) {
1061
1156
  hosts: Array.isArray(o.hosts) ? o.hosts.filter((h) => typeof h === "string") : [],
1062
1157
  };
1063
1158
  }
1064
- /** One audit row of {@link SETTING_CHANGE_ACTIONS} as a {@link DeviceSettingChangeView}. */
1065
- function settingChangeOf(action, at, d, by) {
1066
- const hosts = (v) => Array.isArray(v) ? v.filter((h) => typeof h === "string") : [];
1067
- const via = d.via === "im"
1068
- ? "im"
1069
- : d.via === "device"
1070
- ? "device"
1071
- : d.via === "token"
1072
- ? "token"
1073
- : d.via === "agent"
1074
- ? "agent"
1075
- : "web";
1076
- const base = { at: at.toISOString(), add: [], remove: [], ceiling: null, network: null, by, via };
1077
- if (action === "device.owner_ceiling_changed") {
1078
- const to = ceilingFactsOf(d.to);
1079
- return {
1080
- ...base,
1081
- kind: "ceiling",
1082
- ceiling: to === null ? null : { from: ceilingFactsOf(d.from), to },
1083
- outcome: "applied",
1084
- };
1085
- }
1086
- if (action === "device.network_changed")
1087
- return {
1088
- ...base,
1089
- kind: "network",
1090
- network: { from: networkSettingOf(d.from), to: networkSettingOf(d.to) },
1091
- outcome: "applied",
1092
- };
1159
+ /** One `device.network_changed` audit row as a {@link DeviceSettingChangeView}. */
1160
+ function settingChangeOf(at, d, by) {
1161
+ const via = d.via === "im" || d.via === "token" || d.via === "agent" ? d.via : "web";
1093
1162
  return {
1094
- ...base,
1095
- kind: "policy",
1096
- add: hosts(d.add),
1097
- remove: hosts(d.remove),
1098
- outcome: action === "device.policy_unknown"
1099
- ? "unknown"
1100
- : action === "device.policy_failed"
1101
- ? "failed"
1102
- : "applied",
1163
+ at: at.toISOString(),
1164
+ kind: "network",
1165
+ network: { from: networkSettingOf(d.from), to: networkSettingOf(d.to) },
1166
+ by,
1167
+ via,
1103
1168
  };
1104
1169
  }
1105
1170
  /**
@@ -8,7 +8,7 @@ export interface DeviceProjectScope {
8
8
  /**
9
9
  * The home its provider last reported (`devices.report.home`): projects are relative to it and
10
10
  * the kernel narrows no path below it (where a project may lie is the provider's rule); null
11
- * when the provider reports none, and projects stay in the workspace.
11
+ * when the provider reports none, and the workspace is the base.
12
12
  */
13
13
  home: string | null;
14
14
  supported: boolean;
@@ -16,16 +16,14 @@ export interface DeviceProjectScope {
16
16
  type Scope = DeviceProjectScope;
17
17
  /** The base a relative path resolves against (project root §4.2): the home, else the workspace. */
18
18
  export declare const baseOf: (s: Scope, workspace?: string) => string;
19
- /**
20
- * `path` lies inside what the kernel lets the scope's projects reach: anywhere when the provider
21
- * reports a home (the provider refuses what it will not serve), else inside the workspace (as the
22
- * held instance reports it when given).
23
- */
24
- export declare const withinMode: (s: Scope, path: string, workspace?: string) => boolean;
25
19
  export declare const nameInvalid: (name: string) => ApiError;
26
20
  export declare const nameTaken: (name: string) => ApiError;
27
21
  export declare const projectNotFound: (name: string) => ApiError;
28
- export declare const outsideMode: (path: string, mode: SandboxMode) => ApiError;
22
+ /**
23
+ * A path outside what the device lets a project reach: the device's browse scope refused it, or
24
+ * the resolved path is not one a device can hold.
25
+ */
26
+ export declare const outsideMode: (path: string) => ApiError;
29
27
  export declare const tooBroad: (path: string) => ApiError;
30
28
  /** A device-supplied or person-supplied string inside a message, bounded. */
31
29
  export declare function clipped(s: string, max?: number): string;
@@ -1,20 +1,14 @@
1
1
  import { ApiError } from "../errors.js";
2
2
  /** The base a relative path resolves against (project root §4.2): the home, else the workspace. */
3
3
  export const baseOf = (s, workspace = s.workspace) => s.home ?? workspace;
4
- /**
5
- * `path` lies inside what the kernel lets the scope's projects reach: anywhere when the provider
6
- * reports a home (the provider refuses what it will not serve), else inside the workspace (as the
7
- * held instance reports it when given).
8
- */
9
- export const withinMode = (s, path, workspace = s.workspace) => s.home !== null ||
10
- path === workspace ||
11
- path.startsWith(workspace === "/" ? "/" : `${workspace}/`);
12
4
  export const nameInvalid = (name) => new ApiError("device.project_name_invalid", `"${clipped(name)}" is not a valid project name: use 1-64 characters, not . or .., without / or control characters, and without leading or trailing spaces`);
13
5
  export const nameTaken = (name) => new ApiError("device.project_name_taken", `This device already has a project named "${clipped(name)}"; pick another name`);
14
6
  export const projectNotFound = (name) => new ApiError("device.project_not_found", `This device has no project named "${clipped(name)}"`);
15
- export const outsideMode = (path, mode) => new ApiError("device.project_outside_mode", mode === "sandbox"
16
- ? `${clipped(path)} is outside the device's workspace, the only directory it can read in sandbox mode`
17
- : `${clipped(path)} is outside the device's workspace, the only directory a cloud device can read`);
7
+ /**
8
+ * A path outside what the device lets a project reach: the device's browse scope refused it, or
9
+ * the resolved path is not one a device can hold.
10
+ */
11
+ export const outsideMode = (path) => new ApiError("device.project_outside_mode", `${clipped(path)} is outside what the device lets a project reach; pick a directory inside its base`);
18
12
  export const tooBroad = (path) => new ApiError("device.project_path_too_broad", `${clipped(path)} holds the owner's home directory (or other people's): pick the project's own directory, the home or below it`);
19
13
  /** A device-supplied or person-supplied string inside a message, bounded. */
20
14
  export function clipped(s, max = 200) {
@@ -12,7 +12,7 @@ import { type DeviceAuthorizeBody, type DeviceConfirmBody, type DeviceProvidersQ
12
12
  * - `POST /authorize { name, os, arch, programVersion, protocol }` → `{ deviceCode, userCode,
13
13
  * verificationUri, verificationUriComplete, interval, expiresIn }` (`device-authorize-ip`);
14
14
  * - `POST /token { deviceCode }` → `{ credential, orgId, deviceId, connectUrl,
15
- * reconnectGraceSeconds, maxFrameBytes, outsideSandbox }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
15
+ * reconnectGraceSeconds, maxFrameBytes, outsideSandbox, deviceName, orgName }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
16
16
  * `device_sign_in.denied` / `device_sign_in.expired` (`device-token-ip`).
17
17
  *
18
18
  * The person's routes need a web session (the confirmation page `/device`); each try of a user
@@ -24,7 +24,7 @@ const CODE_THROTTLER = ["device-code-account"];
24
24
  * - `POST /authorize { name, os, arch, programVersion, protocol }` → `{ deviceCode, userCode,
25
25
  * verificationUri, verificationUriComplete, interval, expiresIn }` (`device-authorize-ip`);
26
26
  * - `POST /token { deviceCode }` → `{ credential, orgId, deviceId, connectUrl,
27
- * reconnectGraceSeconds, maxFrameBytes, outsideSandbox }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
27
+ * reconnectGraceSeconds, maxFrameBytes, outsideSandbox, deviceName, orgName }` once, else `device_sign_in.authorization_pending` / `device_sign_in.slow_down` /
28
28
  * `device_sign_in.denied` / `device_sign_in.expired` (`device-token-ip`).
29
29
  *
30
30
  * The person's routes need a web session (the confirmation page `/device`); each try of a user
@@ -63,6 +63,10 @@ export interface DeviceGrant extends Grant {
63
63
  * does not allow it, even when the machine's owner ceiling does.
64
64
  */
65
65
  outsideSandbox: "allowed" | "off";
66
+ /** The device's name (`devices.name`; null when it has none), for `capybara-device status`. */
67
+ deviceName: string | null;
68
+ /** The organization's name (`orgs.name`), for `capybara-device status`. */
69
+ orgName: string;
66
70
  }
67
71
  /** A user code as typed → `XXXX-XXXX`, or null when it cannot be one. */
68
72
  export declare function normalizeUserCode(input: string): string | null;
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { randomBytes } from "node:crypto";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { DevicesService, dialInProviderUnavailable } from "../devices/devices.service.js";
13
+ import { deviceNotFound } from "../devices/errors.js";
13
14
  import { ApiError } from "../errors.js";
14
15
  import { ExtensionDisplayNames } from "../extensions/display-name.js";
15
16
  import { audit } from "../identity/audit.js";
@@ -22,7 +23,6 @@ import { KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
22
23
  import { authorizeOrgAction } from "../orgs/org.guard.js";
23
24
  import { readOrgSettings } from "../orgs/settings.service.js";
24
25
  import { allowedDeviceMode, readDeploymentDevicePolicy } from "../sandbox/modes.js";
25
- import { deviceNotFound } from "../sandbox/sandbox.service.js";
26
26
  import { DialInHandlers } from "./handlers.js";
27
27
  import { DialInMachines } from "./machines.js";
28
28
  /** The 20 consonants a user code is made of (no vowels: no words; no look-alike letters). */
@@ -188,9 +188,21 @@ let DialInAuthService = class DialInAuthService {
188
188
  case "approved": {
189
189
  const grant = JSON.parse(r[1]);
190
190
  const dialIn = this.config.get().devices.dialIn;
191
- const [deployment, settings] = await Promise.all([
191
+ const [deployment, settings, device, org] = await Promise.all([
192
192
  readDeploymentDevicePolicy(this.db.db, this.config),
193
193
  readOrgSettings(this.db.db, grant.orgId),
194
+ this.db.db
195
+ .selectFrom("devices")
196
+ .select("name")
197
+ .where("org_id", "=", grant.orgId)
198
+ .where("id", "=", grant.deviceId)
199
+ .executeTakeFirst(),
200
+ this.db.db
201
+ .selectFrom("orgs")
202
+ .select("name")
203
+ .where("id", "=", grant.orgId)
204
+ // the grant's org exists: the device row it names references it
205
+ .executeTakeFirstOrThrow(),
194
206
  ]);
195
207
  return {
196
208
  ...grant,
@@ -200,6 +212,8 @@ let DialInAuthService = class DialInAuthService {
200
212
  outsideSandbox: allowedDeviceMode(deployment.fullAccess, settings.outsideSandbox) === "auto"
201
213
  ? "allowed"
202
214
  : "off",
215
+ deviceName: device?.name ?? null,
216
+ orgName: org.name,
203
217
  };
204
218
  }
205
219
  case "slow_down":
@@ -9,7 +9,7 @@ import { DialInRelay } from "./relay.js";
9
9
  export declare const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
10
10
  /**
11
11
  * Why a machine was revoked, for the machine and for the provider (`onClose`): `revoked`
12
- * (disconnected, signed out, or a sign-in whose credential never reached its program) or `deleted`
12
+ * (signed out, or a sign-in whose credential never reached its program) or `deleted`
13
13
  * (its device was deleted), both told to stop first; `replaced` (the device signed in from
14
14
  * another machine): no stop, which could reach the replacement instead, and its connection
15
15
  * closes as replaced (4002).
@@ -115,9 +115,10 @@ export declare class DialInMachines {
115
115
  touch(machineId: string): Promise<void>;
116
116
  /**
117
117
  * Disconnects the machine of one of the person's own live dial-in devices, whatever its
118
- * provider (`DELETE /orgs/:orgId/devices/:id/machine`): revokes it and audits
119
- * `device.machine_revoked`. Anyone else's device, a cloud one or a missing one →
120
- * `device.not_found`; no machine connected is a no-op.
118
+ * provider: revokes it and audits `device.machine_revoked`. No route calls it (the device page
119
+ * no longer disconnects a machine; deleting the device revokes it, {@link revokeActive}); the
120
+ * kernel tests revoke a connected machine with it. Anyone else's device, a cloud one or a
121
+ * missing one → `device.not_found`; no machine connected is a no-op.
121
122
  */
122
123
  revoke(orgId: string, accountId: string, deviceId: string, actorTokenId?: string): Promise<void>;
123
124
  /**