ccdeck 3.82.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/login-item.js +5 -0
  5. package/bin/cli/tui.js +58 -4
  6. package/bin/deck.js +27 -1
  7. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  8. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  9. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  10. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  11. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  12. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  13. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  14. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  15. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  16. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  17. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  18. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  19. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  20. package/dist/web/assets/app-40gNTTfq.js +361 -0
  21. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  22. package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
  23. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  24. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  25. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  26. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  27. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  28. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  29. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  30. package/dist/web/index.html +16 -6
  31. package/package.json +13 -1
  32. package/release-notes.json +79 -0
  33. package/src/server/account-client.mjs +196 -0
  34. package/src/server/account-connect.mjs +238 -0
  35. package/src/server/account-flag.mjs +106 -0
  36. package/src/server/account-projects.mjs +1 -1
  37. package/src/server/account-service.mjs +532 -0
  38. package/src/server/account-status.mjs +293 -0
  39. package/src/server/account-store.mjs +137 -0
  40. package/src/server/account-sync.mjs +473 -0
  41. package/src/server/account-token-store.mjs +216 -0
  42. package/src/server/account-ui-fields.mjs +126 -0
  43. package/src/server/account-watch.mjs +1 -1
  44. package/src/server/browser-watch-log.mjs +1 -1
  45. package/src/server/browser-watch-store.mjs +1 -1
  46. package/src/server/ccdeck-account-routes.mjs +252 -0
  47. package/src/server/ccusage-install.mjs +2 -2
  48. package/src/server/ccusage-registry.mjs +4 -4
  49. package/src/server/ccusage-session.mjs +11 -0
  50. package/src/server/claude-accounts.mjs +1 -1
  51. package/src/server/claude-recovery.mjs +9 -4
  52. package/src/server/claude-settings-catalog.mjs +6 -6
  53. package/src/server/claude-settings.mjs +1 -1
  54. package/src/server/codex-auto.mjs +1 -1
  55. package/src/server/codex-cost-usage.mjs +7 -2
  56. package/src/server/codex-live-checkpoint.mjs +24 -9
  57. package/src/server/codex-live-engine.mjs +14 -4
  58. package/src/server/codex-live-handoff.mjs +53 -9
  59. package/src/server/codex-names.mjs +49 -0
  60. package/src/server/codex-translate.mjs +1 -1
  61. package/src/server/codex-ultrafast.d.mts +3 -0
  62. package/src/server/codex-ultrafast.mjs +5 -0
  63. package/src/server/codex-watch.mjs +25 -0
  64. package/src/server/command-panel-engine.mjs +300 -0
  65. package/src/server/command-panel-platform.mjs +99 -0
  66. package/src/server/cswap-auto-choice.mjs +1 -1
  67. package/src/server/cswap-auto-loop.mjs +1 -1
  68. package/src/server/cswap-install.mjs +21 -40
  69. package/src/server/deck-home.mjs +6 -0
  70. package/src/server/deck-prefs.mjs +53 -1
  71. package/src/server/detach.mjs +1 -1
  72. package/src/server/engine-download.mjs +277 -0
  73. package/src/server/engine-install.mjs +378 -0
  74. package/src/server/engine-package.mjs +267 -0
  75. package/src/server/event-log.mjs +7 -1
  76. package/src/server/event-pipeline.mjs +29 -1
  77. package/src/server/ghostty-handoff.mjs +81 -0
  78. package/src/server/index.mjs +143 -5
  79. package/src/server/installer.mjs +4 -1
  80. package/src/server/integrations/jira-write-guard.mjs +14 -208
  81. package/src/server/integrations/store.mjs +37 -19
  82. package/src/server/integrations/write-guard.mjs +223 -0
  83. package/src/server/intel-cpu-temperature.mjs +26 -0
  84. package/src/server/lifecycle.mjs +69 -6
  85. package/src/server/log-replay.mjs +4 -0
  86. package/src/server/login-service.mjs +116 -14
  87. package/src/server/macmon.mjs +1 -1
  88. package/src/server/npm-latest.mjs +1 -1
  89. package/src/server/org-telemetry.mjs +1 -1
  90. package/src/server/output-watch.mjs +4 -1
  91. package/src/server/panel-provenance.mjs +390 -0
  92. package/src/server/pinned-build.mjs +14 -0
  93. package/src/server/prefs-refusal.mjs +8 -1
  94. package/src/server/prefs-routes.mjs +60 -11
  95. package/src/server/pro-engine-client.mjs +339 -0
  96. package/src/server/pro-engine-install.mjs +294 -0
  97. package/src/server/pro-engine-terminal.mjs +308 -0
  98. package/src/server/project-discovery.mjs +139 -0
  99. package/src/server/provider-session-name.mjs +58 -0
  100. package/src/server/quota-closes.mjs +1 -1
  101. package/src/server/quota-history.mjs +1 -1
  102. package/src/server/reports.mjs +86 -21
  103. package/src/server/request-gates.mjs +34 -5
  104. package/src/server/restart-note.mjs +1 -1
  105. package/src/server/seed-boundary.mjs +489 -0
  106. package/src/server/session-counts.mjs +244 -0
  107. package/src/server/session-deck-names.mjs +143 -0
  108. package/src/server/session-enrichment.mjs +43 -6
  109. package/src/server/session-name-route.mjs +73 -0
  110. package/src/server/session-summary.mjs +12 -1
  111. package/src/server/session-transcript-routes.mjs +167 -0
  112. package/src/server/swap-log.mjs +1 -1
  113. package/src/server/system-metrics.mjs +57 -0
  114. package/src/server/terminal-bridge.mjs +485 -0
  115. package/src/server/terminal-folder.mjs +61 -0
  116. package/src/server/terminal-js-routes.mjs +752 -0
  117. package/src/server/terminal-routes.mjs +553 -0
  118. package/src/server/terminal-sessions.mjs +759 -0
  119. package/src/server/terminal-socket.mjs +403 -0
  120. package/src/server/terminal-target.mjs +928 -0
  121. package/src/server/thermal-metrics.mjs +13 -9
  122. package/src/server/tmux-control.mjs +1319 -0
  123. package/src/server/tmux-download.mjs +220 -0
  124. package/src/server/tmux.mjs +542 -0
  125. package/src/server/token-redact.mjs +42 -3
  126. package/src/server/tool-audit-report.mjs +44 -6
  127. package/src/server/tool-audit-routes.mjs +12 -1
  128. package/src/server/tool-audit.mjs +42 -8
  129. package/src/server/traffic-radar-monitor.mjs +1 -1
  130. package/src/server/traffic-radar-permission.mjs +1 -1
  131. package/src/server/transcript-gate.mjs +1 -1
  132. package/src/server/transcript-scan.mjs +15 -7
  133. package/src/server/transcript-turns.mjs +154 -0
  134. package/src/server/tui-network.mjs +1 -0
  135. package/src/server/tui-view.mjs +28 -0
  136. package/src/server/utf8-carry.mjs +159 -0
  137. package/src/server/uv-bootstrap.mjs +2 -2
  138. package/src/server/windows-acl.mjs +158 -0
  139. package/src/server/ws-frames.mjs +690 -0
  140. package/dist/web/assets/BrowserWatchModal-BmRTh_xT.js +0 -1
  141. package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
  142. package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
  143. package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
  144. package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
  146. package/dist/web/assets/app-DZdZoqJ6.js +0 -358
