@capybara-hq/kernel 0.1.0-rc.73 → 0.1.0-rc.75

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 (85) 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 +39 -44
  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 +75 -52
  26. package/dist/devices/devices.service.js +166 -95
  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.service.js +1 -1
  30. package/dist/dial-in/machines.d.ts +4 -15
  31. package/dist/dial-in/machines.js +4 -59
  32. package/dist/errors.d.ts +8 -3
  33. package/dist/errors.js +8 -3
  34. package/dist/extensions/admin-ops.js +2 -1
  35. package/dist/extensions/bootstrap-extra.d.ts +11 -1
  36. package/dist/extensions/bootstrap-extra.js +21 -1
  37. package/dist/extensions/bootstrap-manifest.d.ts +14 -0
  38. package/dist/extensions/bootstrap-manifest.js +23 -0
  39. package/dist/extensions/bootstrap-packages.d.ts +87 -0
  40. package/dist/extensions/bootstrap-packages.js +263 -0
  41. package/dist/extensions/bootstrap.d.ts +27 -71
  42. package/dist/extensions/bootstrap.js +85 -329
  43. package/dist/extensions/guide-places.d.ts +9 -0
  44. package/dist/extensions/guide-places.js +32 -22
  45. package/dist/extensions/plugin-guides.d.ts +20 -2
  46. package/dist/extensions/plugin-guides.js +39 -14
  47. package/dist/http/meta.controller.d.ts +0 -1
  48. package/dist/http/meta.controller.js +2 -6
  49. package/dist/identity/sso-paths.d.ts +7 -0
  50. package/dist/identity/sso-paths.js +13 -0
  51. package/dist/identity/sso.js +3 -2
  52. package/dist/index.d.ts +3 -1
  53. package/dist/index.js +3 -1
  54. package/dist/lifecycle/kernel-lifecycle.js +2 -2
  55. package/dist/platform/exclusions.js +2 -7
  56. package/dist/platform/ops/devices.ops.js +11 -7
  57. package/dist/platform/ops/setup.ops.js +1 -1
  58. package/dist/runtime/project/knowledge.service.js +6 -5
  59. package/dist/sandbox/device-sandbox.d.ts +27 -2
  60. package/dist/sandbox/device-sandbox.js +42 -5
  61. package/dist/sandbox/modes.d.ts +16 -4
  62. package/dist/sandbox/modes.js +12 -0
  63. package/dist/sandbox/operation-authority.js +3 -1
  64. package/dist/sandbox/permission-authority-lock.d.ts +6 -0
  65. package/dist/sandbox/permission-authority-lock.js +14 -0
  66. package/dist/sandbox/permission-facts.d.ts +16 -2
  67. package/dist/sandbox/permission-facts.js +20 -5
  68. package/dist/sandbox/review/permission-candidate.d.ts +12 -7
  69. package/dist/sandbox/review/permission-candidate.js +28 -7
  70. package/dist/sandbox/sandbox.service.d.ts +18 -11
  71. package/dist/sandbox/sandbox.service.js +51 -24
  72. package/dist/setup/setup-guides.service.d.ts +3 -4
  73. package/dist/setup/setup-guides.service.js +2 -5
  74. package/dist/shares/sweep.job.d.ts +2 -0
  75. package/dist/shares/sweep.job.js +3 -1
  76. package/dist/tools/approvals.service.d.ts +31 -11
  77. package/dist/tools/approvals.service.js +55 -19
  78. package/dist/tools/builtins/sandbox/common.d.ts +2 -2
  79. package/dist/tools/builtins/sandbox/common.js +2 -2
  80. package/dist/tools/network-asks.d.ts +103 -20
  81. package/dist/tools/network-asks.js +133 -18
  82. package/dist/tools/pipeline.d.ts +5 -0
  83. package/dist/tools/pipeline.js +15 -8
  84. package/package.json +3 -3
  85. 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
- import { hostGrantable } from "../sandbox/device-sandbox.js";
28
+ import { deviceSideLayer, 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 { assertAuthorityWriteHeld } 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) {
@@ -391,7 +439,7 @@ let DevicesService = class DevicesService {
391
439
  }),
392
440
  ]);
393
441
  if (to.mode === "open" && next.box.networkMode !== "open")
