@capybara-hq/kernel 0.1.0-rc.68 → 0.1.0-rc.69

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 (215) hide show
  1. package/dist/admin/admin.module.js +2 -0
  2. package/dist/admin/health.service.d.ts +11 -4
  3. package/dist/admin/health.service.js +33 -17
  4. package/dist/background/poll.job.js +2 -2
  5. package/dist/background/tasks.service.d.ts +5 -5
  6. package/dist/background/tasks.service.js +9 -8
  7. package/dist/catalog/marketplaces.service.d.ts +1 -1
  8. package/dist/catalog/requests.service.js +1 -1
  9. package/dist/config/schema.d.ts +1 -1
  10. package/dist/config/schema.js +9 -9
  11. package/dist/conversations/conversations.controller.d.ts +8 -3
  12. package/dist/conversations/conversations.controller.js +8 -3
  13. package/dist/conversations/conversations.service.d.ts +33 -15
  14. package/dist/conversations/conversations.service.js +60 -10
  15. package/dist/conversations/events.d.ts +21 -41
  16. package/dist/conversations/events.js +57 -31
  17. package/dist/conversations/permission-profiles.controller.d.ts +6 -4
  18. package/dist/conversations/permission-profiles.service.d.ts +6 -4
  19. package/dist/ctx/create-ctx.d.ts +20 -1
  20. package/dist/ctx/create-ctx.js +77 -6
  21. package/dist/ctx/device-provider-check.d.ts +6 -2
  22. package/dist/ctx/device-provider-check.js +17 -2
  23. package/dist/db/kernel-schema.d.ts +10 -48
  24. package/dist/devices/access.d.ts +3 -4
  25. package/dist/devices/access.js +3 -4
  26. package/dist/devices/conversation-devices.d.ts +1 -3
  27. package/dist/devices/conversation-devices.js +2 -7
  28. package/dist/devices/device-projects.service.js +24 -29
  29. package/dist/devices/device-provider-selection.d.ts +5 -6
  30. package/dist/devices/device-provider-selection.js +8 -9
  31. package/dist/devices/devices.controller.d.ts +8 -21
  32. package/dist/devices/devices.controller.js +9 -34
  33. package/dist/devices/devices.module.js +6 -4
  34. package/dist/devices/devices.schemas.d.ts +1 -5
  35. package/dist/devices/devices.schemas.js +1 -5
  36. package/dist/devices/devices.service.d.ts +84 -147
  37. package/dist/devices/devices.service.js +134 -229
  38. package/dist/devices/dto.d.ts +5 -32
  39. package/dist/devices/dto.js +5 -37
  40. package/dist/devices/errors.d.ts +6 -5
  41. package/dist/devices/errors.js +7 -8
  42. package/dist/devices/project-rules.d.ts +9 -11
  43. package/dist/devices/project-rules.js +7 -7
  44. package/dist/devices/working-root.d.ts +3 -6
  45. package/dist/devices/working-root.js +3 -8
  46. package/dist/dial-in/access.d.ts +23 -0
  47. package/dist/dial-in/access.js +64 -0
  48. package/dist/{local-devices/device-auth.controller.d.ts → dial-in/auth.controller.d.ts} +12 -6
  49. package/dist/{local-devices/device-auth.controller.js → dial-in/auth.controller.js} +30 -15
  50. package/dist/dial-in/auth.module.d.ts +7 -0
  51. package/dist/dial-in/auth.module.js +27 -0
  52. package/dist/{local-devices/device-auth.d.ts → dial-in/auth.service.d.ts} +42 -13
  53. package/dist/{local-devices/device-auth.js → dial-in/auth.service.js} +83 -32
  54. package/dist/dial-in/dial-in.module.d.ts +9 -0
  55. package/dist/dial-in/dial-in.module.js +37 -0
  56. package/dist/{local-devices → dial-in}/dto.d.ts +17 -2
  57. package/dist/{local-devices → dial-in}/dto.js +14 -2
  58. package/dist/dial-in/envelope.d.ts +95 -0
  59. package/dist/dial-in/envelope.js +89 -0
  60. package/dist/dial-in/gateway.d.ts +214 -0
  61. package/dist/{local-devices/local-device-gateway.js → dial-in/gateway.js} +337 -181
  62. package/dist/dial-in/handlers.d.ts +47 -0
  63. package/dist/dial-in/handlers.js +84 -0
  64. package/dist/dial-in/machines.d.ts +155 -0
  65. package/dist/dial-in/machines.js +383 -0
  66. package/dist/dial-in/relay.d.ts +135 -0
  67. package/dist/dial-in/relay.js +444 -0
  68. package/dist/dial-in/relay.module.d.ts +7 -0
  69. package/dist/dial-in/relay.module.js +24 -0
  70. package/dist/{local-devices/device-routes.d.ts → dial-in/routes.d.ts} +19 -11
  71. package/dist/{local-devices/device-routes.js → dial-in/routes.js} +45 -25
  72. package/dist/{local-devices → dial-in}/targets.d.ts +3 -18
  73. package/dist/{local-devices → dial-in}/targets.js +3 -48
  74. package/dist/errors.d.ts +8 -27
  75. package/dist/errors.js +8 -27
  76. package/dist/extensions/bootstrap.d.ts +5 -0
  77. package/dist/extensions/bootstrap.js +10 -1
  78. package/dist/extensions/extensions.module.js +6 -0
  79. package/dist/extensions/host.d.ts +6 -0
  80. package/dist/extensions/host.js +12 -2
  81. package/dist/extensions/permission-set.d.ts +15 -1
  82. package/dist/extensions/permission-set.js +11 -1
  83. package/dist/extensions/permission-view.d.ts +1 -1
  84. package/dist/extensions/permission-view.js +4 -1
  85. package/dist/http/api.module.js +4 -4
  86. package/dist/http/gateway-routes.d.ts +1 -1
  87. package/dist/http/gateway-routes.js +1 -1
  88. package/dist/http/meta.controller.js +1 -1
  89. package/dist/identity/settings.d.ts +1 -1
  90. package/dist/identity/settings.js +6 -8
  91. package/dist/infra/config/kernel-config.service.js +2 -2
  92. package/dist/infra/outbox/registry.d.ts +0 -14
  93. package/dist/infra/outbox/registry.js +0 -15
  94. package/dist/infra/throttler/named-throttlers.d.ts +1 -1
  95. package/dist/infra/throttler/named-throttlers.js +1 -1
  96. package/dist/kernel.module.js +0 -3
  97. package/dist/orgs/settings.service.js +5 -10
  98. package/dist/overrides.d.ts +0 -4
  99. package/dist/overrides.js +0 -2
  100. package/dist/platform/exclusions.js +5 -5
  101. package/dist/platform/ops/admin.ops.js +1 -1
  102. package/dist/platform/ops/conversations.ops.js +5 -2
  103. package/dist/platform/ops/devices.ops.js +11 -24
  104. package/dist/platform/ops/inbox.ops.js +1 -1
  105. package/dist/roles/gateway-role.d.ts +3 -3
  106. package/dist/roles/gateway-role.js +4 -4
  107. package/dist/roles/gateway.module.d.ts +1 -1
  108. package/dist/roles/gateway.module.js +5 -5
  109. package/dist/runtime/context/device-paths.d.ts +4 -1
  110. package/dist/runtime/context/permission-profile.js +5 -5
  111. package/dist/runtime/maintenance.d.ts +2 -5
  112. package/dist/runtime/maintenance.js +9 -19
  113. package/dist/runtime/project/knowledge.js +4 -5
  114. package/dist/runtime/project/knowledge.service.js +2 -1
  115. package/dist/sandbox/cloud-permission-snapshot.d.ts +1 -1
  116. package/dist/sandbox/cloud-permission-snapshot.js +1 -3
  117. package/dist/sandbox/device-reports.d.ts +74 -14
  118. package/dist/sandbox/device-reports.js +190 -33
  119. package/dist/sandbox/device-reports.module.d.ts +7 -0
  120. package/dist/sandbox/device-reports.module.js +25 -0
  121. package/dist/sandbox/device-sandbox.d.ts +39 -41
  122. package/dist/sandbox/device-sandbox.js +44 -83
  123. package/dist/sandbox/kernel-read.d.ts +2 -2
  124. package/dist/sandbox/legacy-retirement.d.ts +11 -59
  125. package/dist/sandbox/legacy-retirement.js +34 -186
  126. package/dist/sandbox/legacy-retirement.module.d.ts +2 -2
  127. package/dist/sandbox/legacy-retirement.module.js +2 -2
  128. package/dist/sandbox/managed-device-context.d.ts +16 -4
  129. package/dist/sandbox/managed-device-context.js +25 -8
  130. package/dist/sandbox/managed-device-context.module.js +4 -0
  131. package/dist/sandbox/modes.d.ts +3 -12
  132. package/dist/sandbox/modes.js +2 -14
  133. package/dist/{local-devices → sandbox}/network-grants.d.ts +2 -21
  134. package/dist/{local-devices → sandbox}/network-grants.js +4 -49
  135. package/dist/sandbox/operation-authority-types.d.ts +2 -1
  136. package/dist/sandbox/operation-authority.d.ts +6 -20
  137. package/dist/sandbox/operation-authority.js +43 -104
  138. package/dist/sandbox/operation-authority.module.js +1 -1
  139. package/dist/sandbox/operation-intents.d.ts +4 -1
  140. package/dist/sandbox/operation-intents.js +11 -2
  141. package/dist/sandbox/operation-reconcile.job.js +2 -4
  142. package/dist/sandbox/permission-availability.d.ts +6 -7
  143. package/dist/sandbox/permission-availability.js +7 -10
  144. package/dist/sandbox/permission-call-grants.d.ts +2 -1
  145. package/dist/sandbox/permission-call-grants.js +1 -7
  146. package/dist/sandbox/permission-call-types.d.ts +4 -4
  147. package/dist/sandbox/permission-ceiling-writes.d.ts +7 -23
  148. package/dist/sandbox/permission-ceiling-writes.js +8 -35
  149. package/dist/sandbox/permission-config-publication.d.ts +9 -1
  150. package/dist/sandbox/permission-config-publication.js +29 -21
  151. package/dist/sandbox/permission-context-types.d.ts +17 -10
  152. package/dist/sandbox/permission-facts.d.ts +98 -95
  153. package/dist/sandbox/permission-facts.js +160 -314
  154. package/dist/sandbox/permission-instance-writes.d.ts +23 -37
  155. package/dist/sandbox/permission-instance-writes.js +44 -121
  156. package/dist/sandbox/permission-runtime-reports.d.ts +38 -30
  157. package/dist/sandbox/permission-runtime-reports.js +105 -122
  158. package/dist/sandbox/providers.d.ts +26 -38
  159. package/dist/sandbox/providers.js +36 -18
  160. package/dist/sandbox/request-not-sent.d.ts +2 -13
  161. package/dist/sandbox/request-not-sent.js +2 -13
  162. package/dist/sandbox/review/permission-candidate.d.ts +13 -8
  163. package/dist/sandbox/review/permission-candidate.js +38 -48
  164. package/dist/sandbox/sandbox.module.js +7 -3
  165. package/dist/sandbox/sandbox.service.d.ts +49 -59
  166. package/dist/sandbox/sandbox.service.js +139 -259
  167. package/dist/schedules/fire.d.ts +15 -6
  168. package/dist/schedules/fire.js +27 -13
  169. package/dist/schedules/grant-rules.js +1 -1
  170. package/dist/schedules/scheduled-tasks.service.d.ts +0 -7
  171. package/dist/schedules/scheduled-tasks.service.js +1 -4
  172. package/dist/schedules/schedules.module.js +5 -3
  173. package/dist/skills/invoke.d.ts +1 -1
  174. package/dist/skills/invoke.js +2 -3
  175. package/dist/tools/approvals.service.d.ts +8 -5
  176. package/dist/tools/approvals.service.js +5 -5
  177. package/dist/tools/builtins/sandbox/bash.js +1 -2
  178. package/dist/tools/builtins/sandbox/common.d.ts +15 -9
  179. package/dist/tools/builtins/sandbox/common.js +37 -38
  180. package/dist/tools/network-asks.d.ts +19 -22
  181. package/dist/tools/network-asks.js +15 -21
  182. package/dist/tools/pipeline.d.ts +6 -7
  183. package/dist/tools/pipeline.js +17 -21
  184. package/dist/tools/tools.module.js +3 -7
  185. package/package.json +3 -4
  186. package/src/migrations/0177_dial_in_contract.sql +32 -0
  187. package/dist/local-devices/device-auth.module.d.ts +0 -7
  188. package/dist/local-devices/device-auth.module.js +0 -25
  189. package/dist/local-devices/device-policy.service.d.ts +0 -213
  190. package/dist/local-devices/device-policy.service.js +0 -605
  191. package/dist/local-devices/instance-bindings.d.ts +0 -82
  192. package/dist/local-devices/instance-bindings.js +0 -307
  193. package/dist/local-devices/local-device-gateway.d.ts +0 -153
  194. package/dist/local-devices/local-device-provider.d.ts +0 -122
  195. package/dist/local-devices/local-device-provider.js +0 -326
  196. package/dist/local-devices/local-devices.module.d.ts +0 -31
  197. package/dist/local-devices/local-devices.module.js +0 -100
  198. package/dist/local-devices/machines.d.ts +0 -211
  199. package/dist/local-devices/machines.js +0 -766
  200. package/dist/local-devices/owner-report.d.ts +0 -81
  201. package/dist/local-devices/owner-report.js +0 -150
  202. package/dist/local-devices/owner-reports.d.ts +0 -48
  203. package/dist/local-devices/owner-reports.js +0 -208
  204. package/dist/local-devices/policy-op-jobs.d.ts +0 -15
  205. package/dist/local-devices/policy-op-jobs.js +0 -12
  206. package/dist/local-devices/policy-summary.d.ts +0 -102
  207. package/dist/local-devices/policy-summary.js +0 -155
  208. package/dist/local-devices/relay.d.ts +0 -166
  209. package/dist/local-devices/relay.js +0 -559
  210. package/dist/tools/device-op-resolver.d.ts +0 -34
  211. package/dist/tools/device-op-resolver.js +0 -120
  212. /package/dist/{local-devices → dial-in}/keys.d.ts +0 -0
  213. /package/dist/{local-devices → dial-in}/keys.js +0 -0
  214. /package/dist/{local-devices → sandbox}/network-grants.module.d.ts +0 -0
  215. /package/dist/{local-devices → sandbox}/network-grants.module.js +0 -0
