Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
1108 lines (1033 loc) · 59.9 KB
/
Copy pathserver.ts
File metadata and controls
1108 lines (1033 loc) · 59.9 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
// alate server: provisioning API + inventory dashboard UI (single server; the standalone dashboard server was folded in).
// Run directly: node server.ts (Node type stripping, no build step).
import { spawn } from 'node:child_process'
import type { ChildProcess } from 'node:child_process'
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { randomBytes, timingSafeEqual } from 'node:crypto'
import { dirname, join } from 'node:path'
import { DatabaseSync } from 'node:sqlite'
import { setTimeout as delay } from 'node:timers/promises'
import type { AddressInfo } from 'node:net'
import type { FastifyError, FastifyReply, FastifyRequest } from 'fastify'
import fastify from 'fastify'
import { childEnv, DEFAULT_GITHUB_HOST, EXEC_PATHS_ENV, keepTemp, parseDataSpec, PROVISION_ENV, redactSecrets } from './lib/data.mjs'
import { runBundleAction, runCleanup, runEdit, runEntryAction, runImport, runSnapshot } from './lib/server-worker.mjs'
import { getTrustedPathSource, isGitWorkTree, isWritableDir, listStoredFiles, loadState, readStoredFile, remoteAhead, remoteHead, setTrustedPathSource } from './web/dashboard.mjs'
import type { StateDef } from './web/dashboard.mjs'
import { checkUpdates, initUpdates, isValidUpdateRecord, loadUpdates } from './lib/updates.mjs'
import { ensureEnvProxy } from './lib/env-proxy.mjs'
import { watchParentDeath } from './lib/parent-death.mjs'
// Node honors proxy env vars for fetch only with proxy support enabled: the built-in
// http.setGlobalProxyFromEnv() (Node 24.14+) applies them in-process, and on 24.12-24.13
// lib/env-proxy.mjs re-spawns once with NODE_USE_ENV_PROXY=1 (the image sets it).
await ensureEnvProxy()
// Test-fixture tie: the fixture holds our stdin pipe and drops it exactly when the test
// runner dies -- a Stryker hang timeout SIGKILLs the runner -- so stdin EOF means the
// runner is gone and this server must not outlive it. The watch lives in
// lib/parent-death.mjs, outside the server's mutate set: a Stryker StringLiteral mutant
// over the flag here could silence the guard for a whole mutation run and let fixture
// servers outlive their runner again.
watchParentDeath()
const repoRoot = import.meta.dirname
const CONFIG_FILE = flagValue('--config') ?? join(repoRoot, 'server-config.json')
const CAP = 200000
const SCRIPTS = ['sync.mjs', 'install-user.mjs', 'install-projects.mjs']
// A provision child that never exits (the audit's turn-planted FIFO at a bookkeeping read)
// would hold the provision lock forever, and /provision, /config, /api/import and editor
// writes would answer 409 until restart. SIGTERM at the deadline, SIGKILL after the grace
// period; the numbers are a gate decision, not a tuning knob.
const PROVISION_CHILD_TIMEOUT_MS = 10 * 60 * 1000
const PROVISION_CHILD_KILL_GRACE_MS = 5000
// After SIGKILL, how long the run still waits for the streams before it detaches from them.
const PROVISION_CHILD_DETACH_MS = 1000
// Test seams for the provision deadline: [gate env key, child source]. While the gate
// file exists, the provision child runs that source instead of its script. Every child
// that leaves orphans prints their PIDs, so a fixture can stop them after its case.
const ORPHAN_CHAIN_A = "const { spawn } = require('node:child_process'); const b = spawn(process.execPath, ['-e', 'setInterval(() => {}, 3_600_000)'], { stdio: 'inherit', detached: true }); require('node:fs').writeSync(1, 'chain ' + process.argv[1] + ' ' + process.pid + ' ' + b.pid + ' exit 0\\n'); process.exit(0)"
const DEADLINE_SEAMS: [string, string][] = [
// a child that never exits
['ALATE_TEST_CHILD_HANG', 'setInterval(() => {}, 3_600_000)'],
// a hung parent whose grandchild inherits the streams
['ALATE_TEST_CHILD_HANG_TREE', "const { spawn } = require('node:child_process'); const g = spawn(process.execPath, ['-e', 'setInterval(() => {}, 3_600_000)'], { stdio: 'inherit' }); require('node:fs').writeSync(1, 'parent ' + process.pid + ' grandchild ' + g.pid + ' hang\\n'); setInterval(() => {}, 3_600_000)"],
// a parent that exits 0 at once while its grandchild keeps the streams
['ALATE_TEST_CHILD_EXIT0_TREE', "const { spawn } = require('node:child_process'); const g = spawn(process.execPath, ['-e', 'setInterval(() => {}, 3_600_000)'], { stdio: 'inherit' }); require('node:fs').writeSync(1, 'parent ' + process.pid + ' grandchild ' + g.pid + ' exit 0\\n'); process.exit(0)"],
// P→A→B: P and A exit 0 at once, and B, in a process group of its own, keeps the streams
['ALATE_TEST_CHILD_ORPHAN_CHAIN', `const { spawn } = require('node:child_process'); spawn(process.execPath, ['-e', ${JSON.stringify(ORPHAN_CHAIN_A)}, String(process.pid)], { stdio: 'inherit' }); process.exit(0)`],
]
// Signals the child's process tree as far as it is provably ours. install-user.mjs spawns
// bun with inherited stdout and stderr (the plugin gate), so a hung grandchild can retain
// the provision pipes after the direct child dies. On POSIX the child leads its own
// process group, and while the child is unreaped its PID pins that PGID, so the group
// signal reaches only the provision tree; once the child is gone, the number may name a
// stranger, so nothing is signalled. Windows has no process groups and reuses PIDs
// quickly, so every PID-based route there is unprovable: a dead child's PID can name an
// unrelated process, an orphan of an older owner of that PID can carry it as its
// ParentProcessId, and a walk from the child cannot reach a descendant whose own parent
// already left. Windows therefore signals only the direct child, through the handle Node
// holds. A descendant that no signal reaches is detached from after SIGKILL (see the
// deadline below). Test seam: ALATE_TEST_SIGNAL_PLATFORM selects the branch on a POSIX
// CI host.
function signalTree(child: ChildProcess, signal: 'SIGTERM' | 'SIGKILL'): void {
if ((process.env.ALATE_TEST_SIGNAL_PLATFORM ?? process.platform) === 'win32') {
child.kill(signal)
return
}
if (child.exitCode !== null || child.signalCode !== null) return
try { process.kill(-child.pid!, signal) } catch { /* the group is already gone */ }
}
const KNOWN_ROUTES = ['/health', '/config', '/provision', '/api/updates', '/api/updates/check', '/api/files', '/api/file', '/api/bundle', '/api/entry']
const testChildEnvCapture = process.env.ALATE_TEST_CHILD_ENV
// Test hook: a server that ignores SIGTERM exercises the test suite's teardown escalation;
// only the process-group SIGKILL fallback stops it.
if (process.env.ALATE_TEST_SIGTERM === 'ignore') process.on('SIGTERM', () => {})
interface UpdateState { lastChecked: string | null; remoteSha: string; provisionedSha: string }
interface Config {
apiKey: string | null
repo: string | null
path: string | null
token: string | null
// A repo import named this host: the stored token is presumed to belong to it, so the
// update checker never sends the token to github.com. Sticky by design; see noteTokenHost.
tokenHost: string | null
autoUpdate: boolean
securityFastPath: boolean
// Workspace that holds the project checkouts install-projects.mjs writes into. Null
// derives it from the source dir for a path source; a repo source needs it set once,
// because the server's clone is temporary (specs/install-projects.md).
projectsRoot: string | null
update: UpdateState
}
interface ProvisionResult { script: string; code: number | null; output: string; truncated: boolean }
// One provisioning item's per-item outcome, as written to the results file by the script
// (specs/provision-item-by-item.md). rule/at name the first finding for a failed item.
interface ProvisionItem { item: string; status: 'installed' | 'unchanged' | 'added' | 'updated' | 'inconclusive' | 'rejected' | 'no-origin'; rule: string | null; at: string | null; report?: string }
// Stored on the dashboard state after every provision run; served by GET /api/state. sha pins
// the results to the imported snapshot, so a stale set is never shown for a newer snapshot.
// failures holds the scripts of a whole-run failure (non-zero exit or null code) with their
// captured output, so a refusal or a crashed child is visible when items alone show nothing.
interface ProvisionState { at: string; sha: string | null; ok: boolean; items: ProvisionItem[]; failures: ProvisionResult[]; lostSkills: number }
function loadConfig(): Config {
try {
const cfg = JSON.parse(readFileSync(CONFIG_FILE, 'utf8')) as Config
cfg.autoUpdate ??= false
cfg.securityFastPath ??= true
cfg.tokenHost ??= null
cfg.projectsRoot ??= null
cfg.update ??= { lastChecked: null, remoteSha: '', provisionedSha: '' }
return cfg
} catch {
const cfg: Config = { apiKey: null, repo: null, path: null, token: null, tokenHost: null, autoUpdate: false, securityFastPath: true, projectsRoot: null, update: { lastChecked: null, remoteSha: '', provisionedSha: '' } }
saveConfig(cfg)
return cfg
}
}
// A temp file in the config's own folder, then a rename over the config file: a sibling
// read (and a crash mid-save) sees the whole old file or the whole new one, never a cut
// one. The periodic dashboard check saves on every tick, so an in-place write raced readers.
// O_EXCL ('wx') creates the temp file fresh and never writes through a planted name. The
// chmod sets 0600 whatever the umask: an owner-bit umask (0400) would otherwise leave a
// file that a non-root restart cannot read, and loadConfig would drop the saved key. As
// before, a file system that refuses chmod keeps the created mode. A failed save removes
// only the temp file it created.
function saveConfig(cfg: Config): void {
const tmp = `${CONFIG_FILE}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`
try {
writeFileSync(tmp, JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
try { chmodSync(tmp, 0o600) } catch {}
renameSync(tmp, CONFIG_FILE)
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'EEXIST') rmSync(tmp, { force: true })
throw err
}
}
const config = loadConfig()
if (!config.apiKey) {
const envKey = process.env.ALATE_API_KEY
if (envKey !== undefined && envKey.length < 32) {
console.error('ALATE_API_KEY is set but shorter than 32 characters; refusing to start, because the paired board would then fail silently')
process.exit(1)
}
if (envKey !== undefined) {
config.apiKey = envKey
saveConfig(config)
console.log('alate API key: taken from ALATE_API_KEY')
} else {
config.apiKey = randomBytes(32).toString('base64url')
saveConfig(config)
console.log(`alate API key: ${config.apiKey}`)
}
}
const dbFile = flagValue('--db') ?? join(dirname(CONFIG_FILE), 'alate.db')
mkdirSync(dirname(dbFile), { recursive: true })
const db = new DatabaseSync(dbFile)
// The worker thread writes the same file during imports and edits: a main-thread write that
// lands inside the worker's transaction waits instead of throwing a bare lock error. The
// bound stays small because a main-thread wait blocks the event loop; a check that collides
// anyway (one already in flight from boot) fails fast and its bounded retry absorbs it.
// The worker gets a generous bound instead: its waits never touch the loop.
db.exec('PRAGMA busy_timeout = 50')
// WAL keeps main-thread reads working while the worker's import transaction runs: a
// large import spills its page cache and then holds the writer lock until COMMIT, and
// in rollback-journal mode every /api/state, /api/files and /api/file read would wait
// out the busy timeout and fail. WAL readers see the last committed snapshot instead.
db.exec('PRAGMA journal_mode = WAL')
// Cap the -wal sidecar at 64 MiB once checkpoints run, so a large import never leaves
// a sidecar that grows with the snapshot size.
db.exec('PRAGMA journal_size_limit = 67108864')
if (process.platform !== 'win32') chmodSync(dbFile, 0o600)
db.exec(`
CREATE TABLE IF NOT EXISTS state (id INTEGER PRIMARY KEY CHECK (id = 1), value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, content BLOB NOT NULL);
CREATE TABLE IF NOT EXISTS exec_index (id INTEGER PRIMARY KEY CHECK (id = 1), paths TEXT NOT NULL);
`)
initUpdates(db)
let running = false
// One file edit at a time, and never during a provision. Edits run in the worker thread, but
// `writing` still serializes concurrent edit requests in-process; `running` (provision) is the
// check tests can reach.
let writing = false
// Worse status wins when both scripts report the same item key. `added` and `updated` are
// the layer-mode labels of `installed`: they rank the same.
const STATUS_RANK: Record<ProvisionItem['status'], number> = { unchanged: 0, installed: 1, added: 1, updated: 1, inconclusive: 2, 'no-origin': 3, rejected: 4 }
const REPORT_CAP = 4000
// Read one child's results file (specs/provision-item-by-item.md). A missing or unparseable
// file means no data; the caller fails closed on it.
function readProvisionResults(file: string): { fatal: boolean; lostSkills: number; items: { item: string; status: ProvisionItem['status']; rule?: unknown; at?: unknown; report?: unknown }[] } | null {
try {
const parsed = JSON.parse(readFileSync(file, 'utf8'))
if (!parsed || typeof parsed.fatal !== 'boolean' || !Array.isArray(parsed.items)) return null
// lostSkills (specs/baseline-version-lockstep.md): anything but a non-negative safe integer counts 0.
return { ...parsed, lostSkills: Number.isSafeInteger(parsed.lostSkills) && parsed.lostSkills >= 0 ? parsed.lostSkills : 0 }
} catch {
return null
}
}
async function provision(): Promise<{ results: ProvisionResult[]; copiedSha: string | null }> {
// The snapshot copy writes every stored byte: it runs in the worker thread, so the
// event loop stays free while it runs.
snapshotting = true
let dir: string
let execPaths: string[] | null = null
try {
const snapshot = await runSnapshot({ dbFile })
dir = snapshot.dir
execPaths = snapshot.execPaths
} finally {
snapshotting = false
runDeferredCheck()
}
// The copy holds the source as of this moment. A queued import or edit that lands
// while the scripts run reassigns dashState; reading it again below would record the
// commit stored at the end instead of the one the copied bytes hold, and /health
// would then hide the provision the board still needs.
const copiedSource = dashState.source
const tmp = mkdtempSync(join(tmpdir(), 'alate-provision-'))
try {
// Exec truth for the snapshot copy (specs/canonical-form.md): the import recorded the
// source index's exec list when it saw one, and the scripts read it through
// ALATE_EXEC_PATHS because the snapshot dir has no .git. No record: the scripts keep
// every existing file's mode and create fresh files 0644, so a provision whose source
// carried no modes never demotes an installed hook or script.
const execFile = execPaths ? join(tmp, 'exec-paths.json') : null
if (execFile) writeFileSync(execFile, JSON.stringify({ execPaths }), { mode: 0o600 })
// --root for install-projects.mjs: the operator-configured projects workspace, or the
// source's parent dir for a path source, because the snapshot copy is temporary and
// the real project checkouts live beside it (specs/install-projects.md).
const projectsRoot = config.projectsRoot ?? (copiedSource?.kind === 'path' && copiedSource.name ? dirname(copiedSource.name) : null)
const results: ProvisionResult[] = []
const merged = new Map<string, ProvisionItem>()
let lostSkills = 0
for (const script of SCRIPTS) {
const resultsFile = join(tmp, `${script}.results.json`)
const env = childEnv()
// Test seam: while the gate file exists, drop the results-file path so a child can
// exit non-zero with no results file, exercising the pipeline's fail-closed branch.
const noResultsGate = process.env.ALATE_TEST_NO_RESULTS_FILE
if (!(noResultsGate && existsSync(noResultsGate))) env[PROVISION_ENV] = resultsFile
if (execFile) env[EXEC_PATHS_ENV] = execFile
// The snapshot dir has no .git, so install-user.mjs cannot read the imported commit
// itself: the server passes it for a repo source, and a layer id then carries it
// instead of "nogit" (specs/agent-layer-switch.md). A path source gets no --commit,
// so the git probe in install-user.mjs keeps its nogit fallback.
const importedSha = copiedSource?.kind === 'repo' ? copiedSource.importedSha ?? '' : ''
const commitArg = script === 'install-user.mjs' && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(importedSha) ? ['--commit', importedSha] : []
// Test seam, mirroring the ALATE_TEST_NO_RESULTS_FILE gate above: while a gate file
// exists, the child is the matching DEADLINE_SEAMS shape instead of the script, so
// the deadline below is exercised without hanging a real provisioning script.
const seam = DEADLINE_SEAMS.find(([key]) => { const gate = process.env[key]; return !!gate && existsSync(gate) })
const childArgs = seam
? ['-e', seam[1]]
: [join(repoRoot, script), '--data', dir, ...commitArg, ...(script === 'install-projects.mjs' && projectsRoot ? ['--root', projectsRoot] : [])]
const child = spawn(process.execPath, childArgs, {
cwd: repoRoot,
env,
// A group leader on POSIX, so signalTree can reach grandchildren that inherited
// the child's stdio (the plugin gate's bun spawn).
detached: process.platform !== 'win32',
})
if (testChildEnvCapture) writeFileSync(testChildEnvCapture, JSON.stringify(childEnv()))
let output = ''
child.stdout.on('data', (d: Buffer) => { if (output.length < CAP + 1000) output += d })
child.stderr.on('data', (d: Buffer) => { if (output.length < CAP + 1000) output += d })
// Audit (install-user.mjs:alate-bookkeeping-read:blocking-open-of-turn-planted-fifo):
// a turn-planted FIFO at a bookkeeping path could hang a provision child forever, and
// while any provision child runs, /provision, /config, /api/import and editor writes
// answer 409, so the deadlined kill is defense in depth: SIGTERM at the deadline,
// SIGKILL after the grace period. The killed child then closes with a null code and
// the run fails closed below, like any other killed child.
const childTimeoutMs = Number(process.env.ALATE_TEST_CHILD_TIMEOUT_MS) || PROVISION_CHILD_TIMEOUT_MS
const { promise: closed, resolve, reject } = Promise.withResolvers<number | null>()
child.on('close', code => resolve(code))
child.on('error', reject)
let timedOut = false
let detached = false
let killGrace: NodeJS.Timeout | undefined
let detach: NodeJS.Timeout | undefined
const deadline = setTimeout(() => {
timedOut = true
signalTree(child, 'SIGTERM')
killGrace = setTimeout(() => {
signalTree(child, 'SIGKILL')
// A descendant that no signal reaches any more (it left the process group, or
// any descendant on Windows, where only the direct child is provably ours) keeps
// the inherited streams open, and `close` would never fire. Stop waiting: drop
// the server's pipe ends and finish the run as killed, so the lock clears.
detach = setTimeout(() => {
detached = true
child.stdout.destroy()
child.stderr.destroy()
resolve(null)
}, PROVISION_CHILD_DETACH_MS)
}, PROVISION_CHILD_KILL_GRACE_MS)
}, childTimeoutMs)
// The timers must not outlive the await: a spawn error rejects here, and an armed
// deadline would keep the event loop alive for its full span.
let captured: number | null
try {
captured = await closed
} finally {
clearTimeout(deadline)
clearTimeout(killGrace)
clearTimeout(detach)
}
// The deadline kill must fail the run even when the parent already exited 0 and only
// a background descendant kept the streams open: the tree the script started was
// torn down, so the run never completed normally. The null code rides the same
// fail-closed branch as any other killed child.
const code = timedOut ? null : captured
const truncated = output.length > CAP
const raw = truncated ? output.slice(0, CAP) : output
// The deadline line is server-generated (no child bytes, no secrets), so it is safe
// to append after the CAP truncation.
const stored = timedOut ? `${raw}\nprovision deadline: ${script} exceeded ${childTimeoutMs} ms; SIGTERM then SIGKILL sent${detached ? '; a surviving descendant still held the output streams, so they were detached, not drained' : ''}` : raw
results.push({ script, code, output: redactSecrets(stored, dashToken()), truncated })
// Merge per-item results by stable key; the worse status wins, and reports join.
const parsed = readProvisionResults(resultsFile)
if (parsed) {
lostSkills += parsed.lostSkills
for (const entry of parsed.items) {
if (!entry || typeof entry.item !== 'string' || !(entry.status in STATUS_RANK)) continue
const status = entry.status
const rule = typeof entry.rule === 'string' ? entry.rule : null
const at = typeof entry.at === 'string' ? entry.at : null
const report = typeof entry.report === 'string' && entry.report
? entry.report.length > REPORT_CAP ? redactSecrets(entry.report.slice(0, REPORT_CAP) + '…', dashToken()) : redactSecrets(entry.report, dashToken())
: undefined
const prev = merged.get(entry.item)
if (!prev) {
merged.set(entry.item, { item: entry.item, status, rule, at, ...(report ? { report } : {}) })
continue
}
const joined = [prev.report, report].filter(Boolean).join('\n')
if (joined) prev.report = joined.length > REPORT_CAP ? joined.slice(0, REPORT_CAP) + '…' : joined
if (STATUS_RANK[status] > STATUS_RANK[prev.status]) Object.assign(prev, { status, rule, at })
}
}
// Fail closed only on true refusals: a killed child, or a non-zero exit whose results
// file is missing or says the whole run was refused. A per-item failure (non-zero exit
// with fatal: false) never stops the pipeline (specs/provision-item-by-item.md).
if (code === null || (code !== 0 && (parsed === null || parsed.fatal))) break
}
dashState.provision = {
at: new Date().toISOString(),
sha: copiedSource?.importedSha || null,
ok: results.every(r => r.code === 0),
items: [...merged.values()].sort((a, b) => (a.item < b.item ? -1 : a.item > b.item ? 1 : 0)),
failures: results.filter(r => r.code !== 0),
lostSkills,
} satisfies ProvisionState
persistDash()
return { results, copiedSha: copiedSource?.importedSha || null }
} finally {
rmSync(tmp, { recursive: true, force: true })
// Same guard cleanupData applied: ALATE_KEEP_TEMP keeps every temp dir for
// strict no-delete runs. The rm itself runs in the worker thread.
if (!keepTemp()) await runCleanup(dir)
runDeferredCheck()
}
}
function isDir(p: string): boolean {
try { return statSync(p).isDirectory() } catch { return false }
}
function repoValid(repo: string): boolean {
return isDir(repo) || parseDataSpec(repo) !== null
}
const app = fastify({ bodyLimit: 1024 * 1024, logger: false })
function keyMatch(a: string, b: string): boolean {
const x = Buffer.from(a)
const y = Buffer.from(b)
return x.length === y.length && timingSafeEqual(x, y)
}
function authorized(req: FastifyRequest): boolean {
const m = /^Bearer (.+)$/s.exec(req.headers.authorization ?? '')
return !!m && keyMatch(m[1], config.apiKey ?? '')
}
// The provisioning API (/config, /provision, /api/updates) always needs the key, on every
// bind: one shared guard so the three routes cannot drift apart.
async function keyGuard(req: FastifyRequest, reply: FastifyReply): Promise<void | FastifyReply> {
if (!authorized(req)) return reply.code(401).send({ error: 'unauthorized' })
}
// Dashboard handlers map a thrown Error to its client-safe message and optional status,
// so the response shape cannot drift between them.
function clientError(reply: FastifyReply, err: unknown): FastifyReply {
const e = err as { status?: number; message?: string } // dashboard.mjs throws Error with a client-safe message and .status
return reply.code(e.status ?? 500).send({ error: e.message })
}
// Dashboard sessions: random ids held only in memory, so a cookie carries nothing
// derived from the key, a restart ends every session, and a rotation (POST /api/key)
// clears the store. Browsers do not isolate cookies by port: another service on the
// same host name can receive this cookie, so key rotation also asks for the current key.
const SESSION_MAX_AGE_S = 30 * 24 * 60 * 60
const sessions = new Map<string, number>() // session id -> expiry (ms since epoch)
function newSession(): string {
const now = Date.now()
for (const [id, exp] of sessions) if (exp <= now) sessions.delete(id)
const id = randomBytes(32).toString('hex')
sessions.set(id, now + SESSION_MAX_AGE_S * 1000)
return id
}
// A sibling service can set its own alate_session cookie on this host name, so every
// value in the header is checked, not only the first one.
function sessionValid(header: string): boolean {
const now = Date.now()
for (const m of header.matchAll(/(?:^|;\s*)alate_session=([a-f0-9]{64})(?=;|$)/g)) {
const exp = sessions.get(m[1])
if (exp !== undefined && exp > now) return true
}
return false
}
function sameOrigin(req: FastifyRequest): boolean {
const raw = req.headers.origin ?? req.headers.referer
if (typeof raw !== 'string' || !req.headers.host) return false
try { return new URL(raw).host === req.headers.host } catch { return false }
}
function cookieAuthed(req: FastifyRequest): boolean {
const header = req.headers.cookie ?? ''
if (!header.includes('alate_session=')) return false
// CSRF: a browser attaches the cookie to cross-site POSTs too, so a cookie write must
// carry a same-origin Origin header (browsers send it on every non-GET request).
if (req.method !== 'GET' && req.method !== 'HEAD' && !sameOrigin(req)) return false
return sessionValid(header)
}
// Non-loopback binds (--host 0.0.0.0, Docker, NAS) expose the dashboard to the network:
// dashboard routes that read or change repo state then need the provisioning key, as a
// Bearer token or a login cookie. Loopback-only binds stay key-free.
async function dashGuard(req: FastifyRequest, reply: FastifyReply): Promise<void | FastifyReply> {
if (authorized(req) || cookieAuthed(req)) return
if (!loopbackBind) return reply.code(401).send({ error: 'unauthorized' })
// A reverse proxy on the same host reaches a loopback bind from loopback and can send a
// loopback Host (nginx's default proxy_set_header Host $proxy_host), so the Host gate
// passes for remote clients. A forwarding header marks such a request: it needs the key.
const h = req.headers
if (h['x-forwarded-for'] !== undefined || h.forwarded !== undefined || h['x-real-ip'] !== undefined) return reply.code(401).send({ error: 'unauthorized' })
// The loopback bind is key-free, but a browser write carries no key: without the
// sameOrigin check, any web page could ride this shortcut with a no-cors POST
// (no preflight) and change dashboard state.
// Browsers send Origin on every non-GET request, and the dashboard's own requests
// are same-origin; scripts keep using the Bearer path above. DNS rebinding makes a
// hostile page's Origin equal its Host, so that check alone passes; the loopback
// Host gate registered near listen() covers that case.
if (req.method !== 'GET' && req.method !== 'HEAD' && !sameOrigin(req)) return reply.code(401).send({ error: 'unauthorized' })
}
// Fastify's default JSON parser refuses a request that carries a JSON content type
// with no body (FST_ERR_CTP_EMPTY_JSON_BODY), and board clients send exactly that to
// POST /provision. Parse an empty or whitespace-only JSON body as {} instead:
// /provision reads no fields, and every other route treats a missing field as absent.
// A malformed non-empty body fails as FST_ERR_CTP_INVALID_JSON, so the error handler
// below keeps its 400 `invalid JSON body` answer.
app.addContentTypeParser('application/json', { parseAs: 'string' }, (_req, body: string, done) => {
if (body.trim() === '') return done(null, {})
try {
return done(null, JSON.parse(body) as unknown)
} catch {
return done(Object.assign(new Error('invalid JSON body'), { code: 'FST_ERR_CTP_INVALID_JSON', statusCode: 400 }), undefined)
}
})
// Auth model: the provisioning API (/config, /provision, /api/updates) always needs
// the key. Dashboard routes use dashGuard: key-free on a loopback bind without proxy
// headers, Bearer token or login cookie otherwise. The static shell and /theme.js stay public so a
// browser can load the page and then ask for the key once (web/app.js).
app.setErrorHandler((err: FastifyError, _req, reply) => {
if (typeof err.code === 'string' && err.code.startsWith('FST_ERR_CTP')) {
return reply.code(err.statusCode ?? 400).send({ error: 'invalid JSON body' })
}
return reply.code(err.statusCode ?? 500).send({ error: err.message })
})
app.setNotFoundHandler((req, reply) => {
const route = new URL(req.url, 'http://x').pathname
if (KNOWN_ROUTES.includes(route)) return reply.code(405).send({ error: 'method not allowed' })
return reply.code(404).send({ error: 'not found' })
})
app.get('/health', async () => {
// Path-source write flags (specs/source-write-flags.md): git says whether a path PUT
// commits, writable whether the folder accepts writes, so a client can disable its
// save before the first refused write. Computed per request, never stored; null for a
// repo source (a repo PUT always commits on a fresh clone). writable can over-report
// (read-only bind mount, root) — see isWritableDir in web/dashboard.mjs.
const src = dashState.source
const writeFlags = src && src.kind === 'path'
? { git: isGitWorkTree(src.name), writable: isWritableDir(src.name) }
: { git: null, writable: null }
return {
ok: true,
running,
// Ottr's provisioning gate reads this flag: it skips its idle wait only when it
// matches the layer mode the spawned install-user.mjs inherits (ALATE_LAYER=1).
layers: process.env.ALATE_LAYER === '1',
apiKeySet: !!config.apiKey,
repo: config.repo,
path: config.path,
...writeFlags,
tokenSet: !!config.token,
pending: !!(dashState.source?.importedSha && dashState.source.importedSha !== config.update.provisionedSha),
update: {
enabled: !!config.repo,
lastChecked: config.update.lastChecked,
behind: !!config.update.provisionedSha && config.update.remoteSha !== config.update.provisionedSha,
},
}
})
app.get('/config', async () => ({ repo: config.repo, path: config.path, projectsRoot: config.projectsRoot, tokenSet: !!config.token }))
interface ConfigBody { repo?: unknown; path?: unknown; token?: unknown; projectsRoot?: unknown }
app.post<{ Body: ConfigBody | undefined }>('/config', {
preHandler: keyGuard,
}, async (req, reply) => {
const body = req.body ?? {}
if (running) return reply.code(409).send({ error: 'provision already running' })
const { repo, path, token, projectsRoot } = body
if (repo != null && path != null) return reply.code(400).send({ error: 'exactly one of repo or path required' })
if (repo == null && path == null && projectsRoot === undefined) return reply.code(400).send({ error: 'exactly one of repo or path required' })
if (repo != null && (typeof repo !== 'string' || !repoValid(repo))) return reply.code(400).send({ error: 'invalid repo' })
if (path != null && (typeof path !== 'string' || !isDir(path))) return reply.code(400).send({ error: 'invalid path' })
if (token !== undefined && typeof token !== 'string') return reply.code(400).send({ error: 'invalid token' })
// undefined leaves the stored root alone, null clears it, a string must be an existing
// directory; a lone projectsRoot changes only the root and keeps the source.
if (projectsRoot !== undefined && projectsRoot !== null && (typeof projectsRoot !== 'string' || !isDir(projectsRoot))) return reply.code(400).send({ error: 'invalid projectsRoot' })
const nextToken = token === undefined ? config.token : token || null
const nextProjectsRoot = projectsRoot === undefined ? config.projectsRoot : (projectsRoot as string | null)
// selectSource queues the first update check for a fresh snapshot, and that check
// reads the token from config: set the new token first, so the check authenticates
// with it. selectSource persists config on every success path; a failed source
// switch restores the previous token and projectsRoot and persists that.
const prevToken = config.token
const prevProjectsRoot = config.projectsRoot
config.token = nextToken
config.projectsRoot = nextProjectsRoot
let queuedCheck = false
try {
if (repo != null || path != null) {
queuedCheck = await selectSource((repo ?? path) as string, repo != null ? 'repo' : 'path', nextToken ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN)
} else {
saveConfig(config)
}
} catch (err) {
config.token = prevToken
config.projectsRoot = prevProjectsRoot
saveConfig(config)
return clientError(reply, err)
}
if (!queuedCheck) void updateCheckAfterChange()
return { repo: config.repo, path: config.path, tokenSet: !!config.token }
})
app.post('/provision', {
preHandler: keyGuard,
}, async (_req, reply) => {
if (running) return reply.code(409).send({ error: 'provision already running' })
if (!config.repo && !config.path) return reply.code(400).send({ error: 'no data source configured' })
running = true
try {
// Test-only file gate: the client controls overlap, not a timer.
while (process.env.ALATE_TEST_PROVISION_GATE && existsSync(process.env.ALATE_TEST_PROVISION_GATE)) {
await delay(10)
}
const { results, copiedSha } = await provision()
const ok = results.every(r => r.code === 0)
if (ok && config.repo) {
// The sha the snapshot copied, not the source's current head: a queued op that ran
// during the provision must not mark the newer commit as provisioned.
config.update.provisionedSha = copiedSha ?? ''
saveConfig(config)
}
// An applied update leaves the list at once, not at the next timer tick.
if (ok) void updateCheckAfterChange()
return { ok, results }
} finally {
running = false
}
})
// Dashboard (folded from the former standalone dashboard server): static UI, inventory state, import API.
let dashState = loadState(db)
// Dev-only allowance so a live-reload dev server can load. Guarded by ALATE_LIVE;
// production builds never set it, so the served CSP stays unchanged.
const liveDev = process.env.ALATE_LIVE ? " http://localhost:8400" : ""
// The live picker previews variants with inline <style> blocks and style attributes.
const liveStyle = process.env.ALATE_LIVE ? " 'unsafe-inline'" : ""
const DASH_HEADERS = {
// frame-ancestors 'none' (plus X-Frame-Options for older engines) blocks clickjacking:
// on a loopback bind the dashboard is key-free, so one click in a framed page can
// import a source or store a key (validated in the ALAT-49 browser run).
'Content-Security-Policy': `default-src 'none'; img-src 'self'; style-src 'self'${liveStyle}; script-src 'self'${liveDev}; font-src 'self'; connect-src 'self'${liveDev}; manifest-src 'self'; frame-ancestors 'none'`,
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-store',
'X-Frame-Options': 'DENY',
}
app.addHook('onSend', async (_req, reply, payload) => {
for (const [name, value] of Object.entries(DASH_HEADERS)) reply.header(name, value)
return payload
})
// Repo assets, read once at startup; null when the file is missing (route answers 404).
const DASH_STATIC: Record<string, { data: Buffer | null; type: string }> = {}
for (const [route, file, type] of [
['/', join(repoRoot, 'web', 'index.html'), 'text/html; charset=utf-8'],
['/style.css', join(repoRoot, 'web', 'style.css'), 'text/css; charset=utf-8'],
['/app.js', join(repoRoot, 'web', 'app.js'), 'text/javascript; charset=utf-8'],
['/theme.js', join(repoRoot, 'web', 'theme.js'), 'text/javascript; charset=utf-8'],
['/diff.mjs', join(repoRoot, 'web', 'diff.mjs'), 'text/javascript; charset=utf-8'],
['/logo.png', join(repoRoot, 'logo.png'), 'image/png'],
['/manifest.webmanifest', join(repoRoot, 'web', 'manifest.webmanifest'), 'application/manifest+json'],
['/sw.js', join(repoRoot, 'web', 'sw.js'), 'text/javascript; charset=utf-8'],
['/icons/icon-192.png', join(repoRoot, 'web', 'icons', 'icon-192.png'), 'image/png'],
['/icons/icon-512.png', join(repoRoot, 'web', 'icons', 'icon-512.png'), 'image/png'],
['/icons/maskable-512.png', join(repoRoot, 'web', 'icons', 'maskable-512.png'), 'image/png'],
['/fonts/source-serif-4.woff2', join(repoRoot, 'node_modules', '@fontsource-variable', 'source-serif-4', 'files', 'source-serif-4-latin-opsz-normal.woff2'), 'font/woff2'],
['/fonts/jetbrains-mono.woff2', join(repoRoot, 'node_modules', '@fontsource-variable', 'jetbrains-mono', 'files', 'jetbrains-mono-latin-wght-normal.woff2'), 'font/woff2'],
] as const) {
let data: Buffer | null = null
try { data = readFileSync(file) } catch {}
DASH_STATIC[route] = { data, type }
}
function sendStatic(route: string, reply: FastifyReply): FastifyReply {
const entry = DASH_STATIC[route]
if (!entry || !entry.data) return reply.code(404).send({ error: 'not found' })
return reply.code(200).type(entry.type).send(entry.data)
}
app.get('/', async (_req, reply) => sendStatic('/', reply))
app.get('/style.css', async (_req, reply) => sendStatic('/style.css', reply))
app.get('/app.js', async (_req, reply) => sendStatic('/app.js', reply))
app.get('/theme.js', async (_req, reply) => sendStatic('/theme.js', reply))
app.get('/diff.mjs', async (_req, reply) => sendStatic('/diff.mjs', reply))
app.get('/logo.png', async (_req, reply) => sendStatic('/logo.png', reply))
app.get('/manifest.webmanifest', async (_req, reply) => sendStatic('/manifest.webmanifest', reply))
app.get('/sw.js', async (_req, reply) => sendStatic('/sw.js', reply))
app.get('/icons/icon-192.png', async (_req, reply) => sendStatic('/icons/icon-192.png', reply))
app.get('/icons/icon-512.png', async (_req, reply) => sendStatic('/icons/icon-512.png', reply))
app.get('/icons/maskable-512.png', async (_req, reply) => sendStatic('/icons/maskable-512.png', reply))
app.get('/fonts/source-serif-4.woff2', async (_req, reply) => sendStatic('/fonts/source-serif-4.woff2', reply))
app.get('/fonts/jetbrains-mono.woff2', async (_req, reply) => sendStatic('/fonts/jetbrains-mono.woff2', reply))
function persistDash(): void {
db.prepare('UPDATE state SET value = ? WHERE id = 1').run(JSON.stringify(dashState))
}
// Dashboard git calls trust the stored key first, then the process environment.
const dashToken = (): string | undefined => config.token ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN
// A repo import named a host other than github.com: the stored token is presumed to
// belong to that host, so no route sends it to github.com — the update checker, the
// git children of later imports and ticks, and the editor push all ride without it.
// Recorded
// before the clone runs, so a failed import (a private repo clone throws before any
// source host is stored) is remembered too, and it stays sticky across later github.com
// imports and restarts. The fail-closed cost is only the unauthenticated GitHub rate
// limit; set ALATE_GITHUB_HOST to the foreign host to use the token there instead.
function noteTokenHost(spec: string, kind?: string): void {
if (kind === 'path') return
const parsed = parseDataSpec(spec)
if (parsed?.host && parsed.host !== DEFAULT_GITHUB_HOST && config.tokenHost !== parsed.host) {
config.tokenHost = parsed.host
saveConfig(config)
}
}
// One snapshot write at a time: imports and file edits share this chain, and a caller
// that queues during one of them must run against the state that op stored.
let importChain: Promise<unknown> = Promise.resolve()
// True from before an import dispatch until it settles. Update checks read this flag:
// a check started during an import writes SQLite rows and would block the event loop
// on the worker's write transaction (OTTR-807).
let importing = false
let checkDeferred = false
// True from before an edit dispatch until it settles; update checks treat it like importing because the edit holds the SQLite write lock in the worker.
let editing = false
// True while the provision snapshot copy runs in the worker; update checks treat it
// like importing because the snapshot's lock window collides with their writes.
let snapshotting = false
// Imports queued or running. The deferred check waits for zero: a check that starts
// between two queued imports still writes rows inside the next import's transaction.
let opsQueued = 0
// Run the one deferred update check, but only while no worker op is running or queued:
// a check that starts mid-import writes rows and would stall the loop on the busy wait.
function runDeferredCheck(): void {
if (!checkDeferred) return
if (importing || editing || snapshotting || opsQueued > 0) return
checkDeferred = false
void updateCheckAfterChange()
}
async function selectSource(spec: string, kind?: string, token = dashToken()): Promise<boolean> {
noteTokenHost(spec, kind)
opsQueued++
const run = importChain.then(async () => {
importing = true
try {
const next = await runImport({ dbFile, state: dashState, spec, kind, token, tokenHost: config.tokenHost, trustedDir: getTrustedPathSource() })
const changed = dashState.source?.spec !== next.source.spec || dashState.source?.kind !== next.source.kind
const newCommit = next.source.kind === 'repo' && !!next.source.importedSha && next.source.importedSha !== dashState.source?.importedSha
dashState = next
const isRepo = next.source.kind === 'repo'
config.repo = isRepo ? next.source.spec : null
config.path = isRepo ? null : next.source.name
config.update = {
lastChecked: isRepo ? next.source.importedAt : null,
remoteSha: next.source.importedSha ?? '',
provisionedSha: changed ? '' : config.update.provisionedSha,
}
dashState.update = isRepo ? { checkedAt: next.source.importedAt, remoteSha: next.source.importedSha, available: false, ahead: null } : null
persistDash()
saveConfig(config)
// A fresh snapshot invalidates the stored update rows at once, not at the next timer tick.
// The return value tells route callers whether the check is already queued, so one
// snapshot change queues exactly one trigger.
if (newCommit) void updateCheckAfterChange()
return newCommit
} finally {
importing = false
opsQueued--
runDeferredCheck()
}
})
importChain = run.then(() => undefined, () => undefined)
return run
}
// Periodic remote check for a repo source: refresh update state, optionally auto re-import.
async function dashCheck(): Promise<void> {
if (running || importing || editing || snapshotting || dashState.source?.kind !== 'repo') return
const src = dashState.source
const sha = await remoteHead(src.name, src.ref, dashToken(), src.host ?? '', config.tokenHost)
const behind = sha !== '' && sha !== src.importedSha
? await remoteAhead(src.name, src.importedSha, sha, dashToken(), src.host, config.tokenHost)
: null
// The ahead lookup above awaited the network: an import, an edit, a queued op or a
// provision that ran in between has its own writes, and this one would pair a stale
// remoteSha with the fresh state (a phantom 'N behind' until the next tick); with
// autoUpdate it would also import mid-provision. Drop the check.
if (running || dashState.source !== src || importing || editing || snapshotting || opsQueued > 0) return
dashState.update = { checkedAt: new Date().toISOString(), remoteSha: sha, available: sha !== '' && sha !== src.importedSha, ahead: behind }
if (sha) config.update.remoteSha = sha
config.update.lastChecked = dashState.update.checkedAt
saveConfig(config)
persistDash()
if (config.autoUpdate && dashState.update.available) {
try {
await selectSource(src.spec, 'repo')
} catch (err) {
console.error(`snapshot refresh failed: ${redactSecrets((err as Error).message, dashToken())}`)
}
persistDash()
}
}
let updateRunning = false
let updatePromise: Promise<void> = Promise.resolve()
let rerunNeeded = false
// Single-flight: one checkUpdates at a time. A plain caller that arrives during a
// run joins it; a snapshot-change caller marks the run stale (it read an older
// snapshot), and exactly one more check follows when it ends, so a snapshot change
// never waits for the next timer tick. The promise never rejects, so the
// fire-and-forget callers stay safe.
function updateCheck(): Promise<void> {
// A worker op holds the SQLite lock: defer exactly one check to the end of the op
// instead of blocking the event loop on the busy timeout.
if (importing || editing || snapshotting) {
checkDeferred = true
return updatePromise
}
if (updateRunning) return updatePromise
updateRunning = true
updatePromise = (async () => {
// One counter for the whole run. A per-attempt counter would reset on every
// retry and loop for as long as a lock is held, blocking the loop every 50 ms.
let lockRetries = 0
for (;;) {
rerunNeeded = false
try {
await checkUpdates(db, { token: dashToken(), securityFastPath: config.securityFastPath, dataRepo: dashState.source ? (dashState.source.kind === 'repo' ? dashState.source.name : dashState.source.spec) : null, dataHost: config.tokenHost ?? (dashState.source && dashState.source.kind === 'repo' ? (dashState.source.host ?? '') : undefined) })
} catch (err) {
const msg = redactSecrets((err as Error).message, dashToken())
// A lock hit between worker ops is transient: retry a bounded number of times,
// then log the failure and leave the rows to the next timer tick.
if (/locked|busy/i.test(msg) && lockRetries < 3) {
lockRetries++
await delay(50)
continue
}
console.error(`update check failed: ${msg}`)
}
if (!rerunNeeded) break
}
updateRunning = false
})()
return updatePromise
}
// For the sites that just changed the snapshot (imports, edits, provisions): a
// check that is already running read the older snapshot, so queue one more.
function updateCheckAfterChange(): Promise<void> {
if (updateRunning) rerunNeeded = true
return updateCheck()
}
app.get('/api/state', { preHandler: dashGuard }, async () => ({ ...dashState, updates: loadUpdates(db) }))
// The provider payload keeps only records the board accepts (isValidUpdateRecord mirrors
// the board's record() checks), so a pull never logs dropped records; /api/state keeps all.
const boardUpdates = () => {
const u = loadUpdates(db)
return { checkedAt: u.checkedAt, updates: u.updates.filter(isValidUpdateRecord) }
}
app.get('/api/updates', {
preHandler: keyGuard,
}, async () => boardUpdates())
// Run a check now for callers such as the board's refresh button, then serve the fresh list.
app.post('/api/updates/check', {
preHandler: keyGuard,
}, async () => {
await updateCheck()
return boardUpdates()
})
// Dashboard login: exchange the provisioning key for a session cookie, because phone
// browsers cannot set an Authorization header. The key never returns in a response
// body and never rides the cookie: the cookie holds a random session id. No Secure flag
// (so no __Host- prefix): a non-loopback bind serves plain HTTP. Path=/api keeps the
// cookie off every other path; SameSite=Strict plus the Origin check in cookieAuthed cover CSRF.
app.post<{ Body: { key?: unknown } | undefined }>('/api/login', { bodyLimit: 64 * 1024 }, async (req, reply) => {
const key = (req.body ?? {}).key
if (typeof key !== 'string' || !keyMatch(key, config.apiKey ?? '')) return reply.code(401).send({ error: 'unauthorized' })
reply.header('set-cookie', `alate_session=${newSession()}; HttpOnly; SameSite=Strict; Path=/api; Max-Age=${SESSION_MAX_AGE_S}`)
return { ok: true }
})
// Issue a fresh API key for callers such as Ottr. Returned once, like the boot-time
// generation; the previous key and every dashboard session stop working immediately.
// No read endpoint: GET would hand the provision credential to every local process for
// as long as the server runs. A session alone cannot rotate: a cookie replayed from a
// sibling port must not mint a key, so the caller proves the current key (Bearer or
// body). 403, not 401: a wrong re-entered key must not send the dashboard to its login view.
app.post<{ Body: { key?: unknown } | undefined }>('/api/key', { bodyLimit: 64 * 1024, preHandler: dashGuard }, async (req, reply) => {
const current = (req.body ?? {}).key
if (!authorized(req) && (typeof current !== 'string' || !keyMatch(current, config.apiKey ?? ''))) {
return reply.code(403).send({ error: 'current key required' })
}
config.apiKey = randomBytes(32).toString('base64url')
saveConfig(config)
sessions.clear()
return { key: config.apiKey }
})
interface ImportBody { source?: unknown; kind?: unknown }
app.post<{ Body: ImportBody | undefined }>('/api/import', { bodyLimit: 64 * 1024, preHandler: dashGuard }, async (req, reply) => {
const body = req.body ?? ({} as ImportBody)
if (running) return reply.code(409).send({ error: 'provision already running' })
if (typeof body.source !== 'string' || body.source === '') return reply.code(400).send({ error: 'source required' })
if (body.kind !== undefined && body.kind !== 'path' && body.kind !== 'repo') return reply.code(400).send({ error: 'kind must be "path" or "repo"' })
let queuedCheck = false
try {
queuedCheck = await selectSource(body.source, body.kind as string | undefined)
} catch (err) {
return clientError(reply, err)
}
if (!queuedCheck) void updateCheckAfterChange()
return { ok: true, state: dashState }
})
// File editor: snapshot reads, plus writes that commit and push. Guarded like /api/import.
app.get('/api/files', { preHandler: dashGuard }, async () => ({ files: listStoredFiles(db) }))
interface FileQuery { path?: unknown }
app.get('/api/file', { preHandler: dashGuard }, async (req, reply) => {
const query = (req.query ?? {}) as FileQuery
const rel = typeof query.path === 'string' ? query.path : ''
try {
const file = readStoredFile(db, rel)
if (!file) return reply.code(404).send({ error: `no stored file at ${rel.slice(0, 200)}` })
return file
} catch (err) {
return clientError(reply, err)
}
})
interface FileEditBody { path?: unknown; content?: unknown; base?: unknown; message?: unknown }
// Shared write path for the file editor and the bundle actions: one dashboard write at a
// time, queued on importChain like the worker does, with the same snapshotChanged
// re-check and deferred update check around every op. work runs on the chain and returns
// the response payload; a failed op rethrows through clientError.
async function queuedDashboardWrite(reply: FastifyReply, work: () => Promise<{ [key: string]: unknown }>): Promise<{ [key: string]: unknown } | FastifyReply> {
if (running || writing) return reply.code(409).send({ error: running ? 'provision already running' : 'another file write is running' })
writing = true
// Queue on importChain like the worker does: an edit that waits for an in-flight
// import must run against the state that import stored, never the one it replaced.
// Reading dashState at dispatch time would commit the edit to the replaced source.
const run = importChain.then(async () => {
editing = true
try {
return await work()
} catch (err) {
// editPathSource re-imports the user's tree before it throws, so a failed
// commit or push still changed the stored snapshot.
if (err && typeof err === 'object' && 'snapshotChanged' in err && err.snapshotChanged === true) void updateCheckAfterChange()
throw err
} finally {
editing = false
// A check that arrived during the edit was deferred: run exactly one now.
if (checkDeferred) {
checkDeferred = false
void updateCheckAfterChange()
}
}
})
importChain = run.then(() => undefined, () => undefined)
try {
return await run
} catch (err) {
return clientError(reply, err)
} finally { writing = false }
}
// The write landed: point the repo source's update block at the new commit (the same
// refresh selectSource does after an import), persist, and queue the snapshot-change
// update check. Returns the editor's response payload shape.
function writeResult(res: { state: StateDef; commit: string; pushed: boolean; warning?: string }): { [key: string]: unknown } {
dashState = res.state
dashState.update = dashState.source.kind === 'repo'
? { checkedAt: new Date().toISOString(), remoteSha: dashState.source.importedSha, available: false, ahead: null }
: null
persistDash()
// Every committed edit changed the stored snapshot, path edits included; the
// stored update rows follow at once, never at the next timer tick.
void updateCheckAfterChange()
return {
ok: true,
commit: res.commit,
pushed: res.pushed,
...(res.warning ? { warning: res.warning } : {}),
state: { ...dashState, updates: loadUpdates(db) },
}
}
async function fileEdit(req: FastifyRequest, reply: FastifyReply, del: boolean) {
const body = (req.body ?? {}) as FileEditBody
return queuedDashboardWrite(reply, async () => {
const res = await runEdit({ dbFile, state: dashState, edit: { ...body, delete: del }, token: dashToken(), tokenHost: config.tokenHost, trustedDir: getTrustedPathSource() })
return writeResult(res)
})
}
app.put('/api/file', { bodyLimit: 2 * 1024 * 1024, preHandler: dashGuard }, async (req, reply) => fileEdit(req, reply, false))
app.delete('/api/file', { bodyLimit: 2 * 1024 * 1024, preHandler: dashGuard }, async (req, reply) => fileEdit(req, reply, true))
// Bundle board actions (specs/bundles.md "Editing (ALAT-180)"): every action validates
// against the stored snapshot and writes through the editor's save path (one commit,
// one push), so the response carries the editor's result shape. The known skill and
// plugin universe comes from the inventory scan, the same names the install derives.
type BundleActionBody = { action?: unknown; name?: unknown; bundle?: unknown; kind?: unknown; from?: unknown; to?: unknown; project?: unknown }