@@ -0,0 +1,293 @@
1
+ // The status frame: what this deck tells its account about the machine it runs
2
+ // on, every fifteen seconds, while it is connected (design 3.4).
3
+ //
4
+ // THE FRAME IS AN ALLOWLIST BY CONSTRUCTION. buildFrame copies named fields
5
+ // out of named readings and nothing else, so a field added to a reading
6
+ // upstream cannot ride along by accident; account-status.test.ts holds the
7
+ // serialized key set to the contract fixture's. What is in it: the deck's
8
+ // version, OS, architecture and channel; CPU busy share and core count; memory
9
+ // used share and total; how many sessions are running and how many are waiting
10
+ // on their human; which settings revision this machine has applied. What is
11
+ // NOT, and never will be without a new schema: load average (the owner's
12
+ // decision), thermals, the hostname, paths, accounts, quota, session names.
13
+ //
14
+ // A METRIC THAT CANNOT BE TOLD IS UNKNOWN, NEVER ZERO. Before the CPU has two
15
+ // samples it is `{ unknown: "warming-up" }`; the counts are `starting` until the
16
+ // ring has been read and `no-capture` with nothing feeding the deck. The same
17
+ // refusal system-metrics.mjs makes for the Machine panel.
18
+ //
19
+ // THE SCHEDULE: the first frame about three seconds after start (the CPU needs
20
+ // two samples), then whatever the last answer's `nextInSec` said — 15 by
21
+ // default — with two seconds of jitter either way, so a fleet started together
22
+ // does not beat together. A network failure or a 5xx backs off 15, 30, 60, 120,
23
+ // then 300 seconds, ±20%; a Retry-After is honoured; a success resets it all.
24
+ //
25
+ // WHAT AN ANSWER CAN SAY BACK (the control channel):
26
+ // 200 next interval, the bound profile's settings revision (a newer one is
27
+ // pulled), `rotateToken` — rotated, and the new token persisted,
28
+ // BEFORE it is used — and `feedback`, the account's unread
29
+ // conversations, which light the Feedback button's dot, and whether
30
+ // replies are also mailed
31
+ // 400 this frame is wrong: dropped, said once, the schedule carries on
32
+ // 401 device_revoked / invalid_token / account_gone: final. Stop, and let
33
+ // the service forget the token
34
+ // 409 stale_sequence / stale_boot: dropped; twice in a row, a new boot id
35
+ // 413 dropped, said once
36
+ // 429 wait as asked
37
+ //
38
+ // A CLEAN STOP SAYS SO. `sendStopping` is the last frame, `state: "stopping"`,
39
+ // with a 1.5 second ceiling, so the console can say "ccdeck stopped" at once
40
+ // instead of waiting 90 seconds for the frames to go stale.
41
+ import { randomUUID } from "node:crypto";
42
+ import { PRODUCT } from "./brand.mjs";
43
+
44
+ export const FIRST_FRAME_MS = 3_000;
45
+ export const DEFAULT_EVERY_SEC = 15;
46
+ export const JITTER_MS = 2_000;
47
+ export const BACKOFF_SEC = Object.freeze([15, 30, 60, 120, 300]);
48
+ export const BACKOFF_SPREAD = 0.2;
49
+ export const STOPPING_TIMEOUT_MS = 1_500;
50
+ /** Errors on which a 401 is final, not a proxy being awkward. */
51
+ export const FINAL_401 = new Set(["device_revoked", "invalid_token", "account_gone"]);
52
+
53
+ const iso = ms => new Date(ms).toISOString();
54
+
55
+ /** The most unread conversations a summary may say: anything past it is not
56
+ * a count anybody wrote. */
57
+ export const FEEDBACK_UNREAD_MAX = 10_000;
58
+ const ZONED = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,7})?)?(Z|z|[+-]\d{2}:\d{2})$/;
59
+
60
+ /**
61
+ * The account's feedback summary as a frame answer (or a read) carries it —
62
+ * `{ unread, latestAt, mail }` — or null for anything that is not one. Only the
63
+ * three fields, so nothing else an answer holds can ride into the page's view.
64
+ * `mail` says whether the team's replies are also mailed: false while the API
65
+ * sends no mail, when the dialog must not promise any. An API from before the
66
+ * field mailed every reply, so its absence is true.
67
+ */
68
+ export function feedbackSummary(raw) {
69
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
70
+ const { unread, latestAt, mail = true } = raw;
71
+ if (!Number.isInteger(unread) || unread < 0 || unread > FEEDBACK_UNREAD_MAX) return null;
72
+ if (latestAt !== null && !(typeof latestAt === "string" && ZONED.test(latestAt) && Number.isFinite(Date.parse(latestAt)))) return null;
73
+ if (typeof mail !== "boolean") return null;
74
+ return { unread, latestAt, mail };
75
+ }
76
+
77
+ /** A metric reading as the frame carries it: the named fields, or the reason
78
+ * it cannot be told. `fields` maps frame keys to reading keys. */
79
+ function metric(reading, fields) {
80
+ if (!reading || typeof reading !== "object") return { unknown: "unavailable" };
81
+ if (typeof reading.unknown === "string") return { unknown: reading.unknown };
82
+ const out = {};
83
+ for (const [to, from] of fields) out[to] = reading[from];
84
+ out.sampledAt = iso(reading.sampledAt);
85
+ return out;
86
+ }
87
+
88
+ /**
89
+ * One frame, built from named fields only. `cpu`, `memory` and `agents` are
90
+ * the readings machineReading and the session counts answer; `settings` is the
91
+ * binding the sync reports, or null before there is one.
92
+ */
93
+ export function buildFrame({ bootId, seq, observedAt, state, deck, cpu, memory, agents, settings }) {
94
+ const frame = {
95
+ v: 1,
96
+ bootId,
97
+ seq,
98
+ observedAt: iso(observedAt),
99
+ state: state === "stopping" ? "stopping" : "running",
100
+ deck: { version: deck.version, os: deck.os, arch: deck.arch, channel: deck.channel },
101
+ cpu: metric(cpu, [["pct", "pct"], ["cores", "cores"]]),
102
+ memory: metric(memory, [["usedPct", "usedPct"], ["totalMb", "totalMb"]]),
103
+ agents: metric(agents, [["running", "running"], ["waiting", "waiting"]]),
104
+ };
105
+ // The binding as soon as there is one; `appliedRevision` is null until a tab
106
+ // has applied something, which the API takes (status-frame.stopping.json).
107
+ if (settings && typeof settings.profileId === "string") {
108
+ frame.settings = {
109
+ profileId: settings.profileId,
110
+ appliedRevision: Number.isInteger(settings.appliedRevision) ? settings.appliedRevision : null,
111
+ };
112
+ }
113
+ return frame;
114
+ }
115
+
116
+ /**
117
+ * The publisher. Every dependency is passed in so the suite can drive it on a
118
+ * fake clock against the fake API:
119
+ *
120
+ * client account-client.mjs
121
+ * token() the device token in use now
122
+ * rotate() rotate the token: ask, persist, swap — the service's
123
+ * reading() machineReading() — { cpu, memory }
124
+ * counts(now) the session counts' reading
125
+ * binding() { profileId, appliedRevision } or null — the sync's
126
+ * onControl(s) a 200's `settings`, and the moment to retry what is pending
127
+ * onFeedback(f) a 200's `feedback` summary, or null when it has none —
128
+ * the service keeps a valid one and ignores the rest
129
+ * onRevoked(err) a final 401
130
+ * onChange() status() would answer something new
131
+ */
132
+ export function createStatusPublisher({
133
+ client,
134
+ token,
135
+ rotate = async () => {},
136
+ reading,
137
+ counts,
138
+ binding = () => null,
139
+ deck,
140
+ onControl = () => {},
141
+ onFeedback = () => {},
142
+ onRevoked = () => {},
143
+ onChange = () => {},
144
+ now = Date.now,
145
+ random = Math.random,
146
+ newBootId = randomUUID,
147
+ setTimer = (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
148
+ clearTimer = t => clearTimeout(t),
149
+ log = msg => console.error(`${PRODUCT}: ${msg}`),
150
+ }) {
151
+ let bootId = newBootId();
152
+ let seq = 0;
153
+ let everySec = DEFAULT_EVERY_SEC;
154
+ let failures = 0;
155
+ let staleInARow = 0;
156
+ let timer = null;
157
+ let running = false;
158
+ let stopped = false;
159
+ let inFlight = null;
160
+ let lastSentAt = null;
161
+ let lastResult = null; // "ok" | "offline" | "rejected"
162
+ let nextAt = null;
163
+ const said = new Set();
164
+
165
+ const sayOnce = (kind, msg) => { if (!said.has(kind)) { said.add(kind); log(msg); } };
166
+
167
+ function schedule(ms) {
168
+ if (!running) return;
169
+ if (timer) clearTimer(timer);
170
+ nextAt = now() + ms;
171
+ timer = setTimer(() => { timer = null; void tick(); }, ms);
172
+ onChange();
173
+ }
174
+
175
+ const jittered = () => everySec * 1000 + (random() * 2 - 1) * JITTER_MS;
176
+ const backoff = () => {
177
+ const step = BACKOFF_SEC[Math.min(failures - 1, BACKOFF_SEC.length - 1)] * 1000;
178
+ return step * (1 + (random() * 2 - 1) * BACKOFF_SPREAD);
179
+ };
180
+
181
+ function frameNow(state) {
182
+ seq += 1;
183
+ const at = now();
184
+ const r = reading() ?? {};
185
+ return buildFrame({
186
+ bootId, seq, observedAt: at, state, deck,
187
+ cpu: r.cpu, memory: r.memory, agents: counts(at), settings: binding(),
188
+ });
189
+ }
190
+
191
+ async function send(frame, timeout) {
192
+ return client.post("/v1/device/status", frame, { token: token(), timeout });
193
+ }
194
+
195
+ async function tick() {
196
+ if (!running || stopped) return;
197
+ const res = await (inFlight = send(frameNow("running")));
198
+ inFlight = null;
199
+ if (!running || stopped) return;
200
+ lastSentAt = now();
201
+
202
+ if (res.ok) {
203
+ failures = 0;
204
+ staleInARow = 0;
205
+ lastResult = "ok";
206
+ const body = res.body ?? {};
207
+ if (Number.isInteger(body.nextInSec) && body.nextInSec >= 5 && body.nextInSec <= 300) everySec = body.nextInSec;
208
+ if (body.rotateToken === true) {
209
+ try { await rotate(); } catch { /* the old token stays good until the new one is used */ }
210
+ }
211
+ try { await onControl(body.settings ?? null); } catch { /* the sync says its own failures */ }
212
+ try { onFeedback(body.feedback ?? null); } catch { /* the dot is never worth a frame */ }
213
+ return schedule(jittered());
214
+ }
215
+ if (res.status === 401 && FINAL_401.has(res.error)) {
216
+ lastResult = "rejected";
217
+ stop();
218
+ return onRevoked(res.error);
219
+ }
220
+ if (res.status === 429 || (res.status === 503 && res.retryAfterMs)) {
221
+ lastResult = "offline";
222
+ failures = Math.max(failures, 1);
223
+ return schedule(res.retryAfterMs ?? backoff());
224
+ }
225
+ if (res.network || res.status >= 500 || res.status === 401 || res.status === 403 || res.status === 404) {
226
+ // 404 is the API with accounts switched off again, or a tunnel being
227
+ // moved; 401/403 without a final error, a proxy. None is final.
228
+ failures += 1;
229
+ lastResult = "offline";
230
+ return schedule(res.retryAfterMs ?? backoff());
231
+ }
232
+ if (res.status === 409) {
233
+ lastResult = "rejected";
234
+ staleInARow += 1;
235
+ if (staleInARow >= 2) {
236
+ // The API has a newer epoch for this boot than this process — a clock
237
+ // or a sequence that went backwards. A new boot id starts clean.
238
+ bootId = newBootId();
239
+ seq = 0;
240
+ staleInARow = 0;
241
+ }
242
+ return schedule(jittered());
243
+ }
244
+ // 400, 413 and anything else the API wrote about the frame itself.
245
+ lastResult = "rejected";
246
+ sayOnce(`status-${res.status}-${res.error ?? ""}`, `the account refused a status frame (${res.status}${res.error ? ` ${res.error}` : ""})`);
247
+ return schedule(jittered());
248
+ }
249
+
250
+ function start(delayMs = FIRST_FRAME_MS) {
251
+ if (running || stopped) return;
252
+ running = true;
253
+ schedule(delayMs);
254
+ }
255
+
256
+ function stop() {
257
+ running = false;
258
+ if (timer) clearTimer(timer);
259
+ timer = null;
260
+ nextAt = null;
261
+ onChange();
262
+ }
263
+
264
+ /** The last frame, for a clean shutdown. Best effort and bounded: resolves
265
+ * whatever happens, within STOPPING_TIMEOUT_MS of the request. */
266
+ async function sendStopping() {
267
+ if (stopped) return;
268
+ const wasRunning = running;
269
+ stopped = true;
270
+ stop();
271
+ if (!wasRunning || !token()) return;
272
+ try {
273
+ await send(frameNow("stopping"), STOPPING_TIMEOUT_MS);
274
+ } catch { /* leaving anyway */ }
275
+ }
276
+
277
+ return {
278
+ start,
279
+ stop,
280
+ sendStopping,
281
+ /** For the suite: send the next frame now. */
282
+ tickNow: () => tick(),
283
+ status: () => (lastSentAt == null && nextAt == null ? null : {
284
+ lastSentAt: lastSentAt == null ? null : iso(lastSentAt),
285
+ lastResult,
286
+ nextAt: nextAt == null ? null : iso(nextAt),
287
+ everySec,
288
+ }),
289
+ /** For the suite. */
290
+ bootId: () => bootId,
291
+ seq: () => seq,
292
+ };
293
+ }
@@ -0,0 +1,137 @@
1
+ // account.json: which ccdeck account this deck is connected to, as which
2
+ // device, and where its settings sync stands.
3
+ //
4
+ // THE DECK'S ALONE AND NEVER SERVED. Nothing here goes to a page whole: the
5
+ // routes answer a view built out of it (account-service.mjs accountView), with
6
+ // no token, no cipher and no device code in it. The token itself lives in the
7
+ // OS keychain where there is one (account-token-store.mjs); where there is
8
+ // not, it lives here, which is why this file is written the way prefs.json is —
9
+ // created 0600 on the create rather than chmod'ed after, staged through an
10
+ // O_EXCL temp file, fsynced, renamed into place with the Windows retry ladder,
11
+ // and the temp removed if anything fails. See deck-prefs.mjs `save` for the
12
+ // whole argument; this is the same discipline on a second secret.
13
+ //
14
+ // In the deck's own data folder (deck-home.mjs deckDataDir), so CCDECK_HOME
15
+ // moves it with everything else and two profiles of one machine are two
16
+ // devices.
17
+ import { chmod, mkdir, readFile, unlink } from "node:fs/promises";
18
+ import { join } from "node:path";
19
+ import { createTemp, renameWithRetry, stripBom } from "./atomic-write.mjs";
20
+ import { deckDataDir } from "./deck-home.mjs";
21
+ import { PRODUCT } from "./brand.mjs";
22
+
23
+ export const ACCOUNT_FILE = "account.json";
24
+ export const ACCOUNT_MODE = 0o600;
25
+ /** The shape version of account.json. */
26
+ export const ACCOUNT_V = 1;
27
+
28
+ export function accountPath(home = deckDataDir()) {
29
+ return join(home, ACCOUNT_FILE);
30
+ }
31
+
32
+ const text = (v, max = 256) => (typeof v === "string" && v.length <= max ? v : "");
33
+ const nullableText = (v, max = 256) => (typeof v === "string" && v.length && v.length <= max ? v : null);
34
+ const TOKEN_STORAGES = new Set(["keychain", "dpapi", "secret-service", "file"]);
35
+
36
+ /** The device token's shape. Anything else is not a token this deck made. */
37
+ export const DEVICE_TOKEN = /^ccdd_[A-Za-z0-9_-]{20,128}$/;
38
+
39
+ /**
40
+ * Whatever is on disk, coerced into the one shape the deck reads. A field that
41
+ * is not what it should be reads as absent — a hand-edited or half-written
42
+ * file must cost a reconnect, never a crash.
43
+ */
44
+ export function normaliseAccount(raw) {
45
+ const src = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
46
+ const tokenStorage = TOKEN_STORAGES.has(src.tokenStorage) ? src.tokenStorage : null;
47
+ return {
48
+ v: ACCOUNT_V,
49
+ apiBase: text(src.apiBase, 200),
50
+ // The console's origin, from the approval page the API sent: where this
51
+ // device's page in Machines is.
52
+ appBase: text(src.appBase, 200),
53
+ accountId: text(src.accountId, 64),
54
+ email: text(src.email, 256),
55
+ deviceId: text(src.deviceId, 64),
56
+ deviceName: text(src.deviceName, 128),
57
+ connectedAt: text(src.connectedAt, 40),
58
+ tokenStorage,
59
+ // The token, for the file backend only; the DPAPI ciphertext for Windows.
60
+ token: tokenStorage === "file" && typeof src.token === "string" && DEVICE_TOKEN.test(src.token) ? src.token : "",
61
+ tokenCipher: tokenStorage === "dpapi" ? text(src.tokenCipher, 4096) : "",
62
+ // Why this deck stopped being connected, when the API ended it.
63
+ revokedAt: text(src.revokedAt, 40),
64
+ revokedReason: nullableText(src.revokedReason, 32),
65
+ // The account this deck was last connected to, kept after a disconnect so a
66
+ // reconnect to the SAME account uploads and one to another never does.
67
+ previousAccountId: text(src.previousAccountId, 64),
68
+ sync: src.sync && typeof src.sync === "object" && !Array.isArray(src.sync) ? src.sync : null,
69
+ };
70
+ }
71
+
72
+ /** A fresh, not-connected record. */
73
+ export function emptyAccount() {
74
+ return normaliseAccount({});
75
+ }
76
+
77
+ /**
78
+ * Read account.json. ENOENT is "never connected"; a file that will not parse
79
+ * is said once and read as never connected too — the next write replaces it,
80
+ * which costs a reconnect and nothing else (there is no LAN key in here to
81
+ * lose, unlike prefs.json).
82
+ */
83
+ export async function loadAccount(home = deckDataDir(), deps = {}) {
84
+ const read = deps.readFile ?? readFile;
85
+ const warn = deps.warn ?? console.error;
86
+ let raw;
87
+ try {
88
+ raw = await read(accountPath(home), "utf8");
89
+ } catch (err) {
90
+ if (err?.code !== "ENOENT") warn(`${PRODUCT}: could not read ${ACCOUNT_FILE}: ${err?.code ?? "error"}`);
91
+ return emptyAccount();
92
+ }
93
+ try {
94
+ return normaliseAccount(JSON.parse(stripBom(raw)));
95
+ } catch {
96
+ warn(`${PRODUCT}: ${ACCOUNT_FILE} is not JSON; this deck starts disconnected`);
97
+ return emptyAccount();
98
+ }
99
+ }
100
+
101
+ let chain = Promise.resolve();
102
+
103
+ /** Write the whole record, behind every write already queued, atomically and
104
+ * at 0600 from the first byte. Answers what was written. */
105
+ export function saveAccount(record, home = deckDataDir(), deps = {}) {
106
+ const job = () => writeRecord(normaliseAccount(record), home, deps);
107
+ const started = chain.then(job, job);
108
+ chain = started.then(() => {}, () => {});
109
+ return started;
110
+ }
111
+
112
+ async function writeRecord(next, home, deps) {
113
+ const mk = deps.mkdir ?? mkdir;
114
+ const temp = deps.createTemp ?? createTemp;
115
+ const setMode = deps.chmod ?? chmod;
116
+ const mv = deps.rename ?? renameWithRetry;
117
+ const drop = deps.unlink ?? unlink;
118
+ const target = accountPath(home);
119
+ await mk(home, { recursive: true, mode: 0o700 });
120
+ const { tmp, handle } = await temp(target, { mode: ACCOUNT_MODE });
121
+ let landed = false;
122
+ try {
123
+ try {
124
+ await handle.writeFile(JSON.stringify(next, null, 2) + "\n", "utf8");
125
+ await handle.sync();
126
+ } finally {
127
+ await handle.close();
128
+ }
129
+ await setMode(tmp, ACCOUNT_MODE);
130
+ await mv(tmp, target);
131
+ landed = true;
132
+ } finally {
133
+ // A temp left behind can hold the token in the clear.
134
+ if (!landed) await drop(tmp).catch(() => {});
135
+ }
136
+ return next;
137
+ }