@point-seven-studio/jq-deck-server 0.0.0-stage → 0.2.1

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,447 @@
1
+ // src/report.ts
2
+ var MAX_REPOS = 200;
3
+ var MAX_BODY_BYTES = 256 * 1024;
4
+ var MAX_QUESTIONS = 20;
5
+ var MAX_QUESTION_CHARS = 400;
6
+ var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
7
+ function count(v, field, max = 1e5) {
8
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 0 || v > max) throw new Error(`${field} must be a whole number from 0 to ${max}`);
9
+ return v;
10
+ }
11
+ function isoOrNull(v, field) {
12
+ if (v === null || v === void 0) return null;
13
+ if (typeof v !== "string" || v.length > 40 || Number.isNaN(Date.parse(v))) throw new Error(`${field} must be a date or null`);
14
+ return new Date(Date.parse(v)).toISOString();
15
+ }
16
+ function repoName(v) {
17
+ if (typeof v !== "string") throw new Error("a repository needs a name");
18
+ const name = v.trim();
19
+ if (!name || name.length > 100 || /[\u0000-\u001f\u007f/\\]/.test(name)) throw new Error("a repository name must be 1 to 100 characters with no slash");
20
+ return name;
21
+ }
22
+ function remote(v) {
23
+ return typeof v === "string" && v.length <= 200 && /^[a-z0-9][a-z0-9.-]*(\/[A-Za-z0-9._~-]+)+$/.test(v) ? v : null;
24
+ }
25
+ function questions(v) {
26
+ if (v === void 0 || v === null) return void 0;
27
+ if (!Array.isArray(v) || v.length > MAX_QUESTIONS) throw new Error(`questions must be a list of at most ${MAX_QUESTIONS}`);
28
+ const out = v.map((q) => {
29
+ if (!isObj(q) || typeof q.text !== "string") throw new Error("each question needs its text");
30
+ const text2 = q.text.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "").trim().slice(0, MAX_QUESTION_CHARS);
31
+ return { asked_at: isoOrNull(q.asked_at, "questions.asked_at"), text: text2 };
32
+ }).filter((q) => q.text);
33
+ return out.length ? out : void 0;
34
+ }
35
+ function sanitizeReport(value) {
36
+ if (!isObj(value)) throw new Error("the report must be a JSON object");
37
+ if (value.v !== 1) throw new Error("unknown report version (this server reads version 1)");
38
+ const generated = isoOrNull(value.generated_at, "generated_at");
39
+ if (!generated) throw new Error("generated_at is missing");
40
+ if (!Array.isArray(value.repos)) throw new Error("repos must be a list");
41
+ if (value.repos.length > MAX_REPOS) throw new Error(`a report holds at most ${MAX_REPOS} repositories`);
42
+ const repos = value.repos.map((r) => {
43
+ if (!isObj(r)) throw new Error("each repository must be an object");
44
+ const setup = isObj(r.setup) ? { score: count(r.setup.score, "setup.score", 100), fail: count(r.setup.fail, "setup.fail"), warn: count(r.setup.warn, "setup.warn") } : null;
45
+ const asked = questions(r.questions);
46
+ return {
47
+ name: repoName(r.name),
48
+ remote: remote(r.remote),
49
+ sessions: count(r.sessions, "sessions"),
50
+ live: count(r.live, "live"),
51
+ needs_you: count(r.needs_you, "needs_you"),
52
+ abandoned: count(r.abandoned, "abandoned"),
53
+ waiting_since: isoOrNull(r.waiting_since, "waiting_since"),
54
+ last_activity_at: isoOrNull(r.last_activity_at, "last_activity_at"),
55
+ setup,
56
+ unread: r.unread === null || r.unread === void 0 ? null : count(r.unread, "unread"),
57
+ ...asked ? { questions: asked } : {}
58
+ };
59
+ });
60
+ return { v: 1, generated_at: generated, repos };
61
+ }
62
+
63
+ // src/team.ts
64
+ var FRESH_MS = 5 * 6e4;
65
+ var SILENT_MS = 24 * 36e5;
66
+ function freshness(receivedAt, now) {
67
+ const age = Math.max(0, now - Date.parse(receivedAt));
68
+ return { freshness: age <= FRESH_MS ? "fresh" : age <= SILENT_MS ? "quiet" : "silent", minutes_ago: Math.floor(age / 6e4) };
69
+ }
70
+ var lower = (s) => s.toLowerCase();
71
+ function visible(viewer, repo) {
72
+ if (!viewer?.repos || viewer.repos.length === 0) return true;
73
+ const allowed = new Set(viewer.repos.map(lower));
74
+ return allowed.has(lower(repo.name)) || !!repo.remote && allowed.has(lower(repo.remote));
75
+ }
76
+ function duration(minutes) {
77
+ if (minutes < 1) return "under a minute";
78
+ if (minutes < 60) return `${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
79
+ const hours = Math.floor(minutes / 60);
80
+ if (hours < 48) return `${hours} ${hours === 1 ? "hour" : "hours"}`;
81
+ return `${Math.floor(hours / 24)} days`;
82
+ }
83
+ var plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
84
+ function buildTeam(reports, now, viewer = null) {
85
+ const scoped = !!viewer?.repos?.length;
86
+ const groups = /* @__PURE__ */ new Map();
87
+ const machines = [];
88
+ for (const stored of reports) {
89
+ const state = freshness(stored.received_at, now);
90
+ const mine = stored.report.repos.filter((r) => visible(viewer, r));
91
+ if (scoped && mine.length === 0) continue;
92
+ machines.push({ machine: stored.machine, who: stored.who, received_at: stored.received_at, ...state });
93
+ if (state.freshness === "silent") continue;
94
+ for (const repo of mine) {
95
+ const key = repo.remote ? lower(repo.remote) : `name:${lower(repo.name)}`;
96
+ const group = groups.get(key) ?? { key, name: repo.name, remote: repo.remote, needs_you: 0, rows: [] };
97
+ const fresh = state.freshness === "fresh";
98
+ const since = fresh && repo.needs_you > 0 && repo.waiting_since ? Math.max(0, Math.floor((now - Date.parse(repo.waiting_since)) / 6e4)) : null;
99
+ group.rows.push({ ...repo, questions: fresh ? repo.questions : void 0, machine: stored.machine, who: stored.who, ...state, waiting_minutes: since });
100
+ if (fresh) group.needs_you += repo.needs_you;
101
+ groups.set(key, group);
102
+ }
103
+ }
104
+ const longest = (g) => Math.max(-1, ...g.rows.map((r) => r.waiting_minutes ?? -1));
105
+ const list = [...groups.values()];
106
+ for (const g of list) g.rows.sort((a, b) => (b.waiting_minutes ?? -1) - (a.waiting_minutes ?? -1) || a.who.localeCompare(b.who) || a.machine.localeCompare(b.machine));
107
+ list.sort((a, b) => longest(b) - longest(a) || b.needs_you - a.needs_you || a.name.localeCompare(b.name));
108
+ machines.sort((a, b) => a.minutes_ago - b.minutes_ago || a.machine.localeCompare(b.machine));
109
+ const freshRows = list.flatMap((g) => g.rows).filter((r) => r.freshness === "fresh");
110
+ const totals = {
111
+ needs_you: freshRows.reduce((n, r) => n + r.needs_you, 0),
112
+ sessions: freshRows.reduce((n, r) => n + r.sessions, 0),
113
+ machines_fresh: machines.filter((m) => m.freshness === "fresh").length,
114
+ machines_quiet: machines.filter((m) => m.freshness === "quiet").length,
115
+ machines_silent: machines.filter((m) => m.freshness === "silent").length
116
+ };
117
+ let headline;
118
+ if (machines.length === 0) headline = scoped ? "No machine has reported a repository you can see." : "No machine has reported yet.";
119
+ else if (totals.machines_fresh === 0) headline = `No machine has reported in the last 5 minutes (${plural(machines.length, "machine", "machines")} known), so nothing below is current.`;
120
+ else if (totals.needs_you === 0) headline = `No session is waiting on a person: ${plural(totals.sessions, "session", "sessions")} on ${plural(totals.machines_fresh, "machine", "machines")} read.`;
121
+ else {
122
+ const top = freshRows.filter((r) => r.waiting_minutes !== null).sort((a, b) => b.waiting_minutes - a.waiting_minutes)[0];
123
+ const where = top ? ` The longest has waited ${duration(top.waiting_minutes)}: ${top.name}, ${top.who}.` : "";
124
+ headline = `${plural(totals.needs_you, "session is", "sessions are")} waiting on a person, on ${plural(totals.machines_fresh, "machine", "machines")}.${where}`;
125
+ }
126
+ const late = totals.machines_quiet + totals.machines_silent;
127
+ if (late > 0 && totals.machines_fresh > 0) headline += ` ${plural(late, "machine has", "machines have")} gone quiet and ${late === 1 ? "is" : "are"} not counted.`;
128
+ return { generated_at: new Date(now).toISOString(), headline, totals, groups: list, machines, scoped };
129
+ }
130
+
131
+ // src/store.ts
132
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
133
+ import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
134
+ import path from "path";
135
+ var NAME = /^[a-z0-9][a-z0-9._-]{0,62}$/;
136
+ function checkName(name) {
137
+ if (!NAME.test(name)) throw new Error("a name is 1 to 63 of: a-z 0-9 . _ - (starting with a letter or digit)");
138
+ return name;
139
+ }
140
+ var sha = (s) => createHash("sha256").update(s).digest("hex");
141
+ var configFile = (dir) => path.join(dir, "config.json");
142
+ var reportFile = (dir, machine) => path.join(dir, "reports", `${checkName(machine)}.json`);
143
+ function writeAtomic(file, text2) {
144
+ const tmp = `${file}.${process.pid}.tmp`;
145
+ writeFileSync(tmp, text2, { mode: 384 });
146
+ renameSync(tmp, file);
147
+ }
148
+ function initStore(dir) {
149
+ if (existsSync(configFile(dir))) throw new Error(`${dir} is already a jq-deck-server folder`);
150
+ mkdirSync(path.join(dir, "reports"), { recursive: true });
151
+ chmodSync(dir, 448);
152
+ writeAtomic(configFile(dir), JSON.stringify({ machines: [], viewers: [] }, null, 2) + "\n");
153
+ }
154
+ function readConfig(dir) {
155
+ if (!existsSync(configFile(dir))) throw new Error(`not a jq-deck-server folder (run: jq-deck-server init ${dir})`);
156
+ const raw = JSON.parse(readFileSync(configFile(dir), "utf8"));
157
+ return { machines: Array.isArray(raw?.machines) ? raw.machines : [], viewers: Array.isArray(raw?.viewers) ? raw.viewers : [] };
158
+ }
159
+ function writeConfig(dir, config) {
160
+ writeAtomic(configFile(dir), JSON.stringify(config, null, 2) + "\n");
161
+ }
162
+ function taken(config, name) {
163
+ return config.machines.some((m) => m.name === name) || config.viewers.some((v) => v.name === name);
164
+ }
165
+ function addMachine(dir, name, who) {
166
+ const config = readConfig(dir);
167
+ if (taken(config, checkName(name))) throw new Error(`the name ${name} is in use`);
168
+ const label = who.trim().replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 60);
169
+ if (!label) throw new Error("--who needs a name to show on the board");
170
+ const token = `jqm_${randomBytes(32).toString("base64url")}`;
171
+ config.machines.push({ name, who: label, token_sha256: sha(token) });
172
+ writeConfig(dir, config);
173
+ return token;
174
+ }
175
+ function addViewer(dir, name, repos) {
176
+ const config = readConfig(dir);
177
+ if (taken(config, checkName(name))) throw new Error(`the name ${name} is in use`);
178
+ const token = `jqv_${randomBytes(32).toString("base64url")}`;
179
+ config.viewers.push({ name, token_sha256: sha(token), ...repos && repos.length ? { repos } : {} });
180
+ writeConfig(dir, config);
181
+ return token;
182
+ }
183
+ function remove(dir, name) {
184
+ const config = readConfig(dir);
185
+ if (!taken(config, checkName(name))) return false;
186
+ config.machines = config.machines.filter((m) => m.name !== name);
187
+ config.viewers = config.viewers.filter((v) => v.name !== name);
188
+ writeConfig(dir, config);
189
+ rmSync(reportFile(dir, name), { force: true });
190
+ return true;
191
+ }
192
+ function match(list, token) {
193
+ if (!token || token.length > 200) return null;
194
+ const given = Buffer.from(sha(token), "hex");
195
+ let found = null;
196
+ for (const item of list) {
197
+ const want = Buffer.from(String(item.token_sha256), "hex");
198
+ if (want.length === given.length && timingSafeEqual(want, given)) found = item;
199
+ }
200
+ return found;
201
+ }
202
+ var machineFor = (config, token) => match(config.machines, token);
203
+ var viewerFor = (config, token) => match(config.viewers, token);
204
+ function saveReport(dir, machine, report, now) {
205
+ const stored = { machine: machine.name, who: machine.who, received_at: new Date(now).toISOString(), report };
206
+ writeAtomic(reportFile(dir, machine.name), JSON.stringify(stored));
207
+ }
208
+ function readReports(dir, config) {
209
+ const known = new Map(config.machines.map((m) => [m.name, m]));
210
+ const out = [];
211
+ const folder = path.join(dir, "reports");
212
+ if (!existsSync(folder)) return out;
213
+ for (const file of readdirSync(folder).filter((f) => f.endsWith(".json"))) {
214
+ const machine = known.get(file.slice(0, -5));
215
+ if (!machine) continue;
216
+ try {
217
+ const stored = JSON.parse(readFileSync(path.join(folder, file), "utf8"));
218
+ out.push({ ...stored, machine: machine.name, who: machine.who });
219
+ } catch {
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+
225
+ // src/server.ts
226
+ import { createServer } from "http";
227
+
228
+ // src/page.ts
229
+ var esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
230
+ var STYLE = `
231
+ :root{--bg:#f7f6f2;--card:#fff;--fg:#1d1c19;--mut:#6b675e;--line:#dedbd2;--well:#f1efe9;--warn:#a1500a;--ok:#1f6b45;--bad:#a3262b;--link:#1d4f91}
232
+ @media (prefers-color-scheme:dark){:root{--bg:#161512;--card:#1f1e1a;--fg:#ece9e1;--mut:#a09c91;--line:#35332d;--well:#161512;--warn:#e0a25a;--ok:#7ccba0;--bad:#ef8a8e;--link:#8fb8ee}}
233
+ *{box-sizing:border-box}
234
+ body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,sans-serif}
235
+ main{max-width:1000px;margin:0 auto;padding:20px 16px 48px}
236
+ h1{font-size:22px;margin:0}h2{font-size:15px;margin:22px 0 8px}.head{margin:4px 0 0;font-weight:600}
237
+ .mut{color:var(--mut);font-size:12px}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.ok,.warn,.bad{font-size:12px;font-weight:600}
238
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;overflow:hidden;margin:10px 0}
239
+ .card h3{font-size:15px;margin:0;padding:10px 12px;word-break:break-word}.card h3 .mut{font-weight:400}
240
+ table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:8px 12px;border-top:1px solid var(--line);vertical-align:top;font-weight:400}
241
+ thead th{font-size:12px;color:var(--mut);font-weight:600}tbody th{font-weight:600}
242
+ tr.quiet td,tr.quiet th,tr.quiet .warn,tr.quiet .bad,tr.quiet .ok{color:var(--mut)}
243
+ tr.asked td{border-top:0;padding-top:0}tr.asked td::before{content:none}
244
+ .q{background:var(--well);margin:6px 0 2px;padding:8px 10px;border-radius:8px;border-left:3px solid var(--warn)}.q p{margin:0;white-space:pre-wrap;word-break:break-word;font-size:14px}
245
+ .top{display:flex;justify-content:space-between;align-items:flex-start;gap:12px}
246
+ button{white-space:nowrap;font:inherit;font-size:14px;min-height:40px;border:1px solid var(--line);background:var(--card);color:var(--fg);border-radius:8px;padding:6px 14px;cursor:pointer}
247
+ button.primary{background:var(--fg);color:var(--bg);border-color:var(--fg);font-weight:600}
248
+ button:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid var(--link);outline-offset:2px}
249
+ .tiles{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:14px 0 4px}
250
+ .tile{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 12px}.tile b{display:block;font-size:24px;line-height:1.2}.tile.hot b{color:var(--warn)}
251
+ table{table-layout:fixed}col.who{width:24%}col.n{width:13%}col.wait{width:21%}col.setup{width:17%}col.mail{width:12%}col.heard{width:13%}
252
+ input{font:inherit;width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:8px;background:var(--card);color:var(--fg)}
253
+ label{display:block;font-weight:600;margin-bottom:6px}.pad{padding:16px}
254
+ ul{margin:0;padding:0;list-style:none}li{padding:6px 12px;border-top:1px solid var(--line)}li:first-child{border-top:0}
255
+ @media (max-width:760px){table,tbody{display:block}colgroup{display:none}.tile b{font-size:20px}thead{display:none}tr{display:block;border-top:1px solid var(--line);padding:6px 0}th,td{display:block;border:0;padding:2px 12px}td::before{content:attr(data-l) ": ";color:var(--mut);font-size:12px}}
256
+ `;
257
+ var heard = (minutes) => minutes < 1 ? "just now" : `${duration(minutes)} ago`;
258
+ var minutesSince = (iso, now) => Math.max(0, Math.floor((now - Date.parse(iso)) / 6e4));
259
+ var clock = (iso) => `${iso.slice(11, 16)} UTC`;
260
+ function row(r, now) {
261
+ const quiet = r.freshness !== "fresh";
262
+ const waiting = quiet ? '<span class="mut">not current</span>' : r.needs_you > 0 ? `<span class="warn">${r.needs_you} waiting${r.waiting_minutes !== null ? `, ${esc(duration(r.waiting_minutes))}` : ""}</span>` : '<span class="mut">none</span>';
263
+ const setup = !r.setup ? '<span class="mut">not checked</span>' : `${r.setup.score}% ${r.setup.fail > 0 ? `<span class="bad">${r.setup.fail} to fix</span>` : r.setup.warn > 0 ? `<span class="warn">${r.setup.warn} to look at</span>` : '<span class="ok">all good</span>'}`;
264
+ const mail = r.unread === null ? '<span class="mut">no inbox</span>' : r.unread === 0 ? '<span class="mut">none unread</span>' : `${r.unread} unread`;
265
+ const asked = (r.questions ?? []).map((q) => `<div class="q"><span class="mut">${esc(r.who)}'s session asked${q.asked_at ? ` ${esc(heard(minutesSince(q.asked_at, now)))}` : ""}</span><p>${esc(q.text)}</p></div>`).join("");
266
+ const askedRow = asked ? `<tr class="asked"><td colspan="6">${asked}</td></tr>` : "";
267
+ return `<tr${quiet ? ' class="quiet"' : ""}><th scope="row">${esc(r.who)} <span class="mut">${esc(r.machine)}</span></th><td data-l="Sessions">${r.sessions} <span class="mut">(${r.live} live)</span></td><td data-l="Waiting on a person">${waiting}</td><td data-l="Setup">${setup}</td><td data-l="Mail">${mail}</td><td data-l="Last heard"><span class="mut">${esc(heard(r.minutes_ago))}</span></td></tr>${askedRow}`;
268
+ }
269
+ function renderTeam(team, viewerName, version) {
270
+ const now = Date.parse(team.generated_at);
271
+ const t = team.totals;
272
+ const known = t.machines_fresh + t.machines_quiet + t.machines_silent;
273
+ const tiles = `<div class="tiles"><div class="tile${t.needs_you > 0 ? " hot" : ""}"><b>${t.needs_you}</b><span class="mut">waiting on a person</span></div><div class="tile"><b>${t.sessions}</b><span class="mut">${t.sessions === 1 ? "session" : "sessions"}</span></div><div class="tile"><b>${t.machines_fresh}<span class="mut"> of ${known}</span></b><span class="mut">${known === 1 ? "machine" : "machines"} reporting</span></div></div>`;
274
+ const groups = team.groups.map(
275
+ (g) => `<section class="card"><h3>${esc(g.name)}${g.remote ? ` <span class="mut">${esc(g.remote)}</span>` : ""}</h3><table><colgroup><col class="who"><col class="n"><col class="wait"><col class="setup"><col class="mail"><col class="heard"></colgroup><thead><tr><th scope="col">Who</th><th scope="col">Sessions</th><th scope="col">Waiting on a person</th><th scope="col">Setup</th><th scope="col">Mail</th><th scope="col">Last heard</th></tr></thead><tbody>${g.rows.map((r) => row(r, now)).join("")}</tbody></table></section>`
276
+ ).join("");
277
+ const machines = team.machines.map((m) => `<li>${esc(m.who)} <span class="mut">${esc(m.machine)} \xB7 last heard ${esc(heard(m.minutes_ago))}</span>${m.freshness === "fresh" ? "" : ` <span class="warn">${m.freshness === "quiet" ? "quiet, not counted" : "silent for over a day, rows hidden"}</span>`}</li>`).join("");
278
+ return `<!doctype html>
279
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="refresh" content="60">
280
+ <title>${t.needs_you > 0 ? `(${t.needs_you}) ` : ""}JQ Deck: team</title><link rel="icon" href="data:,"><style>${STYLE}</style></head><body><main>
281
+ <div class="top"><div><h1>JQ Deck: team</h1><p class="head">${esc(team.headline)}</p></div><form method="post" action="/logout"><button>Sign out</button></form></div>
282
+ ${known > 0 ? tiles : ""}
283
+ <p class="mut">Read at ${esc(clock(team.generated_at))}, signed in as ${esc(viewerName)}${team.scoped ? ", who sees some repositories only" : ""}. Reloads every minute. Read-only: answer a session where it is running.</p>
284
+ ${groups || '<p class="card pad mut">No repository to show.</p>'}
285
+ <h2>Machines</h2>
286
+ <div class="card"><ul>${machines || '<li class="mut">None yet. On each machine: <code>jq-deck --watch --exec "jq-deck-server send --url THIS-ADDRESS"</code></li>'}</ul></div>
287
+ <p class="mut">A machine sends counts and scores: no folder path and no message. What a session asked is sent only where that machine opted the folder in. JQ Deck Server ${esc(version)}.</p>
288
+ </main></body></html>`;
289
+ }
290
+ function renderLogin(message) {
291
+ return `<!doctype html>
292
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
293
+ <title>JQ Deck: sign in</title><link rel="icon" href="data:,"><style>${STYLE}</style></head><body><main style="max-width:420px">
294
+ <h1>JQ Deck: team</h1>
295
+ <p class="mut" style="font-size:14px;margin:4px 0 12px">Which Claude Code sessions are waiting on a person, across this team's machines.</p>
296
+ <form class="card pad" method="post" action="/login">
297
+ ${message ? `<p class="bad" role="alert">${esc(message)}</p>` : ""}
298
+ <label for="token">Viewer token</label>
299
+ <input id="token" name="token" type="password" autocomplete="current-password" placeholder="jqv_..." aria-describedby="token-help" required autofocus>
300
+ <p class="mut" id="token-help">It starts with <code>jqv_</code>. Whoever runs this server gives you one. A machine token (<code>jqm_</code>) does not sign in.</p>
301
+ <button class="primary">Sign in</button>
302
+ </form></main></body></html>`;
303
+ }
304
+
305
+ // src/server.ts
306
+ var COOKIE = "jq_deck";
307
+ var HTML = { "content-type": "text/html; charset=utf-8" };
308
+ var TEXT = { "content-type": "text/plain; charset=utf-8" };
309
+ var JSON_TYPE = { "content-type": "application/json; charset=utf-8" };
310
+ var text = (status, body, headers = {}) => ({ status, headers: { ...TEXT, ...headers }, body });
311
+ var bearer = (h) => h && /^Bearer\s+\S+$/i.test(h) ? h.replace(/^Bearer\s+/i, "") : null;
312
+ function cookieToken(header) {
313
+ for (const part of (header || "").split(";")) {
314
+ const [k, ...v] = part.trim().split("=");
315
+ if (k === COOKIE) return v.join("=") || null;
316
+ }
317
+ return null;
318
+ }
319
+ var cookie = (ctx, value, maxAge) => `${COOKIE}=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAge}${ctx.secureCookie ? "; Secure" : ""}`;
320
+ function handle(req, ctx) {
321
+ const now = (ctx.now ?? Date.now)();
322
+ const route = `${req.method} ${req.path}`;
323
+ if (route === "GET /healthz") return text(200, "ok");
324
+ const config = readConfig(ctx.dir);
325
+ if (route === "POST /report") {
326
+ const machine = machineFor(config, bearer(req.authorization));
327
+ if (!machine) return text(401, "unknown machine token");
328
+ let report;
329
+ try {
330
+ report = sanitizeReport(JSON.parse(req.body));
331
+ } catch (e) {
332
+ return text(400, `not a report: ${e?.message || e}`);
333
+ }
334
+ saveReport(ctx.dir, machine, report, now);
335
+ return { status: 204, headers: {}, body: "" };
336
+ }
337
+ if (route === "GET /login") return { status: 200, headers: HTML, body: renderLogin(null) };
338
+ if (route === "POST /login") {
339
+ const token = new URLSearchParams(req.body).get("token")?.trim();
340
+ if (!viewerFor(config, token)) {
341
+ const why = machineFor(config, token) ? "That is a machine token. Sign in with a viewer token, which starts with jqv_." : "That token is not known to this server.";
342
+ return { status: 401, headers: HTML, body: renderLogin(why) };
343
+ }
344
+ return { status: 303, headers: { location: "/", "set-cookie": cookie(ctx, token, 30 * 86400) }, body: "" };
345
+ }
346
+ if (route === "POST /logout") return { status: 303, headers: { location: "/login", "set-cookie": cookie(ctx, "", 0) }, body: "" };
347
+ if (route === "GET /" || route === "GET /api/team") {
348
+ const api = req.path === "/api/team";
349
+ const viewer = viewerFor(config, cookieToken(req.cookie)) ?? (api ? viewerFor(config, bearer(req.authorization)) : null);
350
+ if (!viewer) return api ? text(401, "a viewer token is needed") : { status: 303, headers: { location: "/login" }, body: "" };
351
+ const team = buildTeam(readReports(ctx.dir, config), now, viewer);
352
+ return api ? { status: 200, headers: JSON_TYPE, body: JSON.stringify(team, null, 2) } : { status: 200, headers: HTML, body: renderTeam(team, viewer.name, ctx.version) };
353
+ }
354
+ return text(404, "not found");
355
+ }
356
+ var SECURITY_HEADERS = {
357
+ "cache-control": "no-store",
358
+ "x-frame-options": "DENY",
359
+ "x-content-type-options": "nosniff",
360
+ "referrer-policy": "no-referrer",
361
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; img-src data:; form-action 'self'; frame-ancestors 'none'; base-uri 'none'"
362
+ };
363
+ function startServer(ctx, port, host, onListen) {
364
+ const server = createServer((req, res) => {
365
+ const chunks = [];
366
+ let size = 0;
367
+ let tooBig = false;
368
+ req.on("data", (chunk) => {
369
+ size += chunk.length;
370
+ if (size > MAX_BODY_BYTES) tooBig = true;
371
+ else chunks.push(chunk);
372
+ });
373
+ req.on("end", () => {
374
+ let reply;
375
+ try {
376
+ reply = tooBig ? text(413, "the body is too large") : handle({ method: req.method || "GET", path: (req.url || "/").split("?")[0], authorization: req.headers.authorization, cookie: req.headers.cookie, body: Buffer.concat(chunks).toString("utf8") }, ctx);
377
+ } catch (e) {
378
+ console.error("jq-deck-server:", e?.message || e);
379
+ reply = text(500, "server error");
380
+ }
381
+ res.writeHead(reply.status, { ...SECURITY_HEADERS, ...reply.headers });
382
+ res.end(reply.body);
383
+ });
384
+ });
385
+ server.listen(port, host, () => {
386
+ const address = server.address();
387
+ onListen?.(typeof address === "object" && address ? address.port : port);
388
+ });
389
+ return server;
390
+ }
391
+
392
+ // src/send.ts
393
+ var LOCAL = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
394
+ function reportUrl(base) {
395
+ let url;
396
+ try {
397
+ url = new URL(base);
398
+ } catch {
399
+ throw new Error(`--url is not an address: ${base}`);
400
+ }
401
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL.has(url.hostname))) throw new Error("--url must start with https (plain http is allowed only to this machine)");
402
+ if (url.username || url.password) throw new Error("--url must not hold a user name or password; the token goes in $JQ_DECK_TOKEN");
403
+ return new URL("/report", url);
404
+ }
405
+ async function send(base, token, input, post = fetch) {
406
+ if (!token) throw new Error("set $JQ_DECK_TOKEN to this machine's token (from: jq-deck-server add-machine)");
407
+ const url = reportUrl(base);
408
+ const report = sanitizeReport(JSON.parse(input));
409
+ const res = await post(url, {
410
+ method: "POST",
411
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
412
+ body: JSON.stringify(report),
413
+ signal: AbortSignal.timeout(1e4),
414
+ redirect: "error"
415
+ });
416
+ if (res.status !== 204) throw new Error(`the server answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
417
+ }
418
+ export {
419
+ FRESH_MS,
420
+ MAX_BODY_BYTES,
421
+ MAX_QUESTIONS,
422
+ MAX_QUESTION_CHARS,
423
+ MAX_REPOS,
424
+ SECURITY_HEADERS,
425
+ SILENT_MS,
426
+ addMachine,
427
+ addViewer,
428
+ buildTeam,
429
+ checkName,
430
+ duration,
431
+ freshness,
432
+ handle,
433
+ initStore,
434
+ machineFor,
435
+ readConfig,
436
+ readReports,
437
+ remove,
438
+ renderLogin,
439
+ renderTeam,
440
+ reportUrl,
441
+ sanitizeReport,
442
+ saveReport,
443
+ send,
444
+ startServer,
445
+ viewerFor,
446
+ visible
447
+ };