@capybara-hq/kernel 0.1.0-rc.53 → 0.1.0-rc.55

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 (190) hide show
  1. package/dist/admin/admin.schemas.d.ts +11 -1
  2. package/dist/catalog/catalog.module.js +1 -1
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/catalog/requests.service.d.ts +5 -5
  5. package/dist/catalog/requests.service.js +9 -9
  6. package/dist/channels/cards.d.ts +4 -3
  7. package/dist/channels/cards.js +25 -16
  8. package/dist/channels/phrases.d.ts +15 -4
  9. package/dist/channels/phrases.js +15 -1
  10. package/dist/config/load.d.ts +26 -7
  11. package/dist/config/load.js +60 -9
  12. package/dist/config/permission-migration.d.ts +17 -9
  13. package/dist/config/permission-migration.js +60 -9
  14. package/dist/config/schema.d.ts +15 -1
  15. package/dist/config/schema.js +66 -11
  16. package/dist/conversations/events.d.ts +247 -5
  17. package/dist/conversations/events.js +127 -16
  18. package/dist/conversations/permission-profiles.controller.d.ts +12 -2
  19. package/dist/conversations/permission-profiles.service.d.ts +12 -2
  20. package/dist/conversations/permission-profiles.service.js +11 -4
  21. package/dist/db/kernel-schema.d.ts +18 -2
  22. package/dist/devices/device-projects.service.d.ts +1 -1
  23. package/dist/devices/device-projects.service.js +6 -6
  24. package/dist/devices/devices.controller.d.ts +10 -8
  25. package/dist/devices/devices.controller.js +14 -18
  26. package/dist/devices/devices.schemas.d.ts +5 -5
  27. package/dist/devices/devices.schemas.js +5 -5
  28. package/dist/devices/devices.service.d.ts +188 -175
  29. package/dist/devices/devices.service.js +284 -292
  30. package/dist/devices/dto.d.ts +43 -23
  31. package/dist/devices/dto.js +45 -49
  32. package/dist/devices/project-rules.d.ts +0 -10
  33. package/dist/devices/project-rules.js +0 -5
  34. package/dist/errors.d.ts +43 -19
  35. package/dist/errors.js +43 -19
  36. package/dist/evals/reconstruct.d.ts +12 -3
  37. package/dist/evals/reconstruct.js +10 -6
  38. package/dist/evals/recorded-permission-context.d.ts +6 -4
  39. package/dist/evals/recorded-permission-context.js +15 -9
  40. package/dist/evals/run-replay.d.ts +6 -1
  41. package/dist/evals/run-replay.js +7 -2
  42. package/dist/evals/worker.js +3 -1
  43. package/dist/http/api.module.js +8 -0
  44. package/dist/http/app.js +9 -0
  45. package/dist/http/meta.controller.d.ts +33 -0
  46. package/dist/http/meta.controller.js +72 -0
  47. package/dist/identity/app-auth.controller.d.ts +25 -0
  48. package/dist/identity/app-auth.controller.js +64 -0
  49. package/dist/identity/app-auth.d.ts +66 -0
  50. package/dist/identity/app-auth.js +203 -0
  51. package/dist/identity/app-auth.schemas.d.ts +47 -0
  52. package/dist/identity/app-auth.schemas.js +43 -0
  53. package/dist/identity/identity.module.d.ts +1 -1
  54. package/dist/identity/identity.module.js +4 -1
  55. package/dist/identity/settings.d.ts +45 -18
  56. package/dist/identity/settings.js +151 -51
  57. package/dist/infra/config/kernel-config.service.d.ts +1 -1
  58. package/dist/infra/config/kernel-config.service.js +19 -5
  59. package/dist/infra/outbox/registry.d.ts +14 -0
  60. package/dist/infra/outbox/registry.js +15 -0
  61. package/dist/infra/throttler/named-throttlers.d.ts +3 -2
  62. package/dist/infra/throttler/named-throttlers.js +14 -2
  63. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  64. package/dist/local-devices/device-auth.controller.js +1 -1
  65. package/dist/local-devices/device-auth.d.ts +4 -4
  66. package/dist/local-devices/device-auth.js +1 -1
  67. package/dist/local-devices/device-policy.service.d.ts +18 -9
  68. package/dist/local-devices/device-policy.service.js +21 -61
  69. package/dist/local-devices/device-routes.d.ts +3 -1
  70. package/dist/local-devices/device-routes.js +15 -4
  71. package/dist/local-devices/instance-bindings.js +5 -2
  72. package/dist/local-devices/local-device-gateway.d.ts +2 -2
  73. package/dist/local-devices/local-device-gateway.js +3 -3
  74. package/dist/local-devices/local-device-provider.d.ts +4 -4
  75. package/dist/local-devices/local-device-provider.js +23 -9
  76. package/dist/local-devices/local-devices.module.d.ts +1 -1
  77. package/dist/local-devices/local-devices.module.js +1 -1
  78. package/dist/local-devices/machines.d.ts +40 -16
  79. package/dist/local-devices/machines.js +89 -61
  80. package/dist/local-devices/owner-report.d.ts +16 -14
  81. package/dist/local-devices/owner-report.js +24 -30
  82. package/dist/local-devices/owner-reports.js +26 -8
  83. package/dist/local-devices/policy-summary.d.ts +25 -44
  84. package/dist/local-devices/policy-summary.js +26 -71
  85. package/dist/local-devices/relay.d.ts +6 -6
  86. package/dist/local-devices/relay.js +10 -8
  87. package/dist/net/public-address.d.ts +1 -1
  88. package/dist/net/public-address.js +5 -2
  89. package/dist/orgs/device-network-setting.d.ts +82 -0
  90. package/dist/orgs/device-network-setting.js +142 -0
  91. package/dist/orgs/settings.service.d.ts +103 -66
  92. package/dist/orgs/settings.service.js +201 -137
  93. package/dist/overrides.d.ts +5 -1
  94. package/dist/overrides.js +2 -0
  95. package/dist/platform/exclusions.js +24 -1
  96. package/dist/platform/operation.js +2 -2
  97. package/dist/platform/ops/admin.ops.js +20 -11
  98. package/dist/platform/ops/devices.ops.js +70 -5
  99. package/dist/platform/ops/org-settings.ops.js +10 -6
  100. package/dist/platform/ops/orgs.ops.js +2 -1
  101. package/dist/platform/ops/platform-icons.ops.d.ts +14 -0
  102. package/dist/platform/ops/platform-icons.ops.js +117 -0
  103. package/dist/platform/platform-ops.module.d.ts +2 -1
  104. package/dist/platform/platform-ops.module.js +3 -0
  105. package/dist/platform/route-schemas.js +3 -0
  106. package/dist/runtime/context/permission-profile.d.ts +17 -8
  107. package/dist/runtime/context/permission-profile.js +126 -45
  108. package/dist/runtime/maintenance.d.ts +5 -2
  109. package/dist/runtime/maintenance.js +15 -4
  110. package/dist/runtime/permission-context.service.d.ts +1 -1
  111. package/dist/runtime/permission-context.service.js +5 -3
  112. package/dist/runtime/project/knowledge.d.ts +5 -4
  113. package/dist/runtime/project/knowledge.js +2 -1
  114. package/dist/runtime/project/knowledge.service.js +16 -13
  115. package/dist/sandbox/cloud-permission-snapshot.js +22 -3
  116. package/dist/sandbox/device-sandbox-settings.d.ts +230 -0
  117. package/dist/sandbox/device-sandbox-settings.js +470 -0
  118. package/dist/sandbox/device-sandbox.d.ts +187 -0
  119. package/dist/sandbox/device-sandbox.js +236 -0
  120. package/dist/sandbox/held-operations.js +15 -7
  121. package/dist/sandbox/modes.d.ts +49 -24
  122. package/dist/sandbox/modes.js +27 -19
  123. package/dist/sandbox/operation-authority-types.d.ts +6 -5
  124. package/dist/sandbox/operation-authority-types.js +7 -8
  125. package/dist/sandbox/operation-authority.d.ts +23 -9
  126. package/dist/sandbox/operation-authority.js +179 -97
  127. package/dist/sandbox/permission-auto-grants.d.ts +42 -0
  128. package/dist/sandbox/permission-auto-grants.js +145 -0
  129. package/dist/sandbox/permission-call-grants.d.ts +12 -4
  130. package/dist/sandbox/permission-call-grants.js +84 -35
  131. package/dist/sandbox/permission-call-grants.module.js +10 -3
  132. package/dist/sandbox/permission-call-types.d.ts +39 -5
  133. package/dist/sandbox/permission-ceiling-writes.d.ts +29 -3
  134. package/dist/sandbox/permission-ceiling-writes.js +38 -4
  135. package/dist/sandbox/permission-config-publication.d.ts +44 -2
  136. package/dist/sandbox/permission-config-publication.js +230 -59
  137. package/dist/sandbox/permission-context-types.d.ts +2 -2
  138. package/dist/sandbox/permission-facts.d.ts +144 -15
  139. package/dist/sandbox/permission-facts.js +258 -70
  140. package/dist/sandbox/permission-runtime-reports.d.ts +5 -4
  141. package/dist/sandbox/permission-runtime-reports.js +19 -29
  142. package/dist/sandbox/review/classifier.d.ts +8 -0
  143. package/dist/sandbox/review/classifier.js +10 -0
  144. package/dist/sandbox/review/permission-candidate.d.ts +69 -5
  145. package/dist/sandbox/review/permission-candidate.js +153 -30
  146. package/dist/sandbox/review/review.service.d.ts +19 -3
  147. package/dist/sandbox/review/review.service.js +59 -11
  148. package/dist/sandbox/review/rules.js +23 -3
  149. package/dist/sandbox/sandbox.service.d.ts +29 -11
  150. package/dist/sandbox/sandbox.service.js +51 -26
  151. package/dist/skills/invoke.js +3 -2
  152. package/dist/themes/platform-icon-objects.d.ts +51 -0
  153. package/dist/themes/platform-icon-objects.js +113 -0
  154. package/dist/themes/platform-icon-public.controller.d.ts +17 -0
  155. package/dist/themes/platform-icon-public.controller.js +58 -0
  156. package/dist/themes/platform-icon.controller.d.ts +22 -0
  157. package/dist/themes/platform-icon.controller.js +65 -0
  158. package/dist/themes/platform-icon.schemas.d.ts +48 -0
  159. package/dist/themes/platform-icon.schemas.js +53 -0
  160. package/dist/themes/platform-icon.service.d.ts +83 -0
  161. package/dist/themes/platform-icon.service.js +301 -0
  162. package/dist/themes/themes.module.d.ts +4 -1
  163. package/dist/themes/themes.module.js +9 -4
  164. package/dist/tools/approvals.service.d.ts +26 -116
  165. package/dist/tools/approvals.service.js +42 -346
  166. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  167. package/dist/tools/builtins/sandbox/bash.js +80 -28
  168. package/dist/tools/builtins/sandbox/common.d.ts +39 -14
  169. package/dist/tools/builtins/sandbox/common.js +47 -24
  170. package/dist/tools/builtins/sandbox/deliver.js +7 -4
  171. package/dist/tools/builtins/skill-load.d.ts +2 -2
  172. package/dist/tools/builtins/skill-load.js +4 -3
  173. package/dist/tools/device-op-resolver.d.ts +4 -10
  174. package/dist/tools/device-op-resolver.js +8 -19
  175. package/dist/tools/network-asks.d.ts +52 -15
  176. package/dist/tools/network-asks.js +55 -25
  177. package/dist/tools/pipeline.d.ts +26 -14
  178. package/dist/tools/pipeline.js +144 -61
  179. package/dist/tools/registry.d.ts +6 -0
  180. package/dist/tools/tools.module.js +1 -1
  181. package/package.json +4 -4
  182. package/src/migrations/0164_platform_icons.sql +10 -0
  183. package/src/migrations/0165_device_network_columns.sql +50 -0
  184. package/src/migrations/0166_permission_grant_full_access.sql +17 -0
  185. package/src/migrations/0167_device_network_backfill.sql +32 -0
  186. package/src/migrations/0168_binding_installed_connection.sql +6 -0
  187. package/dist/orgs/cloud-network-setting.d.ts +0 -33
  188. package/dist/orgs/cloud-network-setting.js +0 -47
  189. package/dist/sandbox/platform-full-access.d.ts +0 -110
  190. package/dist/sandbox/platform-full-access.js +0 -198