394
- throw new ApiError("device.network_not_allowed", `The open network is not allowed for this device: ${networkLayerText(next.box.layer.network)} limits it to ${next.box.networkCeiling === "none" ? "no network" : "the allowlist"}`);
442
+ throw new ApiError("device.network_not_allowed", `The open network is not allowed for this device: ${networkLayerText(next.box.layer.network)} limits it to ${next.box.networkCeiling === "none" ? "no network" : "the allowlist"}${deviceSideLayer(next.box.layer.network) && next.changeHint ? ` (to change this, as the device's provider says: ${next.changeHint.trim().replace(/\.$/, "")})` : ""}`);
395
443
  // a device's own list only narrows its org's hosts, whatever the network in effect now
396
444
  const outside = to.hosts.filter((h) => !next.orgHosts.some((p) => coversHost(p.toLowerCase(), h)));
397
445
  if (outside.length > 0)
@@ -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,84 @@ 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 "add
508
+ * to this device's list" (`via`: where it was decided). In a caller's transaction (the approval
509
+ * decision's) it joins it and requires the authority locks of that prelude already held there
510
+ * (platform and org shared, the device exclusive: {@link lockNetworkAddSubject} in the caller's
511
+ * ordered prelude; else it throws before locking or writing anything; the membership and device
512
+ * rows are locked again in the body); with no transaction it takes that prelude itself
513
+ * ({@link withOrderedLocks}). It takes no distributed lock. The write is a network change like `PATCH`
514
+ * ({@link networkLocked}: audited `device.network_changed` from → to, listed as a recent change,
515
+ * the device epoch bumped and the instance marked for its next use). Refuses with
516
+ * `device.network_not_allowed`, writing nothing, unless the stored network is `allowlist` with a
517
+ * host list of its own (a device following its org's hosts already allows every host its list
518
+ * could name) and every host may join that list (`deviceListAddRefusal`); its detail `reason`
519
+ * says which (`network_closed`, `follows_org`, `host_not_addable`), for the decision's copy.
520
+ * Hosts its list already covers change nothing; own hosts the org's hosts no longer cover (in
521
+ * effect nowhere) leave the list with the addition.
522
+ */
523
+ async addNetworkHostsIn(orgId, accountId, deviceId, hosts, via) {
524
+ if (currentStore() !== undefined) {
525
+ // every authority level the prelude takes: platform and org shared, the device exclusive
526
+ assertAuthorityWriteHeld({ orgId, deviceId }, "device");
527
+ await this.addNetworkHostsLocked(orgId, accountId, deviceId, hosts, via);
528
+ return;
529
+ }
530
+ await withOrderedLocks(() => this.lockNetworkSubject(orgId, accountId, deviceId), () => this.addNetworkHostsLocked(orgId, accountId, deviceId, hosts, via));
531
+ }
532
+ /** {@link addNetworkHostsIn} under the locks of its prelude (naming them again re-checks). */
533
+ async addNetworkHostsLocked(orgId, accountId, id, hosts, via) {
534
+ await this.lockOwn(orgId, accountId, id);
535
+ await this.ceilings.lock({ orgId, deviceId: id }, "device");
536
+ const row = await this.db
537
+ .selectFrom("devices")
538
+ .select(["network_mode", "network_hosts"])
539
+ .where("id", "=", id)
540
+ .executeTakeFirstOrThrow();
541
+ const own = ownNetwork(row);
542
+ if (own.networkMode === "none")
543
+ 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", [{ reason: "network_closed" }]);
544
+ if (own.networkMode !== "allowlist" || own.networkHosts.length === 0)
545
+ 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", [{ reason: "follows_org" }]);
546
+ const wanted = [...new Set(hosts.map((h) => h.toLowerCase()))];
547
+ for (const host of wanted) {
548
+ const invalid = validateAllowHost(host);
549
+ if (invalid.length > 0)
550
+ throw new ApiError("validation_failed", `${host}: ${invalid.join("; ")}`, [
551
+ { path: "hosts", message: `${host}: ${invalid.join("; ")}` },
552
+ ]);
553
+ }
554
+ const facts = await this.facts.deviceSandboxFacts(orgId, id);
555
+ for (const host of wanted) {
556
+ const why = facts.listAddRefusal(host);
557
+ if (why !== null)
558
+ throw new ApiError("device.network_not_allowed", `${host} cannot be added to this device's network list: ${why}`, [{ reason: "host_not_addable" }]);
559
+ }
560
+ const covers = (list, h) => list.some((p) => coversHost(p.toLowerCase(), h));
561
+ // own hosts the org dropped since are in effect nowhere: they would refuse the new list
562
+ const kept = own.networkHosts.filter((h) => covers(facts.orgHosts, h.toLowerCase()));
563
+ const added = wanted.filter((h) => !covers(kept, h));
564
+ if (added.length === 0)
565
+ return;
566
+ await this.networkLocked(orgId, accountId, id, { mode: "allowlist", hosts: [...kept, ...added] }, undefined, { via });
567
+ }
446
568
  /**
447
569
  * The level a sandbox call in the device runs at now, for the model (legacy `device_paths`, auto
448
570
  * mode spec §4.2), the same for every provider: the kernel-internal tier (`SandboxMode`) with
@@ -554,13 +676,6 @@ let DevicesService = class DevicesService {
554
676
  });
555
677
  await oweDeviceDestroy(this.outbox, id, orgId);
556
678
  }
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
679
  /**
565
680
  * Starts one of the person's devices over with empty files (after
566
681
  * `device.files_lost`): records the request (audit), then, after the commit, enqueues the
@@ -591,8 +706,9 @@ let DevicesService = class DevicesService {
591
706
  * The person's default device in the org: the live one if any, whatever its provider's state
592
707
  * (a default whose provider is off stays the default, unavailable, never demoted or replaced),
593
708
  * 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.
709
+ * ({@link DeviceProviderSelection.defaultFor}), else null: no default provider on in the org, or
710
+ * a dial-in one (a machine must sign in to make its device, so nothing is created for the person;
711
+ * spec §6.4). An existing one is read without locking.
596
712
  *
597
713
  * Creating one first takes the person's membership row (`FOR SHARE`, after the org row), so an
598
714
  * offboarding that removes them cannot leave a live default behind; not a member (any more) →
@@ -605,7 +721,7 @@ let DevicesService = class DevicesService {
605
721
  if (live)
606
722
  return live.id;
607
723
  const provider = await this.selection.defaultFor(orgId);
608
- if (!provider)
724
+ if (!provider || servesDialIn(provider))
609
725
  return null;
610
726
  return this.insertDefault(orgId, accountId, provider.plugin);
611
727
  }
@@ -737,6 +853,7 @@ let DevicesService = class DevicesService {
737
853
  // whether each provider serves the org now, evaluated once per provider and request
738
854
  const providerNames = [...new Set(rows.flatMap((r) => (r.provider ? [r.provider] : [])))];
739
855
  const on = new Map(await Promise.all(providerNames.map(async (p) => [p, await this.selection.isOnInOrg(orgId, p)])));
856
+ const providerNamesOf = await this.displayNames.many(providerNames);
740
857
  // each device's sandbox, limits, its instance's pending change and its stored report
741
858
  const perDevice = new Map(await Promise.all(rows.map(async (r) => {
742
859
  const policy = await this.sandbox.devicePolicy({ orgId, deviceId: r.id });
@@ -761,6 +878,7 @@ let DevicesService = class DevicesService {
761
878
  isDefault: r.is_default,
762
879
  ownerKind: "personal",
763
880
  provider,
881
+ providerDisplayName: provider === null ? null : (providerNamesOf.get(provider) ?? null),
764
882
  dialIn: dialIn.has(r.id),
765
883
  // an instance row of another provider (never written by this kernel) is refused on use
766
884
  available: provider !== null &&
@@ -804,8 +922,8 @@ let DevicesService = class DevicesService {
804
922
  return p !== undefined && servesDialIn(p);
805
923
  }
806
924
  /**
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.
925
+ * The last {@link RECENT_POLICY_CHANGES} setting changes of each device in the org (its
926
+ * `device.network_changed` audit rows), newest first, with the deciding account's display name.
809
927
  */
810
928
  async recentChanges(orgId, deviceIds) {
811
929
  const out = new Map();
@@ -815,21 +933,19 @@ let DevicesService = class DevicesService {
815
933
  .selectFrom("audit_events as a")
816
934
  .select([
817
935
  "a.target",
818
- "a.action",
819
936
  "a.at",
820
937
  "a.detail",
821
938
  "a.actor_account_id",
822
939
  sql `row_number() OVER (PARTITION BY a.target ORDER BY a.at DESC, a.id DESC)`.as("n"),
823
940
  ])
824
941
  .where("a.org_id", "=", orgId)
825
- .where("a.action", "in", [...SETTING_CHANGE_ACTIONS])
942
+ .where("a.action", "=", "device.network_changed")
826
943
  .where("a.target", "in", deviceIds);
827
944
  const rows = await this.db
828
945
  .selectFrom(ranked.as("r"))
829
946
  .leftJoin("accounts as ac", "ac.id", "r.actor_account_id")
830
947
  .select((eb) => [
831
948
  "r.target",
832
- "r.action",
833
949
  "r.at",
834
950
  "r.detail",
835
951
  "r.actor_account_id",
@@ -843,7 +959,7 @@ let DevicesService = class DevicesService {
843
959
  if (r.target === null)
844
960
  continue;
845
961
  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
962
+ list.push(settingChangeOf(r.at, (r.detail ?? {}), r.actor_account_id === null || r.display_name === null
847
963
  ? null
848
964
  : {
849
965
  id: r.actor_account_id,
@@ -926,6 +1042,12 @@ __decorate([
926
1042
  __decorate([
927
1043
  Transactional()
928
1044
  ], DevicesService.prototype, "updateIn", null);
1045
+ __decorate([
1046
+ Transactional({ propagation: "mandatory" })
1047
+ ], DevicesService.prototype, "lockNetworkAddSubject", null);
1048
+ __decorate([
1049
+ Transactional()
1050
+ ], DevicesService.prototype, "addNetworkHostsLocked", null);
929
1051
  __decorate([
930
1052
  Transactional({ propagation: "mandatory" })
931
1053
  ], DevicesService.prototype, "lockRemovalSubject", null);
@@ -955,7 +1077,8 @@ DevicesService = __decorate([
955
1077
  __param(12, Inject(PermissionFacts)),
956
1078
  __param(13, Inject(ExtensionDisplayNames)),
957
1079
  __param(14, Inject(DeviceReports)),
958
- __param(15, Inject(DialInHandlers))
1080
+ __param(15, Inject(DialInHandlers)),
1081
+ __param(16, Inject(PluginGuides))
959
1082
  ], DevicesService);
960
1083
  export { DevicesService };
961
1084
  /**
@@ -988,7 +1111,7 @@ function networkWidens(a, b) {
988
1111
  }
989
1112
  const STORED_RANK = { none: 0, allowlist: 1, open: 2 };
990
1113
  /**
991
- * Whether a cloud device's stored network setting widens from `a` to `b`, whatever the network in
1114
+ * Whether a device's stored network setting widens from `a` to `b`, whatever the network in
992
1115
  * effect now (a stored widening takes effect when a ceiling opens later): a wider mode, where
993
1116
  * following the org (null) counts as wider than any explicit mode; or an explicit host list
994
1117
  * replaced by none of its own (follow the org's hosts) or gaining a host.
@@ -1004,7 +1127,7 @@ export function storedNetworkWidens(a, b) {
1004
1127
  return b.hosts.some((h) => !a.hosts.some((p) => coversHost(p.toLowerCase(), h.toLowerCase())));
1005
1128
  }
1006
1129
  /**
1007
- * What a cloud device's new network takes from admitted or started work (`next`: its sandbox
1130
+ * What a device's new network takes from admitted or started work (`next`: its sandbox
1008
1131
  * after the change): open-network work once it is no longer open, and allowlist work naming a host
1009
1132
  * its new hosts no longer cover, unless an independent grant the new per-call ceiling still allows
1010
1133
  * holds it (`hostsNarrowed`).
@@ -1024,35 +1147,13 @@ function networkLayerText(layer) {
1024
1147
  return "the organization (an org admin)";
1025
1148
  case "provider":
1026
1149
  return "its sandbox provider";
1150
+ case "owner":
1151
+ return "the owner of the machine it runs on";
1027
1152
  default:
1028
1153
  return "its owner";
1029
1154
  }
1030
1155
  }
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. */
1156
+ /** One side of an audited network change. */
1056
1157
  function networkSettingOf(v) {
1057
1158
  const o = (typeof v === "object" && v !== null ? v : {});
1058
1159
  const mode = o.mode;
@@ -1061,45 +1162,15 @@ function networkSettingOf(v) {
1061
1162
  hosts: Array.isArray(o.hosts) ? o.hosts.filter((h) => typeof h === "string") : [],
1062
1163
  };
1063
1164
  }
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
- };
1165
+ /** One `device.network_changed` audit row as a {@link DeviceSettingChangeView}. */
1166
+ function settingChangeOf(at, d, by) {
1167
+ const via = d.via === "im" || d.via === "token" || d.via === "agent" ? d.via : "web";
1093
1168
  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",
1169
+ at: at.toISOString(),
1170
+ kind: "network",
1171
+ network: { from: networkSettingOf(d.from), to: networkSettingOf(d.to) },
1172
+ by,
1173
+ via,
1103
1174
  };
1104
1175
  }
1105
1176
  /**
@@ -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) {
@@ -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). */
@@ -3,13 +3,12 @@ import { KernelDb } from "../infra/database/kernel-db.js";
3
3
  import { TransactionHost } from "../infra/database/transaction-host.js";
4
4
  import type { KernelLogger } from "../log.js";
5
5
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
6
- import { DeviceProviders } from "../sandbox/providers.js";
7
6
  import { DialInRelay } from "./relay.js";
8
7
  /** The machine credential's prefix (`cap_dev_` plus 32 random bytes, base64url). */
9
8
  export declare const MACHINE_CREDENTIAL_PREFIX = "cap_dev_";
10
9
  /**
11
10
  * 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`
11
+ * (signed out, or a sign-in whose credential never reached its program) or `deleted`
13
12
  * (its device was deleted), both told to stop first; `replaced` (the device signed in from
14
13
  * another machine): no stop, which could reach the replacement instead, and its connection
15
14
  * closes as replaced (4002).
@@ -57,8 +56,7 @@ export declare class DialInMachines {
57
56
  private readonly bus;
58
57
  private readonly log;
59
58
  private readonly ceilings;
60
- private readonly providers;
61
- constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites, providers: Pick<DeviceProviders, "forDevice">);
59
+ constructor(db: KernelDb, txHost: TransactionHost, relay: Pick<DialInRelay, "stop">, bus: ExtensionContext["bus"], log: Pick<KernelLogger, "warn">, ceilings: PermissionCeilingWrites);
62
60
  /**
63
61
  * A new machine for the device and its credential (returned once). Revokes the
64
62
  * device's active machine first. Joins the caller's transaction (the device confirmation),
@@ -113,18 +111,11 @@ export declare class DialInMachines {
113
111
  }): Promise<void>;
114
112
  /** Marks the machine seen (a ping); writes at most once every 60 seconds. */
115
113
  touch(machineId: string): Promise<void>;
116
- /**
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.
121
- */
122
- revoke(orgId: string, accountId: string, deviceId: string, actorTokenId?: string): Promise<void>;
123
114
  /**
124
115
  * Revokes the device's active machine, if any, in the caller's transaction, and after the
125
116
  * commit tells it to stop (not when `replaced`) and closes its connection for `reason`. Returns
126
- * the revoked machine's id. Used by {@link issue} (`replaced`), {@link revoke} (`revoked`) and
127
- * the device's deletion (`deleted`).
117
+ * the revoked machine's id. Used by {@link issue} (`replaced`) and the device's deletion
118
+ * (`deleted`).
128
119
  */
129
120
  revokeActive(deviceId: string, reason: MachineRevocationReason): Promise<string | null>;
130
121
  /**
@@ -132,8 +123,6 @@ export declare class DialInMachines {
132
123
  * same post-commit disconnect as a replacement (no stop frame). True when it was active.
133
124
  */
134
125
  revokeMachine(machineId: string): Promise<boolean>;
135
- /** Whether a machine ever signed in to the device (revoked or not). */
136
- private everSignedIn;
137
126
  /** The device's active machine, or null. */
138
127
  activeFor(deviceId: string): Promise<ActiveMachine | null>;
139
128
  /**