-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.mjs
More file actions
8297 lines (7875 loc) · 367 KB
/
Copy pathapp.mjs
File metadata and controls
8297 lines (7875 loc) · 367 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { readFile } from "node:fs/promises";
import { createServer } from "node:http";
import { hostname } from "node:os";
import { DEFAULT_HARDWARE_BOARD, HARDWARE_BOARDS, describeHardwareBoard } from "./hardware.mjs";
import { dirname, extname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { createClerkAuthenticator } from "./clerkAuth.mjs";
import { loadConfig } from "./config.mjs";
import { buildConnectorRotateCommand, buildConnectCommand, normalizeConnectAccessMode } from "./connectSession.mjs";
import {
CONNECTOR_CREDENTIAL_SCOPES,
CONNECTOR_PROTOCOL_VERSION,
CONNECTOR_TICKET_AUDIENCE,
} from "./connectorProtocol.mjs";
import { buildDeviceDisplayState, buildUserDisplayState, invalidateDisplayCache } from "./displayState.mjs";
import { createEventBroker } from "./events.mjs";
import {
buildBackgroundLiveness,
createNotificationPublisher,
notificationView,
} from "./notifications.mjs";
import {
createWebPushDeliveryRunner,
publicWebPushConfig,
validatePushSubscription,
} from "./webPush.mjs";
import {
HttpError,
optionalString,
parseJsonBody,
readJson,
readRawBody,
requireString,
sendBuffer,
sendError,
sendJson,
} from "./http.mjs";
import { createId, createSecret } from "./ids.mjs";
import { normalizeIntent } from "./intent.mjs";
import {
COMMAND_REQUEST_OPERATION,
THREAD_LAUNCH_REQUEST_OPERATION,
THREAD_CREATE_REQUEST_OPERATION,
commandRequestHash,
normalizeClientRequestId,
} from "./requestEnvelope.mjs";
import {
buildDeviceFollowUpInstruction,
buildDeviceThreadOutput,
} from "./deviceThreadOutput.mjs";
import {
buildDeviceClaimUrl,
buildDeviceLabelSvg,
buildFirmwareManifest,
buildFlashConfig,
buildNvsSeedCsv,
claimLabelFilename,
isNewerVersion,
normalizeFirmwareRelease,
} from "./manufacturing.mjs";
import { verifyMediaAccessToken } from "./mediaLinks.mjs";
import { renderQrSvg } from "./qrcode.mjs";
import { deleteFirmwareArtifact, readFirmwareArtifact, storeFirmwareArtifact } from "./firmwareArtifacts.mjs";
import { buildFirmwareArtifactUrl, verifyFirmwareArtifactCapability } from "./firmwareLinks.mjs";
import {
abortMediaUpload,
buildMediaAttachments,
createMediaUploadIntent,
deleteStoredMediaRecord,
finalizeMediaUpload,
readStoredMedia,
storeUploadedMedia,
writeMediaUploadSession,
} from "./mediaStore.mjs";
import { createMediaRetentionRunner } from "./mediaRetention.mjs";
import { createEnvironmentRetentionRunner } from "./environmentRetention.mjs";
import { createMediaJobRunner } from "./mediaJobs.mjs";
import { createReleaseRolloutRunner } from "./releaseRollouts.mjs";
import {
buildMediaName,
lookupThreadTitle,
markThreadTitlesUnavailable,
rememberSnapshotThreadTitles,
threadTitlesAreStale,
} from "./mediaNaming.mjs";
import { mintDeviceThreadTitle, normalizeTitle } from "./threadNaming.mjs";
import { deviceJobStatus, mediaJobEvent, voiceAutoSendEnabled } from "./deviceAudio.mjs";
import {
createTranscriptionProvider,
describeTranscriptChange,
isTranscriptionProviderEnabled,
} from "./transcription.mjs";
import { buildUserObservabilitySummary } from "./observability.mjs";
import {
checkResourceLimit,
effectiveTier,
entitlementsFor,
listPlans,
normalizeSubscription,
} from "./billing.mjs";
import { evaluateAlerts, summarizeAlerts } from "./alerts.mjs";
import { buildBetaReadiness } from "./betaReadiness.mjs";
import {
actionControlKind,
actionIntent,
ENVIRONMENT_REMOVED_REASON,
hardwareSupportsAction,
normalizeActionInput,
normalizeDeviceControlItems,
SYSTEM_CONTROL_IDS,
} from "./actions.mjs";
import { describeStoredImage } from "./vision.mjs";
import { classifyNetworkLocation } from "./networkTrust.mjs";
import { buildOnboardingReadiness, normalizeOnboarding } from "./onboarding.mjs";
import { evaluateIntentPolicy } from "./policy.mjs";
import {
capabilitiesForProfile,
isKnownDeviceProfile,
listDeviceProfiles,
normalizeDeviceProfile,
validateCustomProfile,
} from "./profiles.mjs";
import { createRateLimiter } from "./rateLimit.mjs";
import { configurePrivateTailscaleServe, inspectRemoteAccess } from "./remoteAccess.mjs";
import { normalizeGatewayProfileInput, publicGatewayProfile } from "./gatewayProfiles.mjs";
import { createSnapshotPoller } from "./snapshotPoller.mjs";
import { createThreadStreamHub } from "./threadStream.mjs";
import { createCommandArbiter } from "./commandArbiter.mjs";
import { createStore, emptyEnvironmentRemoval } from "./store.mjs";
import { assertSecureTransport } from "./transport.mjs";
import {
TERMINAL_SCOPE,
T3_WS_METHODS,
environmentHasTerminalScope,
} from "./t3Ws.mjs";
import {
buildProviderCatalogue,
extractHarnesses,
extractSessionFailures,
resolveModelSelection,
usableHarnesses,
validateModelSelection,
} from "./t3Harness.mjs";
import {
buildT3Command,
buildT3ProjectLaunchCommands,
buildT3ThreadCreateCommand,
compressSnapshot,
exchangePairingToken,
isEnvironmentTokenExpired,
} from "./t3Client.mjs";
import { createT3TransportResolver } from "./t3Transport.mjs";
import { refineThreadStatus } from "./agentVerb.mjs";
import {
PROVIDER_APPROVAL_DECISION_CATALOGUE,
allowedProviderApprovalDecisions,
collectProviderApprovals,
deviceProviderApprovalView,
normalizeProviderApprovalDecision,
} from "./providerApprovals.mjs";
import {
collectUserInputRequests,
deviceUserInputView,
isDeviceAnswerableUserInput,
userInputAnswersFingerprint,
validateUserInputAnswers,
} from "./userInput.mjs";
import {
buildT3ReleaseStatus,
fetchLatestT3Release,
runT3CompatibilityCheck,
summarizeT3Compatibility,
T3_COMPATIBILITY_POLICY,
} from "./t3Compatibility.mjs";
import {
T3Adapter,
attachmentCapabilitySupported,
capabilityManifestIsFresh,
capabilitySupported,
ownerSafeT3CapabilityProjection,
} from "./t3CapabilityManifest.mjs";
import {
classifyEnvironmentFailure,
describeEnvironmentFailure,
isRetryableEnvironmentFailure,
} from "./environmentFailure.mjs";
const STANDARD_T3_SCOPES = ["orchestration:read", "orchestration:operate"];
const BILLING_WEBHOOK_TOLERANCE_MS = 5 * 60 * 1000;
const __dirname = dirname(fileURLToPath(import.meta.url));
const WEB_DIST_DIR = join(__dirname, "..", "dist", "web");
const t3TransportResolversByStore = new WeakMap();
const notificationPublishersByStore = new WeakMap();
const defaultT3TransportResolver = createT3TransportResolver();
async function resolveEnvironmentHarnessesWithTransport(environment, snapshot, transportResolver) {
let catalogue = environment.providerCatalogue ?? null;
let catalogueSource = catalogue ? "registered" : "snapshot-only";
try {
const config = await transportResolver.forEnvironment(environment).callRpc(
environment,
T3_WS_METHODS.serverGetConfig,
{},
{ timeoutMs: 8000 },
);
if (!Array.isArray(config?.providers)) throw new Error("T3 server.getConfig did not return providers.");
catalogue = buildProviderCatalogue(config.providers, { source: "t3-websocket" });
catalogueSource = "live";
} catch {
// A registered catalogue is still authoritative when the live socket is unavailable. Without
// either source, snapshot-derived harnesses remain permissive so custom models keep working.
}
return {
harnesses: extractHarnesses(snapshot, { catalogue }),
catalogueSource,
};
}
export function createApp({
store = null,
config = loadConfig(),
rateLimiter = createRateLimiter(),
clerkAuth = createClerkAuthenticator(config),
t3CompatibilityRpc = undefined,
t3TransportResolver = createT3TransportResolver(),
connectorRouter = null,
remoteAccessControl = configurePrivateTailscaleServe,
} = {}) {
store ??= createStore({}, { t3TokenEncryptionKey: config.t3TokenEncryptionKey });
// Cloud deployments must never turn a persisted legacy baseUrl into an outbound request. A
// connector is the sole production transport; direct T3 remains available only to the
// self-hosted compatibility adapter. Keeping this at the resolver boundary also covers jobs,
// device routes, and helper paths which do not pass through the environment-management routes.
const runtimeT3TransportResolver = cloudSafeT3TransportResolver(config, t3TransportResolver);
t3TransportResolversByStore.set(store, runtimeT3TransportResolver);
const dispatchT3Command = (environment, command, options) => (
dispatchT3CommandForStore(store, environment, command, options)
);
const fetchT3ThreadDetail = (environment, threadId, options) => (
runtimeT3TransportResolver.forEnvironment(environment).threadDetail(environment, threadId, options)
);
const readT3Snapshot = (environment, options = {}) => (
readT3SnapshotWithTransport(environment, options, runtimeT3TransportResolver)
);
const resolveEnvironmentHarnesses = (environment, snapshot) => (
resolveEnvironmentHarnessesWithTransport(environment, snapshot, runtimeT3TransportResolver)
);
const events = createEventBroker();
const notifications = createNotificationPublisher({ store, events });
notificationPublishersByStore.set(store, notifications);
// The memory and file stores hand back a full snapshot; the Convex store can only name the
// user whose data changed. Both end up as a state.changed event for that user.
store.subscribe((change) => {
if (change && Array.isArray(change.users)) {
// A full snapshot names no single user, so nothing can be assumed still fresh.
invalidateDisplayCache();
events.broadcastStateChange(change);
return;
}
if (change?.userId) {
invalidateDisplayCache(change.userId);
events.broadcastUserChange(change.userId, { action: change.action ?? null });
}
});
// One arbiter, two evidence sources. The poller reads T3 on a timer and the thread stream reads
// it live; without a shared arbiter they would both decide the same dispatched command, and a
// live failure could be overwritten by a polled reply from the same turn. See
// src/commandArbiter.mjs.
const commandArbiter = createCommandArbiter();
const snapshotPoller = createSnapshotPoller({
store,
events,
notifications,
arbiter: commandArbiter,
transportResolver: runtimeT3TransportResolver,
...(config.snapshotPollIntervalMs ? { intervalMs: config.snapshotPollIntervalMs } : {}),
});
// Constructed here, started from server.mjs — same rule as the poller and the media worker, so
// no test opens a socket it did not ask for. Tests drive runOnce().
const threadStreams = createThreadStreamHub({
store,
events,
notifications,
arbiter: commandArbiter,
transportResolver: runtimeT3TransportResolver,
...(config.threadStreamIntervalMs ? { intervalMs: config.threadStreamIntervalMs } : {}),
...(config.threadStreamWatchTtlMs ? { watchTtlMs: config.threadStreamWatchTtlMs } : {}),
});
// Constructed here, started from server.mjs. Tests drive runOnce() so nothing depends on a timer.
const mediaJobRunner = createMediaJobRunner({
store,
config,
events,
notifications,
// Closed over the store and config rather than imported by the worker, which has no business
// knowing what a policy is. Every send is decided here, at the moment it happens.
dispatchTranscript: ({ job, transcript }) => dispatchVoiceTranscript({ store, config, job, transcript }),
...(config.transcriptionWorkerIntervalMs ? { intervalMs: config.transcriptionWorkerIntervalMs } : {}),
...(config.transcriptionLeaseMs ? { leaseMs: config.transcriptionLeaseMs } : {}),
...(config.transcriptionBatchSize ? { batchSize: config.transcriptionBatchSize } : {}),
});
const mediaRetentionRunner = createMediaRetentionRunner({ store, config });
const environmentRetentionRunner = createEnvironmentRetentionRunner({ store });
const releaseRolloutRunner = createReleaseRolloutRunner({ store, events });
const webPushDeliveryRunner = createWebPushDeliveryRunner({
store,
config: config.webPush,
intervalMs: config.webPushWorkerIntervalMs,
});
let remoteAccessCache = null;
let remoteAccessCacheExpiresAt = 0;
async function remoteAccessStatus(force = false) {
if (!force && remoteAccessCache && remoteAccessCacheExpiresAt > Date.now()) {
return remoteAccessCache;
}
remoteAccessCache = await inspectRemoteAccess({
host: config.host,
port: config.port,
publicBaseUrl: config.publicBaseUrl,
});
remoteAccessCacheExpiresAt = Date.now() + 15_000;
return remoteAccessCache;
}
async function handle(req, res) {
try {
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
if (req.method === "GET" && isWebStaticRoute(url.pathname)) {
return await serveWebStatic(res, url.pathname);
}
if (req.method === "GET" && url.pathname === "/favicon.ico") {
return sendBuffer(res, 204, Buffer.alloc(0), { "content-type": "image/x-icon" });
}
if (req.method === "GET" && url.pathname === "/health") {
return sendJson(res, 200, { ok: true, service: "agent-controller", demoMode: config.demoMode });
}
// Unauthenticated on purpose, and it says nothing a probe on the LAN could not already infer
// from /health. Its job is to let a controller CONFIRM that a candidate address is a gateway
// — after a UDP discovery reply, or after the owner typed something — before it commits the
// URL to NVS and reboots into it.
if (req.method === "GET" && url.pathname === "/v1/hardware/boards") {
return sendJson(res, 200, { boards: HARDWARE_BOARDS, defaultBoard: DEFAULT_HARDWARE_BOARD });
}
if (req.method === "GET" && url.pathname === "/v1/discovery") {
return sendJson(res, 200, {
service: "agent-controller",
name: config.discoveryName ?? hostname(),
authProvider: config.authProvider,
claimRequired: true,
});
}
if (req.method === "GET" && url.pathname === "/v1/auth/config") {
return sendJson(res, 200, {
authProvider: config.authProvider,
demoMode: config.demoMode,
deploymentMode: config.deploymentMode ?? "self-hosted",
developmentTokens: {
enabled: isDevTokenCreationEnabled(config),
},
clerk: {
enabled: config.authProvider === "clerk" && Boolean(config.clerkPublishableKey),
publishableKey: config.authProvider === "clerk" ? config.clerkPublishableKey : null,
},
});
}
// Profile editor (roadmap Phase 8). Built-ins are code; custom profiles are user-scoped.
if (req.method === "POST" && url.pathname === "/v1/device-profiles") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const body = await readJson(req);
const candidate = validateCustomProfile({
id: optionalString(body.profileId) ?? optionalString(body.id),
label: optionalString(body.label),
description: optionalString(body.description),
capabilities: body.capabilities,
});
if (!candidate.valid) throw new HttpError(400, candidate.reason);
if (isKnownDeviceProfile(candidate.profile.id)) {
throw new HttpError(409, `"${candidate.profile.id}" is a built-in profile id.`);
}
const created = await store.createDeviceProfile({
userId: user.id,
profileId: candidate.profile.id,
label: candidate.profile.label,
description: candidate.profile.description,
capabilities: candidate.profile.capabilities,
});
if (!created) throw new HttpError(409, `Profile "${candidate.profile.id}" already exists.`);
await publishDeviceRefreshForAll({ store, events, userId: user.id,
resources: ["controls", "display"] });
return sendJson(res, 201, { profile: toPublicProfile(created) });
}
const deviceProfileMatch2 = url.pathname.match(/^\/v1\/device-profiles\/([^/]+)$/u);
if (req.method === "PUT" && deviceProfileMatch2) {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const profileId = deviceProfileMatch2[1];
if (isKnownDeviceProfile(profileId)) {
throw new HttpError(403, "Built-in profiles cannot be edited.");
}
const body = await readJson(req);
if (body.capabilities !== undefined) {
const candidate = validateCustomProfile({ id: profileId, capabilities: body.capabilities });
if (!candidate.valid) throw new HttpError(400, candidate.reason);
}
const updated = await store.updateDeviceProfileDefinition({
userId: user.id,
profileId,
...(body.label !== undefined ? { label: requireString(body.label, "label") } : {}),
...(body.description !== undefined ? { description: String(body.description) } : {}),
...(body.capabilities !== undefined ? { capabilities: body.capabilities } : {}),
});
if (!updated) throw new HttpError(404, "Device profile not found.");
await publishDeviceRefreshForAll({ store, events, userId: user.id,
resources: ["controls", "display"] });
return sendJson(res, 200, { profile: toPublicProfile(updated) });
}
if (req.method === "DELETE" && deviceProfileMatch2) {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const profileId = deviceProfileMatch2[1];
if (isKnownDeviceProfile(profileId)) {
throw new HttpError(403, "Built-in profiles cannot be deleted.");
}
const devices = await store.listDevices(user.id);
const inUse = devices.filter((device) => device.profile === profileId && !device.revokedAt);
if (inUse.length > 0) {
throw new HttpError(409, "This profile is still assigned to a device.", {
deviceIds: inUse.map((device) => device.id),
});
}
const deleted = await store.deleteDeviceProfile({ userId: user.id, profileId });
if (!deleted) throw new HttpError(404, "Device profile not found.");
return sendJson(res, 200, { profile: toPublicProfile(deleted) });
}
if (req.method === "GET" && url.pathname === "/v1/device-profiles") {
const builtins = listDeviceProfiles().map((profile) => ({ ...profile, builtin: true }));
// Stays public for the unauthenticated onboarding step; credentials additionally reveal
// the caller's own custom profiles.
let custom = [];
try {
const user = await authenticateUser(req, store, config, null, clerkAuth);
custom = (await store.listUserDeviceProfiles?.(user.id) ?? []).map(toPublicProfile);
} catch {
custom = [];
}
return sendJson(res, 200, { profiles: [...builtins, ...custom] });
}
if (req.method === "GET" && url.pathname === "/v1/release-rollouts") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
return sendJson(res, 200, { rollouts: await store.listReleaseRollouts(user.id) });
}
if (req.method === "GET" && url.pathname === "/v1/firmware/releases") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
const releases = await store.listFirmwareReleases({
...(url.searchParams.get("channel") ? { channel: url.searchParams.get("channel") } : {}),
});
return sendJson(res, 200, {
releases: releases.map((release) => ({
id: release.id,
version: release.version,
channel: release.channel,
hardwareModel: release.hardwareModel,
mandatory: release.mandatory,
releaseNotes: release.releaseNotes,
createdAt: release.createdAt,
})),
});
}
if (req.method === "POST" && url.pathname === "/v1/release-rollouts") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const body = await readJson(req);
const input = await validateReleaseRolloutInput({ store, userId: user.id, body });
const rollout = await store.createReleaseRollout({ userId: user.id, ...input });
return sendJson(res, 201, { rollout });
}
const releaseRolloutMatch = url.pathname.match(/^\/v1\/release-rollouts\/([^/]+)$/u);
if (req.method === "GET" && releaseRolloutMatch) {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
const rollout = await store.getReleaseRolloutForUser(user.id, releaseRolloutMatch[1]);
if (!rollout) throw new HttpError(404, "Release rollout not found.");
const assignments = await store.listRolloutAssignments({ userId: user.id, rolloutId: rollout.id });
return sendJson(res, 200, { rollout, assignments });
}
const releaseRolloutActionMatch = url.pathname.match(/^\/v1\/release-rollouts\/([^/]+)\/actions$/u);
if (req.method === "POST" && releaseRolloutActionMatch) {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const body = await readJson(req);
const action = requireString(body.action, "action");
if (!["start", "pause", "resume", "expand", "cancel", "rollback", "complete"].includes(action)) {
throw new HttpError(400, "Unsupported rollout action.");
}
const evidenceRef = validateRolloutEvidenceRef(body.evidenceRef);
const current = await store.getReleaseRolloutForUser(user.id, releaseRolloutActionMatch[1]);
if (!current) throw new HttpError(404, "Release rollout not found.");
if (action === "complete") validateRolloutCompletion(current);
const transition = await store.transitionReleaseRollout({
userId: user.id,
rolloutId: current.id,
action,
evidenceRef,
percentage: body.percentage,
});
if (transition?.conflict) {
throw new HttpError(409, rolloutTransitionMessage(transition.reason));
}
const rollout = transition.rollout;
if (["start", "resume", "expand", "rollback"].includes(action)) {
await releaseRolloutRunner.reconcile(rollout);
} else if (action === "cancel") {
await releaseRolloutRunner.reverseAssignments(rollout);
}
events.broadcastToUser(user.id, "release-rollout.changed", {
rolloutId: rollout.id, state: rollout.state, action, changedAt: new Date().toISOString(),
});
return sendJson(res, 200, {
rollout: await store.getReleaseRolloutForUser(user.id, rollout.id),
assignments: await store.listRolloutAssignments({ userId: user.id, rolloutId: rollout.id }),
});
}
if (req.method === "POST" && url.pathname === "/v1/users/dev") {
if (!isDevTokenCreationEnabled(config)) {
throw new HttpError(403, "Development token creation is disabled.");
}
await enforceRateLimit(req, res, rateLimiter, config, {
scope: "auth",
actorId: clientKey(req),
limit: config.rateLimits?.auth,
});
const body = await readJson(req);
const user = await store.ensureUser({
userId: optionalString(body.userId) ?? "user_dev",
email: optionalString(body.email) ?? "dev@example.local",
});
const apiToken = await store.createUserToken({
userId: user.id,
label: optionalString(body.tokenLabel) ?? "Development token",
});
return sendJson(res, 201, { user, apiToken });
}
if (req.method === "POST" && url.pathname === "/v1/factory/devices") {
authenticateFactory(req, config);
await enforceFactoryWrite(req, res, rateLimiter, config);
const body = await readJson(req);
const profile = requireDeviceProfile(body.profile);
// Defaults to the CrowPanel because it is the one board with a firmware validated end to
// end; an unspecified model should mean the proven one, not an arbitrary one.
const hardwareModel = optionalString(body.hardwareModel) ?? DEFAULT_HARDWARE_BOARD;
const result = await store.preprovisionDevice({
label: requireString(body.label, "label"),
profile,
hardwareModel,
});
const gatewayBaseUrl = optionalString(body.gatewayBaseUrl)
?? config.publicBaseUrl
?? requestBaseUrl(req);
// Claim codes are stored hashed, so this response is the only point at which a scannable
// label can be produced for this device. The device secret is likewise returned once, which
// is why the NVS seed has to be built here too rather than reconstructed later.
return sendJson(res, 201, {
...result,
...claimLabelFor(result, { gatewayBaseUrl }),
nvsSeedFilename: `${result.device.id}.nvs.csv`,
nvsSeed: buildNvsSeedCsv({
deviceId: result.device.id,
deviceSecret: result.secret,
gatewayBaseUrl,
claimCode: result.claimCode,
claimCodeExpiresAt: result.device.claimCodeExpiresAt,
hardwareModel,
}),
// Whoever is flashing this unit needs to know WHICH image, now that there is one per
// board. Without it a correct seed still produces a dead device.
board: describeHardwareBoard(hardwareModel),
});
}
if (url.pathname === "/v1/gateway-profiles" && req.method === "GET") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
return sendJson(res, 200, { profiles: (await store.listGatewayProfiles(user.id)).map(publicGatewayProfile) });
}
if (url.pathname === "/v1/gateway-profiles" && req.method === "POST") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
if ((await store.listGatewayProfiles(user.id)).length >= 5) {
throw new HttpError(409, "A maximum of five gateway profiles is supported per owner.");
}
const input = normalizeGatewayProfileInput(await readJson(req));
const profile = await store.createGatewayProfile({ userId: user.id, ...input });
await publishDeviceRefreshForAll({ store, events, userId: user.id,
resources: ["gateway"] });
return sendJson(res, 201, { profile: publicGatewayProfile(profile) });
}
const gatewayProfileMatch = url.pathname.match(/^\/v1\/gateway-profiles\/([^/]+)$/u);
if (gatewayProfileMatch && req.method === "GET") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
const profile = await store.getGatewayProfileForUser(user.id, gatewayProfileMatch[1]);
if (!profile) throw new HttpError(404, "Gateway profile not found.");
return sendJson(res, 200, { profile: publicGatewayProfile(profile) });
}
if (gatewayProfileMatch && req.method === "PUT") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const existing = await store.getGatewayProfileForUser(user.id, gatewayProfileMatch[1]);
if (!existing) throw new HttpError(404, "Gateway profile not found.");
const input = normalizeGatewayProfileInput(await readJson(req), existing);
const profile = await store.updateGatewayProfile({ userId: user.id, profileId: existing.id, ...input });
if (profile?.conflict) throw new HttpError(409, "Create and stage a new profile before changing an assigned gateway URL.", {
deviceIds: profile.deviceIds,
});
await publishDeviceRefreshForAll({ store, events, userId: user.id,
resources: ["gateway"] });
return sendJson(res, 200, { profile: publicGatewayProfile(profile) });
}
if (gatewayProfileMatch && req.method === "DELETE") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const result = await store.deleteGatewayProfile({ userId: user.id, profileId: gatewayProfileMatch[1] });
if (!result) throw new HttpError(404, "Gateway profile not found.");
if (result.conflict) throw new HttpError(409, "Gateway profile is assigned to a device.", { deviceIds: result.deviceIds });
await publishDeviceRefreshForAll({ store, events, userId: user.id,
resources: ["gateway"] });
return sendJson(res, 200, { profile: publicGatewayProfile(result.profile), deleted: true });
}
if (req.method === "POST" && url.pathname === "/v1/factory/batches") {
authenticateFactory(req, config);
await enforceFactoryWrite(req, res, rateLimiter, config);
const body = await readJson(req);
const count = requireCount(body.count);
const labelPrefix = optionalString(body.labelPrefix) ?? "Agent Controller";
const profile = requireDeviceProfile(body.profile);
const gatewayBaseUrl = optionalString(body.gatewayBaseUrl)
?? config.publicBaseUrl
?? requestBaseUrl(req);
const hardwareModel = optionalString(body.hardwareModel) ?? config.defaultHardwareModel;
const firmwareVersion = optionalString(body.firmwareVersion) ?? "0.1.0";
const devices = [];
for (let index = 0; index < count; index += 1) {
const label = count === 1 ? labelPrefix : `${labelPrefix} ${String(index + 1).padStart(3, "0")}`;
const result = await store.preprovisionDevice({ label, profile });
devices.push({
...result,
...claimLabelFor(result, { gatewayBaseUrl }),
// The NVS seed is the production path: one signed image per batch, identity varied
// by a small data partition. The header stays for bench builds.
nvsSeedFilename: `${result.device.id}.nvs.csv`,
nvsSeed: buildNvsSeedCsv({
deviceId: result.device.id,
deviceSecret: result.secret,
gatewayBaseUrl,
claimCode: result.claimCode,
claimCodeExpiresAt: result.device.claimCodeExpiresAt,
}),
flashConfigFilename: `${result.device.id}.controller_config.h`,
flashConfig: buildFlashConfig({
gatewayBaseUrl,
deviceId: result.device.id,
deviceSecret: result.secret,
environmentId: optionalString(body.environmentId) ?? "env_replace_me",
threadId: optionalString(body.threadId) ?? "thread_replace_me",
defaultPrompt: optionalString(body.defaultPrompt)
?? "Continue the current task, inspect progress, and run relevant tests.",
shellCommand: optionalString(body.shellCommand) ?? "npm test",
hardwareModel,
firmwareVersion,
enableOtaApply: body.enableOtaApply === true,
requireOtaSignature: body.requireOtaSignature === true,
otaManifestVerifyKey: optionalString(body.otaManifestVerifyKey) ?? "",
gatewayTlsRootCaPem: config.gatewayTlsRootCaPem,
gatewayTlsNextRootCaPem: config.gatewayTlsNextRootCaPem,
}),
});
}
return sendJson(res, 201, {
batch: {
count,
profile,
gatewayBaseUrl,
hardwareModel,
firmwareVersion,
enableOtaApply: body.enableOtaApply === true,
requireOtaSignature: body.requireOtaSignature === true,
},
devices,
});
}
if (req.method === "POST" && url.pathname === "/v1/factory/firmware/releases") {
authenticateFactory(req, config);
await enforceFactoryWrite(req, res, rateLimiter, config);
const signingKey = requireOtaSigningKey(config);
const body = await readJson(req);
const input = parseFirmwareRelease(body);
const release = await store.createFirmwareRelease(input);
events.broadcastToAll("firmware.changed", {
action: "released", version: release.version, channel: release.channel,
hardwareModel: release.hardwareModel, mandatory: release.mandatory,
changedAt: new Date().toISOString(),
});
return sendJson(res, 201, {
release: sanitizeFirmwareRelease(release),
manifest: buildFirmwareManifest(release, signingKey),
});
}
if (req.method === "POST" && url.pathname === "/v1/factory/firmware/releases/upload") {
authenticateFactory(req, config);
await enforceFactoryWrite(req, res, rateLimiter, config);
const signingKey = requireOtaSigningKey(config);
if (String(req.headers["content-type"] ?? "").split(";", 1)[0].trim().toLowerCase() !== "application/octet-stream") {
throw new HttpError(415, "Firmware upload must use application/octet-stream.");
}
const contentLength = Number(req.headers["content-length"]);
if (Number.isFinite(contentLength) && contentLength > config.maxFirmwareBytes) {
throw new HttpError(413, `Firmware artifact exceeds ${config.maxFirmwareBytes} bytes.`);
}
const version = requireString(url.searchParams.get("version"), "version");
const channel = optionalString(url.searchParams.get("channel")) ?? "stable";
const hardwareModel = optionalString(url.searchParams.get("hardwareModel")) ?? config.defaultHardwareModel;
const releaseNotes = optionalString(url.searchParams.get("releaseNotes")) ?? "";
const mandatory = url.searchParams.get("mandatory") === "1";
const buffer = await readRawBody(req, config.maxFirmwareBytes);
const artifact = await storeFirmwareArtifact({ config, buffer, hardwareModel, channel, version });
let release;
try {
const input = parseFirmwareRelease({ version, channel, hardwareModel,
url: `/v1/device/firmware/artifacts/${artifact.sha256}`, sha256: artifact.sha256,
sizeBytes: artifact.sizeBytes, mandatory, releaseNotes });
release = await store.createFirmwareRelease({ ...input, artifactKey: artifact.artifactKey,
artifactProvider: artifact.artifactProvider });
} catch (error) {
await deleteFirmwareArtifact(artifact, config).catch(() => {});
throw error;
}
const publicRelease = sanitizeFirmwareRelease(release);
events.broadcastToAll("firmware.changed", {
action: "released", version: release.version, channel: release.channel,
hardwareModel: release.hardwareModel, mandatory: release.mandatory,
changedAt: new Date().toISOString(),
});
const manifestRelease = { ...publicRelease, url: new URL(publicRelease.url, requestBaseUrl(req)).toString() };
return sendJson(res, 201, { release: publicRelease, manifest: buildFirmwareManifest(manifestRelease, signingKey), managedArtifact: true });
}
if (req.method === "GET" && url.pathname === "/v1/factory/firmware/releases") {
authenticateFactory(req, config);
await enforceFactoryWrite(req, res, rateLimiter, config);
const hardwareModel = optionalString(url.searchParams.get("hardwareModel"));
const channel = optionalString(url.searchParams.get("channel"));
return sendJson(res, 200, {
releases: await store.listFirmwareReleases({ hardwareModel, channel }),
});
}
const factoryFirmwareReleaseMatch = url.pathname.match(/^\/v1\/factory\/firmware\/releases\/([^/]+)$/u);
if (req.method === "DELETE" && factoryFirmwareReleaseMatch) {
authenticateFactory(req, config);
await enforceFactoryWrite(req, res, rateLimiter, config);
const release = await store.deleteFirmwareRelease(factoryFirmwareReleaseMatch[1]);
if (!release) throw new HttpError(404, "Firmware release not found.");
await deleteFirmwareArtifact(release, config);
events.broadcastToAll("firmware.changed", {
action: "withdrawn", version: release.version, channel: release.channel,
hardwareModel: release.hardwareModel, changedAt: new Date().toISOString(),
});
return sendJson(res, 200, { release: sanitizeFirmwareRelease(release), deleted: true });
}
if (req.method === "POST" && url.pathname === "/v1/devices") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const body = await readJson(req);
await assertWithinPlan(store, user.id, "devices", config);
const profile = await requireOwnedDeviceProfile(store, user.id, body.profile);
assertSecureTransport(req, config, "Device secret delivery");
const result = await store.createDevice({
userId: user.id,
label: requireString(body.label, "label"),
profile,
});
return sendJson(res, 201, result);
}
if (req.method === "POST" && url.pathname === "/v1/devices/claim") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const body = await readJson(req);
await assertWithinPlan(store, user.id, "devices", config);
assertSecureTransport(req, config, "Device secret delivery");
const device = await store.claimDevice({
userId: user.id,
claimCode: requireString(body.claimCode, "claimCode"),
label: optionalString(body.label),
});
if (!device) throw new HttpError(404, "Claim code is invalid, expired, or already used.");
return sendJson(res, 200, { device });
}
const deviceActionMatch = url.pathname.match(/^\/v1\/devices\/([^/]+)\/(revoke|rotate-secret|transfer-reset)$/u);
if (req.method === "POST" && deviceActionMatch) {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const [, deviceId, action] = deviceActionMatch;
if (action === "revoke") {
const device = await store.revokeDevice({ userId: user.id, deviceId });
if (!device) throw new HttpError(404, "Device not found.");
events.broadcastToUser(user.id, "device.refresh", {
deviceId, resources: ["config", "controls", "display"], reason: "revoked",
changedAt: new Date().toISOString(),
});
return sendJson(res, 200, { device });
}
if (action === "transfer-reset") {
const body = await readJson(req);
assertSecureTransport(req, config, "Device secret delivery");
const result = await store.resetDeviceForTransfer({
userId: user.id,
deviceId,
label: optionalString(body.label),
});
if (!result) throw new HttpError(404, "Device not found or revoked.");
events.broadcastToUser(user.id, "device.refresh", {
deviceId, resources: ["config", "controls", "display"], reason: "transfer-reset",
changedAt: new Date().toISOString(),
});
return sendJson(res, 200, result);
}
assertSecureTransport(req, config, "Device secret delivery");
const body = await readJson(req).catch(() => ({}));
const result = await store.rotateDeviceSecret({
userId: user.id,
deviceId,
restart: body?.restart === true,
});
if (!result) throw new HttpError(404, "Device not found or revoked.");
events.broadcastToUser(user.id, "device.refresh", {
deviceId, resources: ["config", "controls", "display"], reason: "secret-rotation-started",
changedAt: new Date().toISOString(),
});
return sendJson(res, 200, result);
}
// Permanently removes a revoked device from the inventory. Revocation first is deliberate:
// it kills the credential, so the record can go without leaving hardware in the field that
// still authenticates against a device the owner can no longer see.
const deviceDeleteMatch = url.pathname.match(/^\/v1\/devices\/([^/]+)$/u);
if (req.method === "DELETE" && deviceDeleteMatch) {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const result = await store.deleteDevice({ userId: user.id, deviceId: deviceDeleteMatch[1] });
if (!result) throw new HttpError(404, "Device not found.");
if (result.reason === "not_revoked") {
throw new HttpError(409, "Revoke the device before deleting it.");
}
return sendJson(res, 200, { device: result.device, deleted: true });
}
const deviceConfigMatch = url.pathname.match(/^\/v1\/devices\/([^/]+)\/config$/u);
if (deviceConfigMatch && req.method === "GET") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
const device = await store.getDeviceForUser(user.id, deviceConfigMatch[1]);
if (!device) throw new HttpError(404, "Device not found.");
return sendJson(res, 200, { deviceId: device.id, config: device.config });
}
if (deviceConfigMatch && req.method === "PUT") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const body = await readJson(req);
if (Object.hasOwn(body, "label")) body.label = requireString(body.label, "label");
if (Object.hasOwn(body, "gatewayAccessMode") && !["local", "tailscale", "online"].includes(body.gatewayAccessMode)) {
throw new HttpError(400, "gatewayAccessMode must be local, tailscale, or online.");
}
if (Object.hasOwn(body, "gatewayUrl") && body.gatewayUrl !== null && body.gatewayUrl !== "") {
const gatewayUrl = requireString(body.gatewayUrl, "gatewayUrl");
let parsedGatewayUrl;
try {
parsedGatewayUrl = new URL(gatewayUrl);
} catch {
throw new HttpError(400, "gatewayUrl must be a valid HTTP or HTTPS URL.");
}
if (!["http:", "https:"].includes(parsedGatewayUrl.protocol)) {
throw new HttpError(400, "gatewayUrl must be a valid HTTP or HTTPS URL.");
}
if (body.gatewayAccessMode && body.gatewayAccessMode !== "local" && parsedGatewayUrl.protocol !== "https:") {
throw new HttpError(400, "Remote gateway URLs must use HTTPS.");
}
}
const environmentId = optionalString(body.environmentId);
if (environmentId && !(await store.getEnvironmentForUser(user.id, environmentId))) {
throw new HttpError(404, "Environment not found.");
}
const device = await store.updateDeviceConfig({
userId: user.id,
deviceId: deviceConfigMatch[1],
config: body,
});
if (!device) throw new HttpError(404, "Device not found.");
events.broadcastToUser(user.id, "device.refresh", {
deviceId: device.id, resources: ["config", "threads", "controls", "display"],
changedAt: new Date().toISOString(),
});
return sendJson(res, 200, { deviceId: device.id, config: device.config, device });
}
const ownerDeviceGatewayMatch = url.pathname.match(/^\/v1\/devices\/([^/]+)\/gateway$/u);
if (ownerDeviceGatewayMatch && req.method === "GET") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
const device = await store.getDeviceForUser(user.id, ownerDeviceGatewayMatch[1]);
if (!device) throw new HttpError(404, "Device not found.");
return sendJson(res, 200, await deviceGatewayResponse(store, device));
}
if (ownerDeviceGatewayMatch && req.method === "PUT") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const device = await store.getDeviceForUser(user.id, ownerDeviceGatewayMatch[1]);
if (!device) throw new HttpError(404, "Device not found.");
const body = await readJson(req);
const profileId = requireString(body.profileId, "profileId");
if (!(await store.getGatewayProfileForUser(user.id, profileId))) throw new HttpError(404, "Gateway profile not found.");
const selection = await store.stageDeviceGatewaySwitch({ userId: user.id, deviceId: device.id, profileId });
if (!selection) throw new HttpError(409, "Gateway switch could not be staged.");
events.broadcastToUser(user.id, "device.refresh", {
deviceId: device.id, resources: ["gateway", "display"], changedAt: new Date().toISOString(),
});
return sendJson(res, 200, await deviceGatewayResponse(store, device, selection));
}
const ownerGatewayRollbackMatch = url.pathname.match(/^\/v1\/devices\/([^/]+)\/gateway\/rollback$/u);
if (ownerGatewayRollbackMatch && req.method === "POST") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const device = await store.getDeviceForUser(user.id, ownerGatewayRollbackMatch[1]);
if (!device) throw new HttpError(404, "Device not found.");
const selection = await store.rollbackDeviceGatewaySwitch({ userId: user.id, deviceId: device.id });
events.broadcastToUser(user.id, "device.refresh", {
deviceId: device.id, resources: ["gateway", "display"], changedAt: new Date().toISOString(),
});
return sendJson(res, 200, await deviceGatewayResponse(store, device, selection));
}
const deviceControlsMatch = url.pathname.match(/^\/v1\/devices\/([^/]+)\/controls$/u);
if (deviceControlsMatch && req.method === "GET") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserRead(req, res, rateLimiter, config, user);
const device = await store.getDeviceForUser(user.id, deviceControlsMatch[1]);
if (!device) throw new HttpError(404, "Device not found.");
const stored = await store.getDeviceControls({ userId: user.id, deviceId: device.id });
return sendJson(res, 200, {
deviceId: device.id,
controls: await resolveDeviceControls({ store, device, stored, config }),
layout: stored,
});
}
if (deviceControlsMatch && req.method === "PUT") {
const user = await authenticateUser(req, store, config, null, clerkAuth);
await enforceUserWrite(req, res, rateLimiter, config, user);
const device = await store.getDeviceForUser(user.id, deviceControlsMatch[1]);
if (!device) throw new HttpError(404, "Device not found.");
const body = await readJson(req);
const menuItems = Number(device.status?.limits?.menuItems) || 8;
const items = normalizeDeviceControlItems(body.controls ?? body.items, { menuItems });
await validateDeviceControlAssignments({ store, device, items, config });
const layout = await store.updateDeviceControls({ userId: user.id, deviceId: device.id, items });
if (!layout) throw new HttpError(404, "Device not found or revoked.");
events.broadcastToUser(user.id, "device.refresh", {