@@ -0,0 +1,135 @@
1
+ import { type ExtensionContext } from "@capybara-hq/plugin-sdk";
2
+ import type { Redis } from "ioredis";
3
+ import { ApiError } from "../errors.js";
4
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
5
+ import { LockService } from "../infra/lock/lock.service.js";
6
+ import type { KernelLogger } from "../log.js";
7
+ import { DeviceRequestNotSentError, isDeviceRequestNotSent } from "../sandbox/request-not-sent.js";
8
+ import { type DialInConnectionFence } from "./envelope.js";
9
+ import { type DeviceConnectionInfo, DeviceTargets } from "./targets.js";
10
+ /** The device's machine is not connected (no replica holds its lease): the kernel's own error. */
11
+ export declare const deviceOffline: () => ApiError;
12
+ export { machineRevoked } from "../devices/errors.js";
13
+ export { DeviceRequestNotSentError, isDeviceRequestNotSent };
14
+ /**
15
+ * A fenced request's result arrived on another connection than the request went out on, or the
16
+ * machine reconnected while a fenced request waited: its answer was sized for the old connection.
17
+ */
18
+ export declare class DialInConnectionChangedError extends Error {
19
+ readonly connectionChanged: true;
20
+ constructor();
21
+ }
22
+ /** A request whose frame does not fit the machine connection's negotiated frame capacity. */
23
+ export declare class DialInFrameTooLargeError extends Error {
24
+ constructor(maxFrameBytes: number);
25
+ }
26
+ /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
27
+ export declare const LEASE_CHECK_TIMEOUT_MS = 2000;
28
+ /** How often a waiting caller checks that a replica still holds the machine's connection. */
29
+ export declare const HOLDER_POLL_MS = 5000;
30
+ /**
31
+ * How much longer than the caller's wait a queued request lives: giving up must still find an
32
+ * untaken request on the list (an expired one would look taken and get a needless cancel).
33
+ */
34
+ export declare const LIST_TTL_MARGIN_MS = 30000;
35
+ /** The options of {@link DialInRelay.request}. */
36
+ export interface DialInRequestOptions {
37
+ /** How long the machine may take (sent to it as `deadlineMs`). */
38
+ timeoutMs: number;
39
+ /** The caller's signal: aborting gives the request up and rejects with its reason. */
40
+ signal?: AbortSignal;
41
+ /**
42
+ * Kernel-internal: the connection the caller sized its request for. Another current connection
43
+ * refuses the request as not sent before anything is queued. Never from an extension.
44
+ */
45
+ connection?: DialInConnectionFence;
46
+ /**
47
+ * Kernel-internal: the result was sized for the request's connection, so it is accepted only from
48
+ * that connection and the wait ends as soon as the machine reconnects
49
+ * ({@link DialInConnectionChangedError}). Never from an extension.
50
+ */
51
+ fenced?: boolean;
52
+ }
53
+ /**
54
+ * The caller side of the dial-in relay (environments spec §13.4), for every provider serving its
55
+ * devices over the dial-in channel. A request goes onto the device's Redis list
56
+ * (`capk:device-req:<deviceId>`) as a {@link QueuedRequest} fenced to the machine's current
57
+ * connection, and is announced on `device.req.<deviceId>`; whichever gateway replica holds the
58
+ * machine's lease drains the list and sends the envelope `req` to the machine (gateway.ts). The
59
+ * holder stores the machine's `res` under `capk:device-res:<requestId>` and publishes it on
60
+ * `device.res.<requestId>`, tagged with the connection it arrived on (envelope.ts); the relay hands
61
+ * back only the body, never reading it.
62
+ *
63
+ * The caller subscribes to its result topic before pushing and reads the result key once after,
64
+ * and once more before giving up (the run-abort pattern; a publish lost while the subscriber
65
+ * reconnects is still found). It waits within its own call for at most `timeoutMs` plus
66
+ * `devices.dialIn.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
67
+ * {@link HOLDER_POLL_MS}) the wait ends at most one grace later ({@link DeviceOfflineError}), and
68
+ * when the machine is connected again as another run of its program (`programRunId`) it ends at
69
+ * that poll with {@link DeviceProgramRestartedError}: the old run's kept results died with it. A
70
+ * result produced while the machine was disconnected arrives after it reconnects. Giving up (grace,
71
+ * abort, a bad result) removes the request from the list, or queues a `cancel` when the machine
72
+ * already took it (ruling R15). Nothing is kept in process memory beyond the call.
73
+ */
74
+ export declare class DialInRelay {
75
+ private readonly redis;
76
+ private readonly bus;
77
+ private readonly locks;
78
+ private readonly config;
79
+ private readonly log;
80
+ private readonly targets;
81
+ constructor(redis: Redis, bus: ExtensionContext["bus"], locks: Pick<LockService, "holderOf">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, targets: Pick<DeviceTargets, "state" | "current">);
82
+ /** Whether a gateway replica holds the machine's connection now. */
83
+ online(deviceId: string): Promise<boolean>;
84
+ /**
85
+ * The negotiated transport of the machine's current connection. Liveness is checked first
86
+ * (ruling R27): no holder throws `device.not_found` for a deleted device, `device.forbidden` for
87
+ * a revoked machine and `device.offline` ({@link deviceOffline}) otherwise. It carries the
88
+ * program run the connection's hello named (`programRunId`): kernel-internal evidence a request
89
+ * keeps, never put into a frame.
90
+ */
91
+ connection(deviceId: string): Promise<DeviceConnectionInfo>;
92
+ /**
93
+ * Queues a `stop` for the machine without waiting for an answer (ruling R14), only while a
94
+ * replica holds its connection (an offline machine must not find it on the list later). With
95
+ * `machineId`, the holder hands it only to that machine's connection (across a socket blip too),
96
+ * never to a newer machine of the device.
97
+ */
98
+ stop(deviceId: string, reason: "drain" | "stop", opts?: {
99
+ machineId?: string;
100
+ }): Promise<void>;
101
+ /**
102
+ * Sends `body` to the device's machine as the body of a `req` and resolves the body of its `res`
103
+ * (never read here). Throws {@link DeviceOfflineError} when no replica holds the machine at send
104
+ * time or when the wait ran out, but `device.forbidden` ({@link machineRevoked}) when the machine
105
+ * was revoked and `device.not_found` when the device was deleted (checked whenever the
106
+ * connection is missing, ruling R27); {@link DeviceRequestNotSentError} when the request never
107
+ * reached the machine (its connection changed first), {@link DialInFrameTooLargeError} when it
108
+ * cannot fit, {@link DeviceProgramRestartedError} when the machine's program restarted before
109
+ * answering. On abort the abort reason is thrown.
110
+ */
111
+ request(deviceId: string, body: unknown, opts: DialInRequestOptions): Promise<unknown>;
112
+ /** {@link online}, or undefined when it takes longer than {@link LEASE_CHECK_TIMEOUT_MS}. */
113
+ private leaseCheck;
114
+ /**
115
+ * The device's state ({@link DeviceTargets}), or undefined when it cannot be read within
116
+ * {@link LEASE_CHECK_TIMEOUT_MS} (a failure only logs: the caller keeps its other rules).
117
+ */
118
+ private targetState;
119
+ /** The error of a state that never comes back; undefined for `active` or unknown. */
120
+ private goneError;
121
+ private graceMs;
122
+ private push;
123
+ /** Announces new frames to the holder; a lost nudge is picked up on the holder's next drain. */
124
+ private nudge;
125
+ /** Removes the request from the list, or queues a cancel when the machine took it (R15). */
126
+ private giveUp;
127
+ /** Runs a side step whose failure must not replace the call's outcome: logged, swallowed. */
128
+ private quietly;
129
+ /**
130
+ * A stored / published result for request `id` with the kernel's tags stripped
131
+ * ({@link readStoredResult}), or the error it carries. A fenced request accepts only its own
132
+ * connection's result.
133
+ */
134
+ private parseRes;
135
+ }
@@ -0,0 +1,444 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { randomUUID } from "node:crypto";
11
+ import { DeviceOfflineError } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { deviceNotFound, machineRevoked } from "../devices/errors.js";
14
+ import { ApiError } from "../errors.js";
15
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
+ import { LockService } from "../infra/lock/lock.service.js";
17
+ import { KERNEL_BUS, KERNEL_LOGGER, REDIS } from "../infra/tokens.js";
18
+ import { DeviceProgramRestartedError, DeviceRequestNotSentError, isDeviceRequestNotSent, } from "../sandbox/request-not-sent.js";
19
+ import { readStoredResult, } from "./envelope.js";
20
+ import { deviceLeaseKey, deviceReqKey, deviceReqTopic, deviceResKey, deviceResTopic, } from "./keys.js";
21
+ import { DeviceTargets } from "./targets.js";
22
+ /** The device's machine is not connected (no replica holds its lease): the kernel's own error. */
23
+ export const deviceOffline = () => new ApiError("device.offline", "The machine of this device is offline. Start its program on that machine, or pick another device.");
24
+ export { machineRevoked } from "../devices/errors.js";
25
+ export { DeviceRequestNotSentError, isDeviceRequestNotSent };
26
+ /**
27
+ * A fenced request's result arrived on another connection than the request went out on, or the
28
+ * machine reconnected while a fenced request waited: its answer was sized for the old connection.
29
+ */
30
+ export class DialInConnectionChangedError extends Error {
31
+ connectionChanged = true;
32
+ constructor() {
33
+ super("The machine's connection changed while the request waited; retry it");
34
+ this.name = "DialInConnectionChangedError";
35
+ }
36
+ }
37
+ /** A request whose frame does not fit the machine connection's negotiated frame capacity. */
38
+ export class DialInFrameTooLargeError extends Error {
39
+ constructor(maxFrameBytes) {
40
+ super(`The request does not fit the machine connection's frame limit of ${maxFrameBytes} bytes; check the device and deployment frame limits`);
41
+ this.name = "DialInFrameTooLargeError";
42
+ }
43
+ }
44
+ /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
45
+ export const LEASE_CHECK_TIMEOUT_MS = 2000;
46
+ /** How often a waiting caller checks that a replica still holds the machine's connection. */
47
+ export const HOLDER_POLL_MS = 5000;
48
+ /**
49
+ * How much longer than the caller's wait a queued request lives: giving up must still find an
50
+ * untaken request on the list (an expired one would look taken and get a needless cancel).
51
+ */
52
+ export const LIST_TTL_MARGIN_MS = 30_000;
53
+ /**
54
+ * Appends one frame to the request list and makes sure the list lives at least `ARGV[2]` ms
55
+ * (never shortens the TTL a request with a longer deadline set). Atomic, so the list never exists
56
+ * without a TTL.
57
+ */
58
+ const PUSH_WITH_TTL = `
59
+ redis.call('RPUSH', KEYS[1], ARGV[1])
60
+ if redis.call('PTTL', KEYS[1]) < tonumber(ARGV[2]) then
61
+ redis.call('PEXPIRE', KEYS[1], ARGV[2])
62
+ end
63
+ return 1
64
+ `;
65
+ /**
66
+ * Gives up on a request (ruling R15): removes the exact request frame `ARGV[1]` from the list; only
67
+ * when it is no longer queued (the machine already took it) appends the cancel `ARGV[2]`, with the
68
+ * TTL rule of {@link PUSH_WITH_TTL}. Returns 1 when a cancel was queued.
69
+ */
70
+ const GIVE_UP = `
71
+ if redis.call('LREM', KEYS[1], 1, ARGV[1]) > 0 then
72
+ return 0
73
+ end
74
+ redis.call('RPUSH', KEYS[1], ARGV[2])
75
+ if redis.call('PTTL', KEYS[1]) < tonumber(ARGV[3]) then
76
+ redis.call('PEXPIRE', KEYS[1], ARGV[3])
77
+ end
78
+ return 1
79
+ `;
80
+ /** Why a call stopped waiting without a result. */
81
+ const ABORTED = Symbol("aborted");
82
+ const GRACE_EXPIRED = Symbol("grace expired");
83
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
84
+ /**
85
+ * The caller side of the dial-in relay (environments spec §13.4), for every provider serving its
86
+ * devices over the dial-in channel. A request goes onto the device's Redis list
87
+ * (`capk:device-req:<deviceId>`) as a {@link QueuedRequest} fenced to the machine's current
88
+ * connection, and is announced on `device.req.<deviceId>`; whichever gateway replica holds the
89
+ * machine's lease drains the list and sends the envelope `req` to the machine (gateway.ts). The
90
+ * holder stores the machine's `res` under `capk:device-res:<requestId>` and publishes it on
91
+ * `device.res.<requestId>`, tagged with the connection it arrived on (envelope.ts); the relay hands
92
+ * back only the body, never reading it.
93
+ *
94
+ * The caller subscribes to its result topic before pushing and reads the result key once after,
95
+ * and once more before giving up (the run-abort pattern; a publish lost while the subscriber
96
+ * reconnects is still found). It waits within its own call for at most `timeoutMs` plus
97
+ * `devices.dialIn.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
98
+ * {@link HOLDER_POLL_MS}) the wait ends at most one grace later ({@link DeviceOfflineError}), and
99
+ * when the machine is connected again as another run of its program (`programRunId`) it ends at
100
+ * that poll with {@link DeviceProgramRestartedError}: the old run's kept results died with it. A
101
+ * result produced while the machine was disconnected arrives after it reconnects. Giving up (grace,
102
+ * abort, a bad result) removes the request from the list, or queues a `cancel` when the machine
103
+ * already took it (ruling R15). Nothing is kept in process memory beyond the call.
104
+ */
105
+ let DialInRelay = class DialInRelay {
106
+ redis;
107
+ bus;
108
+ locks;
109
+ config;
110
+ log;
111
+ targets;
112
+ constructor(redis, bus, locks, config, log, targets) {
113
+ this.redis = redis;
114
+ this.bus = bus;
115
+ this.locks = locks;
116
+ this.config = config;
117
+ this.log = log;
118
+ this.targets = targets;
119
+ }
120
+ /** Whether a gateway replica holds the machine's connection now. */
121
+ async online(deviceId) {
122
+ return (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== null;
123
+ }
124
+ /**
125
+ * The negotiated transport of the machine's current connection. Liveness is checked first
126
+ * (ruling R27): no holder throws `device.not_found` for a deleted device, `device.forbidden` for
127
+ * a revoked machine and `device.offline` ({@link deviceOffline}) otherwise. It carries the
128
+ * program run the connection's hello named (`programRunId`): kernel-internal evidence a request
129
+ * keeps, never put into a frame.
130
+ */
131
+ async connection(deviceId) {
132
+ if (await this.online(deviceId)) {
133
+ const current = await this.targets.current(deviceId);
134
+ if (current)
135
+ return current;
136
+ }
137
+ throw this.goneError(await this.targetState(deviceId)) ?? deviceOffline();
138
+ }
139
+ /**
140
+ * Queues a `stop` for the machine without waiting for an answer (ruling R14), only while a
141
+ * replica holds its connection (an offline machine must not find it on the list later). With
142
+ * `machineId`, the holder hands it only to that machine's connection (across a socket blip too),
143
+ * never to a newer machine of the device.
144
+ */
145
+ async stop(deviceId, reason, opts = {}) {
146
+ if (!(await this.online(deviceId)))
147
+ return;
148
+ const frame = {
149
+ type: "stop",
150
+ reason,
151
+ ...(opts.machineId !== undefined && { machineId: opts.machineId }),
152
+ };
153
+ await this.push(deviceId, JSON.stringify(frame), this.graceMs() + LIST_TTL_MARGIN_MS);
154
+ await this.bus.publish(deviceReqTopic(deviceId), { id: randomUUID() });
155
+ }
156
+ /**
157
+ * Sends `body` to the device's machine as the body of a `req` and resolves the body of its `res`
158
+ * (never read here). Throws {@link DeviceOfflineError} when no replica holds the machine at send
159
+ * time or when the wait ran out, but `device.forbidden` ({@link machineRevoked}) when the machine
160
+ * was revoked and `device.not_found` when the device was deleted (checked whenever the
161
+ * connection is missing, ruling R27); {@link DeviceRequestNotSentError} when the request never
162
+ * reached the machine (its connection changed first), {@link DialInFrameTooLargeError} when it
163
+ * cannot fit, {@link DeviceProgramRestartedError} when the machine's program restarted before
164
+ * answering. On abort the abort reason is thrown.
165
+ */
166
+ async request(deviceId, body, opts) {
167
+ const signal = opts.signal ?? new AbortController().signal;
168
+ signal.throwIfAborted();
169
+ let current;
170
+ try {
171
+ // liveness first: a deleted device or a revoked machine keeps its typed error (R27)
172
+ current = await this.connection(deviceId);
173
+ }
174
+ catch (e) {
175
+ if (e instanceof ApiError && e.code === "device.offline")
176
+ throw new DeviceOfflineError(deviceId, { cause: e });
177
+ throw e;
178
+ }
179
+ const connection = {
180
+ connectionId: current.connectionId,
181
+ maxFrameBytes: current.maxFrameBytes,
182
+ };
183
+ if (opts.connection &&
184
+ (connection.connectionId !== opts.connection.connectionId ||
185
+ connection.maxFrameBytes !== opts.connection.maxFrameBytes))
186
+ // nothing was queued: the request was definitely not sent
187
+ throw new DeviceRequestNotSentError("The machine's connection changed before the request was sent; retry it");
188
+ // the program run the request goes to: the drain sends it only on this connection (a newer
189
+ // one refuses it as not sent), so a later connection of another run proves its result lost
190
+ const sentToRun = current.programRunId;
191
+ const fenced = opts.fenced === true;
192
+ if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0)
193
+ throw new RangeError(`timeoutMs must be a positive number, got ${opts.timeoutMs}`);
194
+ if (body === undefined)
195
+ throw new TypeError("a dial-in request needs a body");
196
+ const id = randomUUID();
197
+ const deadlineMs = Math.max(1, Math.ceil(opts.timeoutMs));
198
+ const graceMs = this.graceMs();
199
+ const listTtlMs = graceMs + deadlineMs + LIST_TTL_MARGIN_MS;
200
+ const wire = JSON.stringify({ type: "req", id, deadlineMs, body });
201
+ if (Buffer.byteLength(wire) > connection.maxFrameBytes)
202
+ throw new DialInFrameTooLargeError(connection.maxFrameBytes);
203
+ const queued = { type: "req", id, deadlineMs, body, ...connection };
204
+ const reqJson = JSON.stringify(queued);
205
+ signal.throwIfAborted();
206
+ let settle;
207
+ const outcome = new Promise((resolve) => {
208
+ let done = false;
209
+ settle = (r) => {
210
+ if (done)
211
+ return;
212
+ done = true;
213
+ resolve(r);
214
+ };
215
+ });
216
+ const onStored = (raw) => {
217
+ if (raw !== null && raw !== undefined)
218
+ settle(this.parseRes(raw, id, connection, fenced));
219
+ };
220
+ const onAbort = () => settle({ error: ABORTED });
221
+ const unsubscribe = await this.bus.subscribe(deviceResTopic(id), (payload) => {
222
+ onStored(payload);
223
+ });
224
+ let timer;
225
+ let stopped = false;
226
+ try {
227
+ signal.addEventListener("abort", onAbort, { once: true });
228
+ // aborted while subscribing: nothing was sent yet
229
+ signal.throwIfAborted();
230
+ await this.push(deviceId, reqJson, listTtlMs);
231
+ this.nudge(deviceId, id);
232
+ onStored(await this.redis.get(deviceResKey(id)));
233
+ // wait until the result, the abort, or `giveUpAt`. The lease is checked every poll: its loss
234
+ // caps `giveUpAt` at one grace from then (never extending it); a reconnect within that grace
235
+ // restores the full wait, so a long command whose machine blipped keeps its deadline
236
+ const fullGiveUpAt = Date.now() + deadlineMs + graceMs;
237
+ let giveUpAt = fullGiveUpAt;
238
+ let capped = false;
239
+ const tick = async () => {
240
+ if (stopped)
241
+ return;
242
+ try {
243
+ // a stalled Redis must not hold the give-up back: no answer in time means "unknown"
244
+ const live = await this.leaseCheck(deviceId);
245
+ if (fenced && live === true) {
246
+ // a fenced request never waits across a reconnect: its answer was sized for this socket
247
+ const now = await this.targets.current(deviceId);
248
+ if (now &&
249
+ (now.connectionId !== connection.connectionId ||
250
+ now.maxFrameBytes !== connection.maxFrameBytes)) {
251
+ settle({ error: new DialInConnectionChangedError() });
252
+ return;
253
+ }
254
+ }
255
+ if (!fenced && sentToRun !== undefined && live === true) {
256
+ // results a program keeps for a reconnect live in its memory: once the machine is
257
+ // connected as another run, this request's result can never arrive (unless it was
258
+ // stored before the old run went away, which the last look below still finds)
259
+ const now = await this.targets.current(deviceId).catch(() => null);
260
+ if (now?.programRunId !== undefined && now.programRunId !== sentToRun) {
261
+ this.redis.get(deviceResKey(id)).then((raw) => raw !== null
262
+ ? onStored(raw)
263
+ : settle({ error: new DeviceProgramRestartedError("the request") }), () => settle({ error: new DeviceProgramRestartedError("the request") }));
264
+ return;
265
+ }
266
+ }
267
+ if (live === true && capped) {
268
+ capped = false;
269
+ giveUpAt = fullGiveUpAt;
270
+ }
271
+ else if (live === false && !capped) {
272
+ capped = true;
273
+ giveUpAt = Math.min(giveUpAt, Date.now() + graceMs);
274
+ }
275
+ if (live === false) {
276
+ // a revoked machine or a deleted device never comes back: fail at once
277
+ const gone = this.goneError(await this.targetState(deviceId));
278
+ if (gone) {
279
+ settle({ error: gone });
280
+ return;
281
+ }
282
+ }
283
+ }
284
+ catch (e) {
285
+ this.log.warn("device relay lease check failed", { deviceId, error: errMsg(e) });
286
+ }
287
+ if (stopped)
288
+ return;
289
+ if (Date.now() >= giveUpAt) {
290
+ // a last look at the key: the publish may have been lost while the subscriber reconnected
291
+ this.redis.get(deviceResKey(id)).then((raw) => (raw !== null ? onStored(raw) : settle({ error: GRACE_EXPIRED })), () => settle({ error: GRACE_EXPIRED }));
292
+ return;
293
+ }
294
+ schedule();
295
+ };
296
+ const schedule = () => {
297
+ if (stopped)
298
+ return;
299
+ const wait = Math.max(0, Math.min(HOLDER_POLL_MS, giveUpAt - Date.now()));
300
+ timer = setTimeout(() => void tick(), wait);
301
+ };
302
+ schedule();
303
+ const r = await outcome;
304
+ stopped = true;
305
+ clearTimeout(timer);
306
+ if ("res" in r) {
307
+ // the result's connection tag was checked in parseRes: a later reconnect changes nothing
308
+ await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
309
+ // only the gateway's marker says a request never reached the machine
310
+ if (r.res.notSent !== undefined)
311
+ throw new DeviceRequestNotSentError(r.res.notSent);
312
+ return r.res.body;
313
+ }
314
+ if (r.error instanceof Error) {
315
+ // a bad answer: drop it, give the request up, report the error
316
+ await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
317
+ }
318
+ await this.giveUp(deviceId, id, reqJson, listTtlMs);
319
+ if (r.error === ABORTED)
320
+ throw signal.reason;
321
+ if (r.error === GRACE_EXPIRED)
322
+ throw new DeviceOfflineError(deviceId);
323
+ throw r.error;
324
+ }
325
+ finally {
326
+ stopped = true;
327
+ clearTimeout(timer);
328
+ signal.removeEventListener("abort", onAbort);
329
+ await this.quietly("unsubscribe", deviceId, unsubscribe);
330
+ }
331
+ }
332
+ /** {@link online}, or undefined when it takes longer than {@link LEASE_CHECK_TIMEOUT_MS}. */
333
+ async leaseCheck(deviceId) {
334
+ let timer;
335
+ const check = this.online(deviceId);
336
+ check.catch(() => { }); // a late failure after the timeout is not unhandled
337
+ try {
338
+ return await Promise.race([
339
+ check,
340
+ new Promise((resolve) => {
341
+ timer = setTimeout(() => resolve(undefined), LEASE_CHECK_TIMEOUT_MS);
342
+ }),
343
+ ]);
344
+ }
345
+ finally {
346
+ clearTimeout(timer);
347
+ }
348
+ }
349
+ /**
350
+ * The device's state ({@link DeviceTargets}), or undefined when it cannot be read within
351
+ * {@link LEASE_CHECK_TIMEOUT_MS} (a failure only logs: the caller keeps its other rules).
352
+ */
353
+ async targetState(deviceId) {
354
+ let timer;
355
+ const read = this.targets.state(deviceId);
356
+ read.catch(() => { });
357
+ try {
358
+ return await Promise.race([
359
+ read,
360
+ new Promise((resolve) => {
361
+ timer = setTimeout(() => resolve(undefined), LEASE_CHECK_TIMEOUT_MS);
362
+ }),
363
+ ]);
364
+ }
365
+ catch (e) {
366
+ this.log.warn("device relay could not read the device state", {
367
+ deviceId,
368
+ error: errMsg(e),
369
+ });
370
+ return undefined;
371
+ }
372
+ finally {
373
+ clearTimeout(timer);
374
+ }
375
+ }
376
+ /** The error of a state that never comes back; undefined for `active` or unknown. */
377
+ goneError(state) {
378
+ if (state === "deleted")
379
+ return deviceNotFound();
380
+ if (state === "revoked")
381
+ return machineRevoked();
382
+ return undefined;
383
+ }
384
+ graceMs() {
385
+ return this.config.get().devices.dialIn.reconnectGraceSeconds * 1000;
386
+ }
387
+ async push(deviceId, frame, ttlMs) {
388
+ await this.redis.eval(PUSH_WITH_TTL, 1, deviceReqKey(deviceId), frame, String(ttlMs));
389
+ }
390
+ /** Announces new frames to the holder; a lost nudge is picked up on the holder's next drain. */
391
+ nudge(deviceId, id) {
392
+ this.bus.publish(deviceReqTopic(deviceId), { id }).catch((e) => {
393
+ this.log.warn("device relay nudge failed", { deviceId, error: errMsg(e) });
394
+ });
395
+ }
396
+ /** Removes the request from the list, or queues a cancel when the machine took it (R15). */
397
+ async giveUp(deviceId, id, reqJson, ttlMs) {
398
+ const cancel = { type: "cancel", id };
399
+ await this.quietly("give the request up", deviceId, async () => {
400
+ const queued = await this.redis.eval(GIVE_UP, 1, deviceReqKey(deviceId), reqJson, JSON.stringify(cancel), String(ttlMs));
401
+ if (queued === 1)
402
+ this.nudge(deviceId, id);
403
+ });
404
+ }
405
+ /** Runs a side step whose failure must not replace the call's outcome: logged, swallowed. */
406
+ async quietly(what, deviceId, fn) {
407
+ try {
408
+ await fn();
409
+ }
410
+ catch (e) {
411
+ this.log.warn(`device relay could not ${what}`, { deviceId, error: errMsg(e) });
412
+ }
413
+ }
414
+ /**
415
+ * A stored / published result for request `id` with the kernel's tags stripped
416
+ * ({@link readStoredResult}), or the error it carries. A fenced request accepts only its own
417
+ * connection's result.
418
+ */
419
+ parseRes(raw, id, connection, fenced) {
420
+ try {
421
+ const r = readStoredResult(raw);
422
+ if (r.id !== id)
423
+ throw new Error("the gateway stored a result for another request");
424
+ if (fenced &&
425
+ (r.connection.connectionId !== connection.connectionId ||
426
+ r.connection.maxFrameBytes !== connection.maxFrameBytes))
427
+ return { error: new DialInConnectionChangedError() };
428
+ return { res: r };
429
+ }
430
+ catch (e) {
431
+ return { error: new Error(`the device relay read an invalid result: ${errMsg(e)}`) };
432
+ }
433
+ }
434
+ };
435
+ DialInRelay = __decorate([
436
+ Injectable(),
437
+ __param(0, Inject(REDIS)),
438
+ __param(1, Inject(KERNEL_BUS)),
439
+ __param(2, Inject(LockService)),
440
+ __param(3, Inject(KernelConfigService)),
441
+ __param(4, Inject(KERNEL_LOGGER)),
442
+ __param(5, Inject(DeviceTargets))
443
+ ], DialInRelay);
444
+ export { DialInRelay };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The caller side of the dial-in relay ({@link DialInRelay}, {@link DeviceTargets}) and the
3
+ * extensions' access to it ({@link DialInAccess}, behind `ctx.dialIn`). It needs only the global
4
+ * infrastructure (PG, Redis, locks, config), so the extension host's module can import it.
5
+ */
6
+ export declare class DialInRelayModule {
7
+ }
@@ -0,0 +1,24 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Module } from "@nestjs/common";
8
+ import { DialInAccess } from "./access.js";
9
+ import { DialInRelay } from "./relay.js";
10
+ import { DeviceTargets } from "./targets.js";
11
+ /**
12
+ * The caller side of the dial-in relay ({@link DialInRelay}, {@link DeviceTargets}) and the
13
+ * extensions' access to it ({@link DialInAccess}, behind `ctx.dialIn`). It needs only the global
14
+ * infrastructure (PG, Redis, locks, config), so the extension host's module can import it.
15
+ */
16
+ let DialInRelayModule = class DialInRelayModule {
17
+ };
18
+ DialInRelayModule = __decorate([
19
+ Module({
20
+ providers: [DeviceTargets, DialInRelay, DialInAccess],
21
+ exports: [DeviceTargets, DialInRelay, DialInAccess],
22
+ })
23
+ ], DialInRelayModule);
24
+ export { DialInRelayModule };
@@ -1,19 +1,20 @@
1
1
  import { type WebSocket } from "@fastify/websocket";