@@ -1,47 +0,0 @@
1
- import { validateAllowHost } from "@capybara-hq/plugin-sdk";
2
- import { z } from "zod";
3
- /** The org cloud-network allowlist's host limit. */
4
- export const ORG_SANDBOX_ALLOW_HOSTS_MAX = 200;
5
- /** One host list of the org's cloud network: at most {@link ORG_SANDBOX_ALLOW_HOSTS_MAX} valid, unique hosts. */
6
- const orgHostList = (name) => z
7
- .array(z.string())
8
- .max(ORG_SANDBOX_ALLOW_HOSTS_MAX)
9
- .superRefine((hosts, ctx) => {
10
- hosts.forEach((h, i) => {
11
- for (const message of validateAllowHost(h)) {
12
- ctx.addIssue({ code: "custom", path: [i], message: `${h}: ${message}` });
13
- }
14
- });
15
- if (new Set(hosts).size !== hosts.length) {
16
- ctx.addIssue({ code: "custom", message: `${name} must not contain duplicates` });
17
- }
18
- })
19
- .optional();
20
- /**
21
- * The org's sandbox-mode network (org egress ceiling spec §D1), stored as a delta over the
22
- * platform's `sandbox.limits.allowHosts`, never a copy of it, so platform changes keep reaching the
23
- * org:
24
- * - `mode`: the cloud network of a cloud device in sandbox mode, `open` (any public host; loopback,
25
- * private and cloud metadata addresses are blocked outside the container) or `allowlist`; absent
26
- * follows the platform's default (open). `sandbox.limits.orgHosts: within` makes it the allowlist.
27
- * - `base`: `platform` (the default: start from the platform's list) or `none` (only the org's own
28
- * hosts).
29
- * - `extraHosts`: hosts the org adds (ignored outside the platform list under `within`).
30
- * - `excludedHosts`: platform entries the org drops (exact entries; any host is accepted, since the
31
- * platform may drop an entry later).
32
- * The effective hosts ({@link orgEffectiveHosts} in `sandbox/modes.ts`) are also the ceiling a local
33
- * device in sandbox mode reaches (the device intersects them with its own list).
34
- */
35
- export const CloudNetworkSettingSchema = z
36
- .object({
37
- mode: z.enum(["open", "allowlist"]).optional(),
38
- base: z.enum(["platform", "none"]).optional(),
39
- extraHosts: orgHostList("extraHosts"),
40
- excludedHosts: orgHostList("excludedHosts"),
41
- })
42
- .strict();
43
- /** What an invalid stored `cloudNetwork` reads as: the allowlist with no host (never wider). */
44
- export const invalidCloudNetwork = () => ({
45
- mode: "allowlist",
46
- base: "none",
47
- });
@@ -1,110 +0,0 @@
1
- import { z } from "zod";
2
- import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
- import type { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
- import type { KernelLogger } from "../log.js";
5
- /**
6
- * The platform's Full permission switch (permission runtime cutover B1, replacing the auto-mode
7
- * switch): whether a device's owner ceiling may allow Full permission. It is both a startup config
8
- * field (`devices.fullAccess`) and a deployment setting ({@link DEVICES_FULL_ACCESS_SETTING}), read
9
- * live at every use: environment > config file / Nacos > the super admin's choice in the admin
10
- * console > {@link DEVICES_FULL_ACCESS_DEFAULT}. A field set in the startup config is read-only in
11
- * the admin console. An invalid stored value reads as `off` with a warning (fail closed): a value
12
- * nobody could set must never widen a device.
13
- */
14
- export type FullAccessPermission = "allowed" | "off";
15
- /** The `deployment_settings` key of the super admin's choice. */
16
- export declare const DEVICES_FULL_ACCESS_SETTING = "devicesFullAccess";
17
- /**
18
- * The key the auto-mode switch was stored under. Only the one-time conversion in the permission
19
- * configuration publication reads it ({@link convertStoredPermissionKeys}).
20
- */
21
- export declare const LEGACY_DEVICES_AUTO_MODE_SETTING = "devicesAutoMode";
22
- /** What a deployment with neither the startup config nor the stored choice says: allowed. */
23
- export declare const DEVICES_FULL_ACCESS_DEFAULT: FullAccessPermission;
24
- /** The stored choice: `permission` absent follows the default. */
25
- export declare const DevicesFullAccessStoredSchema: z.ZodObject<{
26
- permission: z.ZodOptional<z.ZodEnum<{
27
- allowed: "allowed";
28
- off: "off";
29
- }>>;
30
- }, z.core.$strict>;
31
- export type DevicesFullAccessStored = z.infer<typeof DevicesFullAccessStoredSchema>;
32
- /**
33
- * A change of the stored choice (`PUT /api/v1/admin/settings` `devicesFullAccess`): `permission:
34
- * null` clears it, back to {@link DEVICES_FULL_ACCESS_DEFAULT}.
35
- */
36
- export declare const DEVICES_FULL_ACCESS_PATCH: z.ZodObject<{
37
- permission: z.ZodNullable<z.ZodEnum<{
38
- allowed: "allowed";
39
- off: "off";
40
- }>>;
41
- }, z.core.$strict>;
42
- export type DevicesFullAccessPatch = z.infer<typeof DEVICES_FULL_ACCESS_PATCH>;
43
- /** Where the effective switch comes from. */
44
- export type DevicesFullAccessSource = "env" | "file" | "nacos" | "db" | "default";
45
- /** The admin console's view: the effective permission and where it comes from. */
46
- export interface DevicesFullAccessView {
47
- permission: FullAccessPermission;
48
- source: DevicesFullAccessSource;
49
- }
50
- /**
51
- * Parses a stored choice: missing -> `{}`; invalid -> `{ permission: "off" }` with a warning,
52
- * narrower, never wider.
53
- */
54
- export declare function parseStoredDevicesFullAccess(value: unknown, log?: Pick<KernelLogger, "warn">): DevicesFullAccessStored;
55
- /**
56
- * Parses a stored old auto-mode choice into the new shape: `{ mode }` maps to `{ permission }`, an
57
- * empty choice stays empty, an invalid one becomes an explicit `off` with a warning, never absent.
58
- */
59
- export declare function parseLegacyStoredDevicesAutoMode(value: unknown, log?: Pick<KernelLogger, "warn">): DevicesFullAccessStored;
60
- /** The stored choice with `patch` applied (`permission: null` clears it). */
61
- export declare function applyDevicesFullAccessPatch(_stored: DevicesFullAccessStored, patch: DevicesFullAccessPatch): DevicesFullAccessStored;
62
- /**
63
- * The effective switch and its source, pure (the reader below adds the database read). The startup
64
- * config field is optional and has no schema default, so a defined `configured` value means the
65
- * config source (environment, file or Nacos) sets it: it wins over the stored choice.
66
- */
67
- export declare function resolveDevicesFullAccess(configured: FullAccessPermission | undefined, configSource: Exclude<DevicesFullAccessSource, "db" | "default"> | undefined, stored: DevicesFullAccessStored): DevicesFullAccessView;
68
- /**
69
- * The narrower of two stored choices: `off` when either says off; otherwise an explicit value
70
- * beats an absent one only when it is narrower, so two non-off choices read as `a`.
71
- */
72
- export declare const narrowerStoredFullAccess: (a: DevicesFullAccessStored, b: DevicesFullAccessStored) => DevicesFullAccessStored;
73
- /**
74
- * The stored choice, read live (in the caller's transaction when there is one). It reads both
75
- * keys and takes the narrower (fail closed): until the permission configuration publication
76
- * converts an old `devicesAutoMode` ({@link convertStoredPermissionKeys}; a mismatch window
77
- * before activation keeps it), its off is never lost. The old key is no public input.
78
- */
79
- export declare function readStoredDevicesFullAccess(db: KernelSchemaDb, log?: Pick<KernelLogger, "warn">): Promise<DevicesFullAccessStored>;
80
- /** Whether the old key is still stored (a write then keeps it in step until it is converted). */
81
- export declare function legacyDevicesAutoModeStored(db: KernelSchemaDb): Promise<boolean>;
82
- /**
83
- * The org's stored Full switch read over both keys (fail closed): `fullAccess` and an old
84
- * `autoMode` the publication has not converted yet (an invalid old value reads as off); the
85
- * narrower wins, an absent old key leaves `fullAccess` as it is.
86
- */
87
- export declare function narrowedOrgFullAccess(fullAccess: FullAccessPermission | undefined, rawLegacy: unknown): FullAccessPermission | undefined;
88
- /**
89
- * The platform's effective Full switch, read live from PG at every use (so a change applies on
90
- * every replica at once): see {@link resolveDevicesFullAccess}.
91
- */
92
- export declare function readDevicesFullAccess(db: KernelSchemaDb, config: Pick<KernelConfigService, "get" | "fieldSource">, log?: Pick<KernelLogger, "warn">): Promise<DevicesFullAccessView>;
93
- /**
94
- * Locks the org rows {@link convertStoredPermissionKeys} would convert, in id order, before the
95
- * caller takes the platform authority write lock: the global lock order puts the org row before
96
- * the permission authority locks (a fenced prelude holds an org row while it waits for its shared
97
- * platform lock). The conversion itself then finds its rows already held.
98
- */
99
- export declare function lockOrgsWithStoredPermissionKeys(db: KernelSchemaDb): Promise<void>;
100
- /**
101
- * The one-time conversion of the stored permission keys (B1), run only inside the permission
102
- * configuration publication transaction under the platform authority write lock (which excludes
103
- * every org and device writer; the caller locked the org rows to convert before it,
104
- * {@link lockOrgsWithStoredPermissionKeys}): the deployment setting `devicesAutoMode` becomes
105
- * `devicesFullAccess`, and every org's `autoMode` becomes `fullAccess` (absent stays absent:
106
- * the org follows the platform). Values convert exactly; an invalid old value converts to an
107
- * explicit `off` with a warning. An old and a new value that differ stop the conversion (the
108
- * caller's transaction rolls back): never pick the wider one. Idempotent.
109
- */
110
- export declare function convertStoredPermissionKeys(db: KernelSchemaDb, log?: Pick<KernelLogger, "warn">): Promise<void>;
@@ -1,198 +0,0 @@
1
- import { sql } from "kysely";
2
- import { z } from "zod";
3
- /** The `deployment_settings` key of the super admin's choice. */
4
- export const DEVICES_FULL_ACCESS_SETTING = "devicesFullAccess";
5
- /**
6
- * The key the auto-mode switch was stored under. Only the one-time conversion in the permission
7
- * configuration publication reads it ({@link convertStoredPermissionKeys}).
8
- */
9
- export const LEGACY_DEVICES_AUTO_MODE_SETTING = "devicesAutoMode";
10
- /** What a deployment with neither the startup config nor the stored choice says: allowed. */
11
- export const DEVICES_FULL_ACCESS_DEFAULT = "allowed";
12
- const Permission = z.enum(["allowed", "off"]);
13
- /** The stored choice: `permission` absent follows the default. */
14
- export const DevicesFullAccessStoredSchema = z
15
- .object({ permission: Permission.optional() })
16
- .strict();
17
- /**
18
- * A change of the stored choice (`PUT /api/v1/admin/settings` `devicesFullAccess`): `permission:
19
- * null` clears it, back to {@link DEVICES_FULL_ACCESS_DEFAULT}.
20
- */
21
- export const DEVICES_FULL_ACCESS_PATCH = z.object({ permission: Permission.nullable() }).strict();
22
- /**
23
- * Parses a stored choice: missing -> `{}`; invalid -> `{ permission: "off" }` with a warning,
24
- * narrower, never wider.
25
- */
26
- export function parseStoredDevicesFullAccess(value, log) {
27
- if (value === undefined)
28
- return {};
29
- const parsed = DevicesFullAccessStoredSchema.safeParse(value);
30
- if (parsed.success)
31
- return parsed.data;
32
- log?.warn("invalid deployment setting; it reads as Full permission off", {
33
- key: DEVICES_FULL_ACCESS_SETTING,
34
- });
35
- return { permission: "off" };
36
- }
37
- /**
38
- * Parses a stored old auto-mode choice into the new shape: `{ mode }` maps to `{ permission }`, an
39
- * empty choice stays empty, an invalid one becomes an explicit `off` with a warning, never absent.
40
- */
41
- export function parseLegacyStoredDevicesAutoMode(value, log) {
42
- const parsed = z.object({ mode: Permission.optional() }).strict().safeParse(value);
43
- if (parsed.success)
44
- return parsed.data.mode === undefined ? {} : { permission: parsed.data.mode };
45
- log?.warn("invalid deployment setting devicesAutoMode; it converts to Full permission off", {
46
- key: LEGACY_DEVICES_AUTO_MODE_SETTING,
47
- });
48
- return { permission: "off" };
49
- }
50
- /** The stored choice with `patch` applied (`permission: null` clears it). */
51
- export function applyDevicesFullAccessPatch(_stored, patch) {
52
- return patch.permission === null ? {} : { permission: patch.permission };
53
- }
54
- /**
55
- * The effective switch and its source, pure (the reader below adds the database read). The startup
56
- * config field is optional and has no schema default, so a defined `configured` value means the
57
- * config source (environment, file or Nacos) sets it: it wins over the stored choice.
58
- */
59
- export function resolveDevicesFullAccess(configured, configSource, stored) {
60
- if (configured !== undefined && configSource !== undefined) {
61
- return { permission: configured, source: configSource };
62
- }
63
- if (stored.permission !== undefined)
64
- return { permission: stored.permission, source: "db" };
65
- return { permission: DEVICES_FULL_ACCESS_DEFAULT, source: "default" };
66
- }
67
- /**
68
- * The narrower of two stored choices: `off` when either says off; otherwise an explicit value
69
- * beats an absent one only when it is narrower, so two non-off choices read as `a`.
70
- */
71
- export const narrowerStoredFullAccess = (a, b) => a.permission === "off" || b.permission === "off" ? { permission: "off" } : a;
72
- /**
73
- * The stored choice, read live (in the caller's transaction when there is one). It reads both
74
- * keys and takes the narrower (fail closed): until the permission configuration publication
75
- * converts an old `devicesAutoMode` ({@link convertStoredPermissionKeys}; a mismatch window
76
- * before activation keeps it), its off is never lost. The old key is no public input.
77
- */
78
- export async function readStoredDevicesFullAccess(db, log) {
79
- const rows = await db
80
- .selectFrom("deployment_settings")
81
- .select(["key", "value"])
82
- .where("key", "in", [DEVICES_FULL_ACCESS_SETTING, LEGACY_DEVICES_AUTO_MODE_SETTING])
83
- .execute();
84
- const current = rows.find((r) => r.key === DEVICES_FULL_ACCESS_SETTING);
85
- const legacy = rows.find((r) => r.key === LEGACY_DEVICES_AUTO_MODE_SETTING);
86
- const stored = parseStoredDevicesFullAccess(current?.value, log);
87
- return legacy === undefined
88
- ? stored
89
- : narrowerStoredFullAccess(stored, parseLegacyStoredDevicesAutoMode(legacy.value, log));
90
- }
91
- /** Whether the old key is still stored (a write then keeps it in step until it is converted). */
92
- export async function legacyDevicesAutoModeStored(db) {
93
- const row = await db
94
- .selectFrom("deployment_settings")
95
- .select("key")
96
- .where("key", "=", LEGACY_DEVICES_AUTO_MODE_SETTING)
97
- .executeTakeFirst();
98
- return row !== undefined;
99
- }
100
- /**
101
- * The org's stored Full switch read over both keys (fail closed): `fullAccess` and an old
102
- * `autoMode` the publication has not converted yet (an invalid old value reads as off); the
103
- * narrower wins, an absent old key leaves `fullAccess` as it is.
104
- */
105
- export function narrowedOrgFullAccess(fullAccess, rawLegacy) {
106
- if (rawLegacy === undefined)
107
- return fullAccess;
108
- const legacy = Permission.safeParse(rawLegacy);
109
- return fullAccess === "off" || !legacy.success || legacy.data === "off" ? "off" : fullAccess;
110
- }
111
- /**
112
- * The platform's effective Full switch, read live from PG at every use (so a change applies on
113
- * every replica at once): see {@link resolveDevicesFullAccess}.
114
- */
115
- export async function readDevicesFullAccess(db, config, log) {
116
- const stored = await readStoredDevicesFullAccess(db, log);
117
- return resolveDevicesFullAccess(config.get().devices.fullAccess, config.fieldSource("devices.fullAccess"), stored);
118
- }
119
- const asObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
120
- /** Two stored choices say the same thing. */
121
- const same = (a, b) => a.permission === b.permission;
122
- /**
123
- * Locks the org rows {@link convertStoredPermissionKeys} would convert, in id order, before the
124
- * caller takes the platform authority write lock: the global lock order puts the org row before
125
- * the permission authority locks (a fenced prelude holds an org row while it waits for its shared
126
- * platform lock). The conversion itself then finds its rows already held.
127
- */
128
- export async function lockOrgsWithStoredPermissionKeys(db) {
129
- await db
130
- .selectFrom("orgs")
131
- .select("id")
132
- .where(sql `settings ? ${"autoMode"}`)
133
- .orderBy("id")
134
- // the conversion updates only `settings`, a non-key column: the org row lock's mode (OrgLock),
135
- // which leaves foreign key checks against the org (FOR KEY SHARE) unblocked
136
- .forNoKeyUpdate()
137
- .execute();
138
- }
139
- /**
140
- * The one-time conversion of the stored permission keys (B1), run only inside the permission
141
- * configuration publication transaction under the platform authority write lock (which excludes
142
- * every org and device writer; the caller locked the org rows to convert before it,
143
- * {@link lockOrgsWithStoredPermissionKeys}): the deployment setting `devicesAutoMode` becomes
144
- * `devicesFullAccess`, and every org's `autoMode` becomes `fullAccess` (absent stays absent:
145
- * the org follows the platform). Values convert exactly; an invalid old value converts to an
146
- * explicit `off` with a warning. An old and a new value that differ stop the conversion (the
147
- * caller's transaction rolls back): never pick the wider one. Idempotent.
148
- */
149
- export async function convertStoredPermissionKeys(db, log) {
150
- const rows = await db
151
- .selectFrom("deployment_settings")
152
- .select(["key", "value"])
153
- .where("key", "in", [LEGACY_DEVICES_AUTO_MODE_SETTING, DEVICES_FULL_ACCESS_SETTING])
154
- .forUpdate()
155
- .execute();
156
- const old = rows.find((r) => r.key === LEGACY_DEVICES_AUTO_MODE_SETTING);
157
- const current = rows.find((r) => r.key === DEVICES_FULL_ACCESS_SETTING);
158
- if (old !== undefined) {
159
- const converted = parseLegacyStoredDevicesAutoMode(old.value, log);
160
- if (current !== undefined && !same(converted, parseStoredDevicesFullAccess(current.value, log)))
161
- throw new Error(`Stored deployment settings devicesAutoMode and devicesFullAccess differ; remove one of them before converting the permission configuration`);
162
- if (current === undefined)
163
- await db
164
- .insertInto("deployment_settings")
165
- .values({ key: DEVICES_FULL_ACCESS_SETTING, value: JSON.stringify(converted) })
166
- .execute();
167
- await db
168
- .deleteFrom("deployment_settings")
169
- .where("key", "=", LEGACY_DEVICES_AUTO_MODE_SETTING)
170
- .execute();
171
- }
172
- const orgs = await db
173
- .selectFrom("orgs")
174
- .select(["id", "settings"])
175
- .where(sql `settings ? ${"autoMode"}`)
176
- .orderBy("id")
177
- .forNoKeyUpdate()
178
- .execute();
179
- for (const org of orgs) {
180
- const { autoMode, ...rest } = asObject(org.settings);
181
- const parsed = Permission.safeParse(autoMode);
182
- if (!parsed.success)
183
- log?.warn("org settings: stored autoMode is invalid; it converts to fullAccess off", {
184
- orgId: org.id,
185
- });
186
- const value = parsed.success ? parsed.data : "off";
187
- if ("fullAccess" in rest) {
188
- const existing = Permission.safeParse(rest.fullAccess);
189
- if (!existing.success || existing.data !== value)
190
- throw new Error(`Org ${org.id} stores autoMode and fullAccess that differ; remove one of them before converting the permission configuration`);
191
- }
192
- await db
193
- .updateTable("orgs")
194
- .set({ settings: JSON.stringify({ ...rest, fullAccess: value }) })
195
- .where("id", "=", org.id)
196
- .execute();
197
- }
198
- }