@dreamforgestudiollc/emet 0.3.2 → 0.3.4

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.
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Carry-forward close.
3
+ *
4
+ * emet_session_close still compares this session's receipts with the store.
5
+ * A later session advances HANDOFF and STATE, so those receipts no longer
6
+ * match, the close stays blocked, and retries used to count toward the
7
+ * three-close cap.
8
+ *
9
+ * A records/ session disposition (templates/SESSIONDISPOSITION.md, #95)
10
+ * documents that fact. The row does not close the graph and it is not a
11
+ * receipt. This path closes the graph only when the owner door, or the
12
+ * credential that wrote the session, cites that current row and the later
13
+ * continuity versions that superseded the receipts. Transcripts stay.
14
+ * A declared source is not authority. A refused call is not a blocked close
15
+ * and is not counted.
16
+ */
17
+
18
+ import { COLLECTION_PREFIX } from './database.js';
19
+ import { actorIsOwner } from './attribution.js';
20
+ import { rawActor, resolveTokenSubject } from './persons.js';
21
+ import {
22
+ parseDispositionRows,
23
+ SESSION_DISPOSITION_TEMPLATE
24
+ } from './conformance.js';
25
+ import { readDispositionCoverage } from './checkpoint.js';
26
+ import { isBotTag, botHandoffDoc, mainRecordIds } from './session-graph.js';
27
+
28
+ export const CARRY_FORWARD_DISPOSITIONS = Object.freeze([
29
+ 'CARRIED_FORWARD',
30
+ 'SUPERSEDED_BY_LATER_SESSION',
31
+ 'ABANDONED_NO_TRANSCRIPT'
32
+ ]);
33
+ const CLOSABLE = new Set(CARRY_FORWARD_DISPOSITIONS);
34
+ const PART_SUFFIX = /_(?:verbatim_)?part\d+$/i;
35
+
36
+ export function closeBaseId(sessionId) {
37
+ const id = typeof sessionId === 'string' ? sessionId.trim() : '';
38
+ if (!id) return null;
39
+ return id.replace(PART_SUFFIX, '') || null;
40
+ }
41
+
42
+ function toMillis(value) {
43
+ if (value instanceof Date) {
44
+ const t = value.getTime();
45
+ return Number.isFinite(t) ? t : null;
46
+ }
47
+ if (typeof value === 'number' && Number.isFinite(value)) return value > 1e11 ? value : value * 1000;
48
+ if (typeof value === 'string') {
49
+ const t = Date.parse(value);
50
+ return Number.isFinite(t) ? t : null;
51
+ }
52
+ return null;
53
+ }
54
+
55
+ export function hasCarryForward(options) {
56
+ return !!options && Object.prototype.hasOwnProperty.call(options, 'carry_forward') && options.carry_forward != null;
57
+ }
58
+
59
+ export function parseCarryForward(value) {
60
+ if (value && typeof value === 'object' && !Array.isArray(value)) return { value, problem: null };
61
+ if (typeof value === 'string' && value.trim().startsWith('{')) {
62
+ try {
63
+ const parsed = JSON.parse(value);
64
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return { value: parsed, problem: null };
65
+ } catch { /* text that does not parse is not a citation */ }
66
+ }
67
+ return { value: null, problem: 'carry_forward must be an object with disposition_doc, disposition_version, and citations' };
68
+ }
69
+
70
+ /**
71
+ * Owner door, or the credential that wrote the session. A declared source,
72
+ * a guest door, and a source named only on the call are not authority.
73
+ * No HTTP actor is the local stdio owner, the same rule as actorIsOwner.
74
+ */
75
+ function credentialTag(actor) {
76
+ if (!actor || actor.sourceBasis === 'declared') return null;
77
+ if (actor.sourceBasis === 'subkey' || actor.sourceBasis === 'credential') {
78
+ const tag = typeof actor.effectiveTag === 'string' ? actor.effectiveTag.trim() : '';
79
+ return tag || null;
80
+ }
81
+ if (actor.sourceBasis === 'login') {
82
+ const tag = typeof actor.sourceTag === 'string' ? actor.sourceTag.trim() : '';
83
+ return tag || null;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ export function carryForwardAuthority(actor, evidence = {}) {
89
+ const a = actor && typeof actor === 'object' ? actor : null;
90
+ if (!a || a.transport !== 'http') return { ok: true, basis: 'owner' };
91
+ if (a.door === 'guest') {
92
+ return { ok: false, basis: null, reason: 'a guest door cannot carry-forward close a session' };
93
+ }
94
+ if (a.sourceBasis === 'declared') {
95
+ return { ok: false, basis: null, reason: 'a declared source is not authority for a carry-forward close' };
96
+ }
97
+ if (actorIsOwner(a, a.ownerId) && (a.door === 'owner' || a.door == null)) {
98
+ return { ok: true, basis: 'owner' };
99
+ }
100
+ const opened = evidence.openedBy && typeof evidence.openedBy === 'object' ? evidence.openedBy : null;
101
+ if (opened && opened.person_id && a.personId && opened.person_id !== a.personId) {
102
+ return { ok: false, basis: null, reason: 'carry-forward close needs the owner door, or the credential that opened this session' };
103
+ }
104
+ const credTag = credentialTag(a);
105
+ const sameTag = !!credTag && !!evidence.sessionTag && credTag === evidence.sessionTag;
106
+ const sameClient = !!(opened && a.clientId && opened.client_id === a.clientId && a.personId && opened.person_id === a.personId);
107
+ const doorOk = a.door === 'member' || a.door === 'owner' || a.door == null;
108
+ if (doorOk && (sameClient || sameTag)) return { ok: true, basis: 'writer' };
109
+ return { ok: false, basis: null, reason: 'carry-forward close needs the owner door, or the credential that opened this session' };
110
+ }
111
+
112
+ function writerBase(sessionId) {
113
+ if (typeof sessionId !== 'string' || !sessionId.trim()) return null;
114
+ return sessionId.trim().replace(PART_SUFFIX, '');
115
+ }
116
+
117
+ function laterWriter(writers, docId, sessionBase) {
118
+ if (!writers || typeof writers.get !== 'function' || !sessionBase) return false;
119
+ const wrote = writerBase(writers.get(docId));
120
+ return !!wrote && wrote !== sessionBase;
121
+ }
122
+
123
+ /**
124
+ * True when every receipt problem is HANDOFF or STATE having moved forward
125
+ * under a later session. A same-session mismatch, a missing receipt, or a
126
+ * working-document mismatch is false: those still count toward the cap.
127
+ * "Handoff was not the last write" counts as this case only together with
128
+ * one of those later-session mismatches.
129
+ */
130
+ export function supersededStrikeSkipped(problems, { writers, handoffDoc, sessionBase } = {}) {
131
+ if (!Array.isArray(problems) || problems.length === 0 || !sessionBase) return false;
132
+ let sawLater = false;
133
+ for (const problem of problems) {
134
+ const handoff = /^handoff: receipt says v(\d+), store holds v(\d+)$/.exec(problem);
135
+ if (handoff) {
136
+ if (!(Number(handoff[2]) > Number(handoff[1]))) return false;
137
+ if (!laterWriter(writers, handoffDoc, sessionBase)) return false;
138
+ sawLater = true;
139
+ continue;
140
+ }
141
+ const board = /^board ([^:]+): receipt says v(\d+), store holds v(\d+)$/.exec(problem);
142
+ if (board) {
143
+ if (!(Number(board[3]) > Number(board[2]))) return false;
144
+ if (!laterWriter(writers, board[1], sessionBase)) return false;
145
+ sawLater = true;
146
+ continue;
147
+ }
148
+ if (/^handoff v\d+ was written by session /.test(problem) || /^board .+ was written by session /.test(problem)) {
149
+ sawLater = true;
150
+ continue;
151
+ }
152
+ if (/^handoff was not the last write /.test(problem)) continue;
153
+ return false;
154
+ }
155
+ return sawLater;
156
+ }
157
+
158
+ /**
159
+ * Receipt versions that match the store, written by a different session.
160
+ * Those numbers are the later continuity record, not this session's receipt.
161
+ */
162
+ export function foreignContinuityProblems({ receipts, writers, handoffDoc, sessionBase, documents } = {}) {
163
+ if (!receipts || !sessionBase) return [];
164
+ const byId = new Map((documents || []).map((d) => [d.doc_id, d]));
165
+ const problems = [];
166
+ const handoff = handoffDoc ? byId.get(handoffDoc) : null;
167
+ if (handoff && handoff.exists && typeof receipts.handoff_version === 'number' && receipts.handoff_version === handoff.version
168
+ && laterWriter(writers, handoffDoc, sessionBase)) {
169
+ const wrote = writerBase(writers.get(handoffDoc));
170
+ problems.push(`handoff v${handoff.version} was written by session ${wrote}, not ${sessionBase}; cite it with carry_forward`);
171
+ }
172
+ const boardId = typeof receipts.board_doc === 'string' ? receipts.board_doc : null;
173
+ const board = boardId ? byId.get(boardId) : null;
174
+ if (board && board.exists && typeof receipts.board_version === 'number' && receipts.board_version === board.version
175
+ && laterWriter(writers, boardId, sessionBase)) {
176
+ const wrote = writerBase(writers.get(boardId));
177
+ problems.push(`board ${boardId} v${board.version} was written by session ${wrote}, not ${sessionBase}; cite it with carry_forward`);
178
+ }
179
+ return problems;
180
+ }
181
+
182
+ export function assessCitations(citations, docs, { requiredIds = [], forbiddenIds = [], sessionBase, anchorMs } = {}) {
183
+ const problems = [];
184
+ const byId = docs instanceof Map ? docs : new Map((docs || []).map((d) => [d.doc_id, d]));
185
+ if (!Array.isArray(citations) || citations.length === 0) {
186
+ problems.push('carry_forward.citations must name the later continuity records, each as {doc_id, version}');
187
+ return problems;
188
+ }
189
+ const seen = new Set();
190
+ for (const cite of citations) {
191
+ const id = cite && typeof cite.doc_id === 'string' ? cite.doc_id.trim() : '';
192
+ const version = cite && typeof cite.version === 'number' ? cite.version : null;
193
+ if (!id || !Number.isInteger(version)) {
194
+ problems.push('each citation needs a doc_id and an integer version');
195
+ continue;
196
+ }
197
+ if (forbiddenIds.includes(id)) {
198
+ problems.push(`citation ${id} is a main record this bot session does not cite`);
199
+ continue;
200
+ }
201
+ seen.add(id);
202
+ const doc = byId.get(id);
203
+ if (!doc || doc.exists === false) {
204
+ problems.push(`citation ${id} is not in the store`);
205
+ continue;
206
+ }
207
+ if (doc.version !== version) { // citation-version
208
+ problems.push(`citation ${id} says v${version}; the version in force is v${doc.version}`);
209
+ }
210
+ const wrote = writerBase(doc.session_id);
211
+ if (wrote && sessionBase && wrote === sessionBase) {
212
+ problems.push(`citation ${id} v${version} was written in this session; use a normal receipt close`);
213
+ }
214
+ const ms = toMillis(doc.updated_at);
215
+ if (anchorMs == null || ms == null || ms <= anchorMs) { // citation-later
216
+ problems.push(`citation ${id} v${version} is not later than this session`);
217
+ }
218
+ }
219
+ for (const id of requiredIds) {
220
+ if (!seen.has(id)) problems.push(`citation missing: ${id}`);
221
+ }
222
+ return problems;
223
+ }
224
+
225
+ function refused(problems, extra = {}) {
226
+ return {
227
+ state: 'refused',
228
+ speak: [
229
+ 'Carry-forward close: refused',
230
+ ...problems.map((p) => p),
231
+ 'Transcript: retained',
232
+ 'Close state: refused'
233
+ ],
234
+ missing: problems,
235
+ warnings: [],
236
+ carry_forward: { closed: false, transcripts_deleted: false, ...extra },
237
+ close_attempts: { counted: false, escalated: false },
238
+ instructions:
239
+ 'The session is NOT saved. The session graph stays open, and no transcript was deleted. ' +
240
+ 'This refusal is not a blocked close and is not counted. ' +
241
+ 'Cite the current records/ disposition and the later HANDOFF and STATE versions, ' +
242
+ 'or use a normal receipt close when this session\'s receipts still match the store.'
243
+ };
244
+ }
245
+
246
+ function anchorMillis(session, rows) {
247
+ const opened = toMillis(session && session.opened_at);
248
+ if (opened != null) return opened;
249
+ let max = null;
250
+ for (const doc of rows || []) {
251
+ const end = toMillis(doc && doc.session_end);
252
+ if (end != null && (max == null || end > max)) max = end;
253
+ for (const ex of (doc && doc.exchanges) || []) {
254
+ const t = toMillis(ex && ex.timestamp);
255
+ if (t != null && (max == null || t > max)) max = t;
256
+ }
257
+ }
258
+ return max;
259
+ }
260
+
261
+ export async function runCarryForwardClose(db, options = {}) {
262
+ const parsed = parseCarryForward(options.carry_forward);
263
+ if (parsed.problem) return refused([parsed.problem]);
264
+ const spec = parsed.value;
265
+ const requested = typeof options.session_id === 'string' ? options.session_id.trim() : '';
266
+ const base = closeBaseId(requested);
267
+ if (!base) return refused(['carry_forward requires session_id of the open session to close']);
268
+
269
+ const sessions = db.collection(`${COLLECTION_PREFIX}sessions`);
270
+ const session = await sessions.findOne({ _id: base });
271
+ if (!session || session.opened !== true) {
272
+ return refused([`session ${base} has no open session row`], { session_id: base });
273
+ }
274
+ if (session.closed === true) {
275
+ return refused([`session ${base} is already closed`], { session_id: base });
276
+ }
277
+
278
+ const loaded = await (async () => {
279
+ const { sessionTagOf } = await import('./session.js');
280
+ const pattern = `^${String(base).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(_.*)?$`;
281
+ const rows = await db.collection('transcripts').find({ session_id: { $regex: pattern } }).toArray();
282
+ return { rows, tag: sessionTagOf(rows).tag };
283
+ })();
284
+
285
+ const actor = rawActor();
286
+ let ownerId = actor && actor.ownerId;
287
+ if (actor && actor.transport === 'http' && !ownerId) {
288
+ try { ownerId = await resolveTokenSubject(db); } catch { ownerId = null; }
289
+ }
290
+ const auth = carryForwardAuthority(actor ? { ...actor, ownerId: ownerId || actor.ownerId } : null, {
291
+ sessionTag: loaded.tag,
292
+ openedBy: session.opened_by || null
293
+ });
294
+ if (!auth.ok) return refused([auth.reason], { session_id: base });
295
+
296
+ const docId = typeof spec.disposition_doc === 'string' ? spec.disposition_doc.trim() : '';
297
+ const dispositionVersion = typeof spec.disposition_version === 'number' ? spec.disposition_version : null;
298
+ if (!docId || !docId.startsWith('records/') || !Number.isInteger(dispositionVersion)) {
299
+ return refused(['carry_forward.disposition_doc must be a records/ id and disposition_version its integer version in force'], { session_id: base });
300
+ }
301
+
302
+ const covered = await readDispositionCoverage(db);
303
+ const exact = covered.get(requested) || covered.get(base);
304
+ if (!exact) {
305
+ const named = await db.collection('documents').findOne(
306
+ { doc_id: docId },
307
+ { projection: { content: 1, conformance: 1, retired: 1 } }
308
+ );
309
+ const rows = named ? parseDispositionRows(named.content) : [];
310
+ const transcriptOnly = rows.some((row) => (row.session_id === base || row.session_id === requested) && row.inserted_id);
311
+ const problems = transcriptOnly
312
+ ? [`${docId} dispositions a transcript inserted_id only. That row does not close ${base}`]
313
+ : [`no current conforming session-level disposition covers ${base}`];
314
+ if (named && named.retired === true) problems.push(`${docId} is retired`);
315
+ if (named && named.conformance && named.conformance.template && named.conformance.template !== SESSION_DISPOSITION_TEMPLATE) {
316
+ problems.push(`${docId} is not a ${SESSION_DISPOSITION_TEMPLATE} record`);
317
+ }
318
+ return refused(problems, { session_id: base });
319
+ }
320
+ if (exact.doc_id !== docId || exact.version !== dispositionVersion) { // disposition-in-force
321
+ return refused([
322
+ `the disposition in force for ${base} is ${exact.doc_id} v${exact.version} (${exact.disposition}), not ${docId} v${dispositionVersion}`
323
+ ], { session_id: base });
324
+ }
325
+ if (!CLOSABLE.has(exact.disposition)) { // closable-disposition
326
+ const why = exact.disposition === 'RETAINED_OPEN_CRITICAL'
327
+ ? `${base} is RETAINED_OPEN_CRITICAL. That row keeps the session open.`
328
+ : `${base} is ${exact.disposition}. carry_forward closes only ${CARRY_FORWARD_DISPOSITIONS.join(', ')}. Use a normal receipt close for CLOSED_NORMAL.`;
329
+ return refused([why], { session_id: base, disposition: exact.disposition });
330
+ }
331
+
332
+ const mains = mainRecordIds();
333
+ const bot = loaded.tag && isBotTag(loaded.tag);
334
+ const requiredIds = bot ? [botHandoffDoc(loaded.tag)] : mains;
335
+ const forbiddenIds = bot ? mains : [];
336
+ const citeIds = new Set(requiredIds);
337
+ for (const cite of Array.isArray(spec.citations) ? spec.citations : []) {
338
+ if (cite && typeof cite.doc_id === 'string' && cite.doc_id.trim()) citeIds.add(cite.doc_id.trim());
339
+ }
340
+ const found = new Map();
341
+ for (const id of citeIds) {
342
+ const row = await db.collection('documents').findOne(
343
+ { doc_id: id },
344
+ { projection: { doc_id: 1, version: 1, updated_at: 1, session_id: 1, retired: 1 } }
345
+ );
346
+ found.set(id, row && row.retired !== true
347
+ ? { doc_id: id, exists: true, version: row.version, updated_at: row.updated_at, session_id: row.session_id || null }
348
+ : { doc_id: id, exists: false });
349
+ }
350
+ const anchorMs = anchorMillis(session, loaded.rows);
351
+ const citeProblems = assessCitations(spec.citations, found, {
352
+ requiredIds, forbiddenIds, sessionBase: base, anchorMs
353
+ });
354
+ if (citeProblems.length) return refused(citeProblems, { session_id: base, disposition: exact.disposition });
355
+
356
+ const citations = (spec.citations || []).map((cite) => ({ doc_id: cite.doc_id.trim(), version: cite.version }));
357
+ const citedText = citations.map((c) => `${c.doc_id} v${c.version}`).join(', ');
358
+ return {
359
+ state: 'complete',
360
+ speak: [
361
+ `Carry-forward close: ${base}`,
362
+ `Authority: ${auth.basis}`,
363
+ `Disposition: ${exact.doc_id} v${exact.version} ${exact.disposition}`,
364
+ `Later continuity: ${citedText}`,
365
+ 'Transcript: retained',
366
+ 'Close state: complete'
367
+ ],
368
+ missing: [],
369
+ warnings: [],
370
+ carry_forward: {
371
+ closed: true,
372
+ authority: auth.basis,
373
+ disposition_doc: exact.doc_id,
374
+ disposition_version: exact.version,
375
+ disposition: exact.disposition,
376
+ citations,
377
+ transcripts_deleted: false,
378
+ session_id: base
379
+ },
380
+ close_attempts: { counted: false, escalated: false },
381
+ instructions:
382
+ 'Say every line of `speak` to the user, in order. ' +
383
+ 'This session is closed by carry-forward. The disposition and the later continuity versions were cited. ' +
384
+ 'The transcript was kept. This is not a receipt close. After `speak`, tell the user the session is saved, in one line.'
385
+ };
386
+ }
@@ -12,11 +12,16 @@
12
12
  * without a database. The wiring lives in tools.js (transcript append),
13
13
  * session.js (close) and setup.js (initialize).
14
14
  *
15
- * 1. machineLineCheck - the first transcript append of a session must carry
16
- * a measured machine name and a clock reading, or the
17
- * words `no local shell MCP`. Two sessions on
18
- * 2026-09-26 skipped the machine check and still got a
19
- * transcript started.
15
+ * 1. machineLineCheck - the first successful transcript append of a session
16
+ * must carry a measured machine name and a clock
17
+ * reading, or the words `no local shell MCP`. The
18
+ * check is on the append that opens the transcript,
19
+ * or that becomes the lowest stored index, whatever
20
+ * exchange_index that is. Two sessions on 2026-09-26
21
+ * skipped the machine check and still got a transcript
22
+ * started. On 2026-11-03 a refused exchange 1 was
23
+ * followed by an accepted exchange 2, because the
24
+ * door only ran when the index was 1.
20
25
  * 2. applyCloseCap - three blocked closes on one session escalate to the
21
26
  * user instead of retrying. A host looping on close
22
27
  * burns attempts; after three, the wrap plan is wrong
@@ -41,6 +46,24 @@
41
46
 
42
47
  export const NO_SHELL_PHRASE = 'no local shell MCP';
43
48
 
49
+ /**
50
+ * Whether this append is the one the machine line must ride on.
51
+ * `storedIndexes` are the exchange indexes already stored for the session.
52
+ * True when nothing is stored yet, so any index would open the transcript.
53
+ * True when `incoming` is lower than every stored index, so it becomes the
54
+ * lowest. A refused exchange 1 leaves the store empty, and a later index
55
+ * still has to pass.
56
+ */
57
+ export function machineLineRequired(storedIndexes, incoming) {
58
+ const stored = (Array.isArray(storedIndexes) ? storedIndexes : [])
59
+ .map((n) => Number(n))
60
+ .filter((n) => Number.isInteger(n) && n >= 1);
61
+ if (stored.length === 0) return true;
62
+ const n = Number(incoming);
63
+ if (!Number.isInteger(n) || n < 1) return false;
64
+ return n < Math.min(...stored);
65
+ }
66
+
44
67
  /**
45
68
  * Reads the known machine names out of the user's install notes. The notes are
46
69
  * a markdown document; the machines are the first column of any table whose
@@ -359,7 +382,7 @@ export function checkLessonFields(layer, metadata) {
359
382
  }
360
383
 
361
384
  export default {
362
- NO_SHELL_PHRASE, knownMachinesFromInstallNotes, machineLineCheck,
385
+ NO_SHELL_PHRASE, machineLineRequired, knownMachinesFromInstallNotes, machineLineCheck,
363
386
  CLOSE_CAP, applyCloseCap, scopeFor, escalateSpeak,
364
387
  LESSON_REPEAT_THRESHOLD, DISPOSITION_KINDS, pendingLessons,
365
388
  LESSON_KEY_PATTERN, suggestLessonKey, checkLessonFields
@@ -7,6 +7,9 @@
7
7
  */
8
8
 
9
9
  import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
10
13
  import express from 'express';
11
14
 
12
15
  export const SESSION_MS = 15 * 60 * 1000;
@@ -14,6 +17,27 @@ export const COOKIE_NAME = 'emet_owner';
14
17
  const SESSION_MAX = 200;
15
18
  const NEXT_OK = new Set(['/owner/chooser', '/owner/break-glass']);
16
19
 
20
+ /** Full-resolution README hero. The README tag uses the 560px derivative of this file. */
21
+ export const OWNER_GRAPHIC_PATH = '/owner/assets/portrait.webp';
22
+ const OWNER_GRAPHIC_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'site', 'assets', 'portrait.webp');
23
+
24
+ /**
25
+ * The deploy image copies this file. The npm package does not.
26
+ * A missing file leaves the page without a portrait. It does not stop startup.
27
+ */
28
+ function readOwnerGraphic() {
29
+ try {
30
+ return fs.readFileSync(OWNER_GRAPHIC_FILE);
31
+ } catch (err) {
32
+ if (err && err.code === 'ENOENT') return null;
33
+ throw err;
34
+ }
35
+ }
36
+
37
+ const OWNER_GRAPHIC_BYTES = readOwnerGraphic();
38
+
39
+ export const OWNER_PAGE_CSP = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";
40
+
17
41
  export function esc(s) {
18
42
  return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
19
43
  }
@@ -30,6 +54,16 @@ export function readCookie(req, name) {
30
54
  return null;
31
55
  }
32
56
 
57
+ /**
58
+ * The portrait is the page background. The sheet is a scrim: 0.86 of #12141a
59
+ * still clears WCAG AA for the text colors below when a pixel of the portrait
60
+ * is white. Text fields and buttons use an opaque light face.
61
+ */
62
+ function bodyBackground() {
63
+ if (!OWNER_GRAPHIC_BYTES) return 'background-color: #12141a;';
64
+ return `background-color: #12141a; background-image: url("${OWNER_GRAPHIC_PATH}"); background-repeat: no-repeat; background-position: center; background-size: cover;`;
65
+ }
66
+
33
67
  export function htmlPage(title, body) {
34
68
  return `<!DOCTYPE html>
35
69
  <html lang="en">
@@ -38,10 +72,13 @@ export function htmlPage(title, body) {
38
72
  <meta name="viewport" content="width=device-width, initial-scale=1">
39
73
  <title>${esc(title)}</title>
40
74
  <style>
41
- body { font-family: system-ui, sans-serif; background: #12141a; color: #e8e6e0; margin: 0; padding: 24px; line-height: 1.45; }
75
+ body { font-family: system-ui, sans-serif; color: #e8e6e0; margin: 0; min-height: 100vh; line-height: 1.45; ${bodyBackground()} }
76
+ .sheet { box-sizing: border-box; max-width: 52rem; margin: 24px; padding: 20px 22px; background: rgba(18, 20, 26, 0.86); border-radius: 12px; }
42
77
  a { color: #8eb4d6; }
43
78
  button, input, select { font: inherit; }
79
+ button, input[type="text"], input[type="password"], select { color: #12141a; background-color: #f4f5f7; border: 1px solid #3d4450; padding: 4px 8px; }
44
80
  button { margin-right: 8px; }
81
+ input::placeholder { color: #3d4450; }
45
82
  table { border-collapse: collapse; }
46
83
  td, th { text-align: left; padding: 4px 10px 4px 0; vertical-align: top; }
47
84
  code { color: #d9c27a; }
@@ -49,7 +86,9 @@ export function htmlPage(title, body) {
49
86
  </style>
50
87
  </head>
51
88
  <body>
89
+ <div class="sheet">
52
90
  ${body}
91
+ </div>
53
92
  </body>
54
93
  </html>`;
55
94
  }
@@ -58,7 +97,7 @@ export function sendHtml(res, status, body, title = 'EMET') {
58
97
  res.status(status);
59
98
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
60
99
  res.setHeader('Cache-Control', 'no-store');
61
- res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
100
+ res.setHeader('Content-Security-Policy', OWNER_PAGE_CSP);
62
101
  res.send(htmlPage(title, body));
63
102
  }
64
103
 
@@ -156,7 +195,29 @@ export function createOwnerGate({ checkPassphrase, throttle, now = Date.now } =
156
195
  return { sessionOf, login, now, endOtherSessions };
157
196
  }
158
197
 
198
+ export function mountOwnerGraphic(app) {
199
+ if (!app || app.get('emetOwnerGraphic')) return;
200
+ app.set('emetOwnerGraphic', true);
201
+ app.get(OWNER_GRAPHIC_PATH, (_req, res) => {
202
+ if (!OWNER_GRAPHIC_BYTES) {
203
+ res.status(404);
204
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
205
+ res.setHeader('Cache-Control', 'no-store');
206
+ res.setHeader('X-Content-Type-Options', 'nosniff');
207
+ res.end('Not found');
208
+ return;
209
+ }
210
+ res.status(200);
211
+ res.setHeader('Content-Type', 'image/webp');
212
+ res.setHeader('Content-Length', String(OWNER_GRAPHIC_BYTES.length));
213
+ res.setHeader('Cache-Control', 'public, max-age=86400');
214
+ res.setHeader('X-Content-Type-Options', 'nosniff');
215
+ res.end(OWNER_GRAPHIC_BYTES);
216
+ });
217
+ }
218
+
159
219
  export function mountOwnerLogin(app, gate) {
220
+ mountOwnerGraphic(app);
160
221
  if (app.get('emetOwnerLogin')) return;
161
222
  app.set('emetOwnerLogin', true);
162
223
  app.post('/owner/login', express.urlencoded({ extended: false }), (req, res) => gate.login(req, res));