2
2
  import type { FastifyInstance, FastifyRequest } from "fastify";
3
- import type { MachineIdentity } from "./machines.js";
3
+ import type { DialInAdmission } from "./gateway.js";
4
4
  /** The device connection route (environments spec §13.4). */
5
5
  export declare const DEVICE_CONNECT_ROUTE = "/device/connect";
6
- /** The header carrying the program's protocol version. */
6
+ /** The header carrying the dial-in protocol the program speaks (`<name>/<major>`). */
7
7
  export declare const DEVICE_PROTOCOL_HEADER = "x-capybara-device-protocol";
8
- /** What the route needs from the gateway (`LocalDeviceGateway`). */
8
+ /** What the route needs from the gateway (`DialInGateway`). */
9
9
  export interface DeviceRoutesGateway {
10
- authenticate(credential: string): Promise<MachineIdentity | null>;
10
+ /** Who the credential stands for and the provider serving its device; null when unknown. */
11
+ admit(credential: string): Promise<DialInAdmission>;
11
12
  /** Serves the upgraded socket (re-checks the credential with the socket paused). */
12
- accept(socket: WebSocket, credential: string): Promise<void>;
13
+ accept(socket: WebSocket, credential: string, protocol: string): Promise<void>;
13
14
  }
14
15
  export interface DeviceRoutesOptions {
15
16
  gateway: DeviceRoutesGateway;
16
- /** `devices.local.maxFrameBytes`: a larger incoming frame closes the socket (1009). */
17
+ /** `devices.dialIn.maxFrameBytes`: a larger incoming frame closes the socket (1009). */
17
18
  maxFrameBytes: number;
18
19
  }
19
20
  /**
@@ -21,14 +22,21 @@ export interface DeviceRoutesOptions {
21
22
  * case-insensitive). Other upgrades (`h2c`, …) are ordinary requests here.
22
23
  */
23
24
  export declare function isWebSocketUpgrade(req: FastifyRequest): boolean;
25
+ /**
26
+ * The text of a 426: the device's provider speaks `expected`, the program `spoken`. A program of
27
+ * the same protocol family with a newer major is told the deployment is the one to upgrade; an
28
+ * older one (or another protocol) to update the program. The program's protocol is named only
29
+ * when it is a well-formed `<name>/<major>` (header input).
30
+ */
31
+ export declare function protocolMismatchMessage(plugin: string, expected: string, spoken: unknown): string;
24
32
  /**
25
33
  * Registers `GET /device/connect` (the gateway role only) in its own encapsulated scope with
26
34
  * `@fastify/websocket`: a raw Fastify route outside Nest, so neither the API's `AuthGuard` nor its
27
- * CSRF check applies; the route checks the machine credential itself, before the upgrade (401
28
- * `device.credential_invalid`), then the protocol header (426 `device.program_outdated`): only
29
- * {@link DEVICE_PROTOCOL_VERSION} (5) is served; an older program (protocol 4 among them) must
30
- * update. A newer program reads the kernel's protocol in the message and asks for the deployment
31
- * to be upgraded instead.
35
+ * CSRF check applies. Before the upgrade the route checks the machine credential (401
36
+ * `device.credential_invalid`), then the device's provider: off in the org, not loaded or not a
37
+ * dial-in provider is 403 `device.provider_unavailable`; then the protocol header, which must
38
+ * equal the provider's `permissions.dialIn.protocol` (426 `device.program_outdated`, naming the
39
+ * provider's protocol).
32
40
  * Must be called before Nest `app.init()`, on the root instance.
33
41
  *
34
42
  * `@fastify/websocket` sends every upgrade request of the server through the Fastify router; the