@dreamforgestudiollc/emet 0.3.1 → 0.3.2

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 (71) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +29 -6
  3. package/docs/BOOTSTRAP.md +2 -0
  4. package/docs/BOTS.md +8 -7
  5. package/docs/DEPLOY.md +6 -0
  6. package/docs/ERROR-CODES-SPEC.md +2 -2
  7. package/docs/ERROR-CODES.md +29 -0
  8. package/docs/GUIDED-SETUP.md +1 -1
  9. package/docs/PERMISSIONS.md +5 -5
  10. package/docs/SETUP.md +10 -4
  11. package/docs/SUBKEYS.md +4 -4
  12. package/package.json +2 -2
  13. package/server.json +8 -4
  14. package/src/aleph.js +34 -13
  15. package/src/annotations.js +6 -2
  16. package/src/approve-throttle.js +3 -0
  17. package/src/atlas-role.js +1 -1
  18. package/src/attribution.js +76 -28
  19. package/src/bound-door.js +170 -0
  20. package/src/break-glass.js +531 -0
  21. package/src/checkpoint.js +241 -0
  22. package/src/chooser.js +543 -0
  23. package/src/claimed-tag.js +140 -0
  24. package/src/conformance.js +269 -5
  25. package/src/deep-links.js +267 -0
  26. package/src/dispatch.js +112 -18
  27. package/src/error-codes.js +29 -0
  28. package/src/error-log.js +138 -26
  29. package/src/error-report.js +17 -5
  30. package/src/gaps.js +1 -1
  31. package/src/grants.js +230 -0
  32. package/src/http-remote.js +80 -26
  33. package/src/index.js +18 -2
  34. package/src/invites.js +47 -1
  35. package/src/layers.js +1 -1
  36. package/src/lessons-to-checks.js +1 -1
  37. package/src/logger.js +3 -1
  38. package/src/oauth-provider.js +89 -5
  39. package/src/owl.js +232 -0
  40. package/src/owner-approvals.js +24 -267
  41. package/src/owner-session.js +174 -0
  42. package/src/pages.js +1 -1
  43. package/src/persons.js +39 -6
  44. package/src/proof-run.js +70 -0
  45. package/src/redact.js +4 -0
  46. package/src/request-log.js +2 -2
  47. package/src/rotate.js +554 -0
  48. package/src/rune-dispatch.js +1 -1
  49. package/src/session-graph.js +44 -25
  50. package/src/session.js +3 -3
  51. package/src/setup.js +21 -12
  52. package/src/staged-write.js +522 -0
  53. package/src/startup-pages.js +2 -2
  54. package/src/startup-payload.js +3 -3
  55. package/src/subkeys.js +61 -0
  56. package/src/tools.js +270 -78
  57. package/src/transcript-session.js +23 -4
  58. package/src/validation.js +1 -1
  59. package/src/version.js +1 -1
  60. package/src/writer-approval.js +394 -0
  61. package/templates/AREA.md +1 -1
  62. package/templates/BOTHANDOFF.md +2 -2
  63. package/templates/GRANT.md +48 -0
  64. package/templates/INDEX.md +9 -7
  65. package/templates/PROCEDURE.md +1 -1
  66. package/templates/ROSTER.md +2 -2
  67. package/templates/SEED.md +2 -2
  68. package/templates/SESSIONDISPOSITION.md +59 -0
  69. package/templates/STAGING.md +1 -1
  70. package/templates/STANDARD.md +1 -1
  71. package/templates/THREAD.md +1 -1
@@ -259,7 +259,8 @@ export function baseMap() {
259
259
  'threads/': 'templates/THREAD.md',
260
260
  'staging/': 'templates/STAGING.md',
261
261
  'procedures/': 'templates/PROCEDURE.md',
262
- 'areas/': 'templates/AREA.md'
262
+ 'areas/': 'templates/AREA.md',
263
+ [SESSION_DISPOSITION_PREFIX]: SESSION_DISPOSITION_TEMPLATE
263
264
  }
264
265
  };
265
266
  }
@@ -371,7 +372,7 @@ function idCell(row, idIndex) {
371
372
  * a closed row named in a note, an item cross-referenced in a next action -
372
373
  * read as a row of its own, so the carry-forward check reported it missing
373
374
  * from the next revision. Found by running the validator against the reference
374
- * install's own board, 2026-09-11: board 12 and board 50 were both closed on the
375
+ * install's own board, 2026-09-11: board 012 and board 050 were both closed on the
375
376
  * prior revision and appeared only inside another row's text.
376
377
  *
377
378
  * The failure direction matters and is recorded so no one "fixes" this by
@@ -401,6 +402,261 @@ function idColumnIndex(body) {
401
402
  return i === -1 ? null : i;
402
403
  }
403
404
 
405
+ /**
406
+ * Session disposition (templates/SESSIONDISPOSITION.md).
407
+ * A batch under records/ notes overdue or duplicate sessions. It does not close
408
+ * them and it does not write a receipt. An inserted_id row dispositions that
409
+ * transcript and leaves the transcript in the store. A session-level row
410
+ * (no inserted_id) is what checkpoint overdue listing reads.
411
+ */
412
+ export const SESSION_DISPOSITION_TEMPLATE = 'templates/SESSIONDISPOSITION.md';
413
+ export const SESSION_DISPOSITION_PREFIX = 'records/';
414
+ export const SESSION_DISPOSITIONS = Object.freeze([
415
+ 'CARRIED_FORWARD',
416
+ 'ABANDONED_NO_TRANSCRIPT',
417
+ 'SUPERSEDED_BY_LATER_SESSION',
418
+ 'CLOSED_NORMAL',
419
+ 'RETAINED_OPEN_CRITICAL'
420
+ ]);
421
+ const SESSION_DISPOSITION_SET = new Set(SESSION_DISPOSITIONS);
422
+ const NEEDS_DESTINATION = new Set(['CARRIED_FORWARD', 'SUPERSEDED_BY_LATER_SESSION']);
423
+ const INSERTED_ID_RE = /^[a-f0-9]{24}$/i;
424
+
425
+ export function dispositionResolvesOverdue(name) {
426
+ return SESSION_DISPOSITION_SET.has(name);
427
+ }
428
+
429
+ function markdownTable(body) {
430
+ const lines = String(body || '').split('\n').map((l) => l.trim());
431
+ let header = null;
432
+ let seenRule = false;
433
+ const rows = [];
434
+ for (const line of lines) {
435
+ if (!line.startsWith('|')) {
436
+ if (seenRule && rows.length) break;
437
+ continue;
438
+ }
439
+ if (!header) { header = cells(line); continue; }
440
+ if (!seenRule) { seenRule = /^\|[\s:|-]+\|$/.test(line); continue; }
441
+ rows.push(cells(line));
442
+ }
443
+ return { header: header || [], rows };
444
+ }
445
+
446
+ function columnIndex(header, ...names) {
447
+ const norm = (header || []).map((h) => String(h || '').toLowerCase().replace(/[\s-]+/g, '_'));
448
+ for (const name of names) {
449
+ const i = norm.indexOf(name);
450
+ if (i !== -1) return i;
451
+ }
452
+ return -1;
453
+ }
454
+
455
+ function cellAt(row, index) {
456
+ if (index == null || index < 0) return '';
457
+ return String((row && row[index]) || '').trim();
458
+ }
459
+
460
+ function unanswered(value, label) {
461
+ const v = String(value ?? '').trim();
462
+ if (!v || /^_{2,}$/.test(v)) return `${label} is blank`;
463
+ if (/^(none|n\/a)$/i.test(v)) return `${label} is an unscoped none`;
464
+ if (/^(none|n\/a)\b/i.test(v) && !/^(?:none|n\/a)\s*[—–-]\s*\S/i.test(v)) return `${label} is an unscoped none`;
465
+ return null;
466
+ }
467
+
468
+ function isScopedNone(value) {
469
+ return /^(?:none|n\/a)\b/i.test(String(value ?? '').trim());
470
+ }
471
+
472
+ function controlValue(body, label) {
473
+ const re = new RegExp(`${String(label).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*:\\s*([^·\\n]+)`, 'i');
474
+ const m = re.exec(String(body || ''));
475
+ return m ? m[1].trim() : null;
476
+ }
477
+
478
+ /** A real transcript id, or null when the cell is empty or a scoped none. */
479
+ export function realInsertedId(value) {
480
+ const v = String(value ?? '').trim();
481
+ if (!v || isScopedNone(v)) return null;
482
+ return INSERTED_ID_RE.test(v) ? v.toLowerCase() : v;
483
+ }
484
+
485
+ function dispositionKey(sessionId, insertedId) {
486
+ return `${sessionId}\0${insertedId || ''}`;
487
+ }
488
+
489
+ function indexDispositionColumns(header) {
490
+ return {
491
+ session_id: columnIndex(header, 'session_id'),
492
+ opened_at: columnIndex(header, 'opened_at'),
493
+ last_saved_at: columnIndex(header, 'last_saved_at'),
494
+ disposition: columnIndex(header, 'disposition'),
495
+ reason: columnIndex(header, 'reason'),
496
+ evidence: columnIndex(header, 'evidence'),
497
+ carried_forward_to: columnIndex(header, 'carried_forward_to'),
498
+ inserted_id: columnIndex(header, 'inserted_id')
499
+ };
500
+ }
501
+
502
+ /**
503
+ * §1 rows. `inserted_id` is the 24-hex id, or null when the row is session-level.
504
+ * A row that fails form still parses, so a reader can see what was written.
505
+ */
506
+ export function parseDispositionRows(content) {
507
+ const one = parseSections(content).find((s) => s.num === '1');
508
+ if (!one) return [];
509
+ const table = markdownTable(one.body);
510
+ const idx = indexDispositionColumns(table.header);
511
+ if (idx.session_id < 0) return [];
512
+ const out = [];
513
+ for (const raw of table.rows) {
514
+ const session_id = cellAt(raw, idx.session_id);
515
+ if (!session_id) continue;
516
+ out.push({
517
+ session_id,
518
+ opened_at: cellAt(raw, idx.opened_at),
519
+ last_saved_at: cellAt(raw, idx.last_saved_at),
520
+ disposition: cellAt(raw, idx.disposition),
521
+ reason: cellAt(raw, idx.reason),
522
+ evidence: cellAt(raw, idx.evidence),
523
+ carried_forward_to: cellAt(raw, idx.carried_forward_to),
524
+ inserted_id: realInsertedId(cellAt(raw, idx.inserted_id))
525
+ });
526
+ }
527
+ return out;
528
+ }
529
+
530
+ function dispositionSubjects(content) {
531
+ return parseDispositionRows(content).map((row) => ({
532
+ key: dispositionKey(row.session_id, row.inserted_id),
533
+ session_id: row.session_id,
534
+ inserted_id: row.inserted_id
535
+ }));
536
+ }
537
+
538
+ /**
539
+ * Form checks for a session-disposition record. The write path calls this
540
+ * from checkRecord. It checks form, not whether the disposition is true.
541
+ */
542
+ export function checkDispositionRecord(content, { previous = null } = {}) {
543
+ const failures = [];
544
+ const sections = parseSections(content);
545
+ const byNum = new Map(sections.map((s) => [s.num, s]));
546
+ const zero = byNum.get('0');
547
+ if (zero) {
548
+ for (const label of ['Session id', 'Source tag', 'Written (local)', 'Scope', 'Rows']) {
549
+ const problem = unanswered(controlValue(zero.body, label), label);
550
+ if (problem) failures.push(`record control ${problem}`);
551
+ }
552
+ const declared = controlValue(zero.body, 'Rows');
553
+ const stated = declared == null ? NaN : Number(String(declared).replace(/[^0-9-]/g, ''));
554
+ const one = byNum.get('1');
555
+ const table = one ? markdownTable(one.body) : { header: [], rows: [] };
556
+ if (Number.isFinite(stated) && one && stated !== table.rows.length) {
557
+ failures.push(`§0 states Rows ${stated}; §1 holds ${table.rows.length} row${table.rows.length === 1 ? '' : 's'}`);
558
+ }
559
+ }
560
+
561
+ const one = byNum.get('1');
562
+ if (one) {
563
+ if (/no session in this record/i.test(one.body) && markdownTable(one.body).rows.length > 0) {
564
+ failures.push('§1 says no session in this record and also holds rows');
565
+ }
566
+ const table = markdownTable(one.body);
567
+ if (table.rows.length === 0) {
568
+ if (!/None\s*[—–-]\s*\S/i.test(one.body)) {
569
+ failures.push('§1 names no session and states no scoped none');
570
+ }
571
+ } else {
572
+ const idx = indexDispositionColumns(table.header);
573
+ const required = ['session_id', 'opened_at', 'last_saved_at', 'disposition', 'reason', 'evidence', 'carried_forward_to', 'inserted_id'];
574
+ for (const name of required) {
575
+ if (idx[name] < 0) failures.push(`§1 table has no ${name} column`);
576
+ }
577
+ if (required.every((name) => idx[name] >= 0)) {
578
+ const seen = new Map();
579
+ table.rows.forEach((raw, n) => {
580
+ const at = `§1 row ${n + 1}`;
581
+ const session_id = cellAt(raw, idx.session_id);
582
+ const opened_at = cellAt(raw, idx.opened_at);
583
+ const last_saved_at = cellAt(raw, idx.last_saved_at);
584
+ const disposition = cellAt(raw, idx.disposition);
585
+ const reason = cellAt(raw, idx.reason);
586
+ const evidence = cellAt(raw, idx.evidence);
587
+ const carried = cellAt(raw, idx.carried_forward_to);
588
+ const insertedRaw = cellAt(raw, idx.inserted_id);
589
+ const inserted = realInsertedId(insertedRaw);
590
+ if (!session_id || isScopedNone(session_id)) failures.push(`${at} session_id is not a session id`);
591
+ for (const [label, value] of [['opened_at', opened_at], ['last_saved_at', last_saved_at], ['carried_forward_to', carried], ['inserted_id', insertedRaw]]) {
592
+ const problem = unanswered(value, label);
593
+ if (problem) failures.push(`${at} ${problem}`);
594
+ }
595
+ if (!SESSION_DISPOSITION_SET.has(disposition)) {
596
+ failures.push(`${at} disposition "${disposition}" is not one of ${SESSION_DISPOSITIONS.join(', ')}`);
597
+ }
598
+ if (reason.trim().length < MIN_ACCEPTANCE_REASON) {
599
+ failures.push(`${at} reason is shorter than ${MIN_ACCEPTANCE_REASON} characters`);
600
+ }
601
+ if (isScopedNone(evidence) || evidence.trim().length < MIN_ACCEPTANCE_REASON) {
602
+ failures.push(`${at} evidence must name a record, revision, inserted id, or dated words (at least ${MIN_ACCEPTANCE_REASON} characters)`);
603
+ }
604
+ if (NEEDS_DESTINATION.has(disposition) && isScopedNone(carried)) {
605
+ failures.push(`${at} ${disposition} must name carried_forward_to`);
606
+ }
607
+ if (insertedRaw && !isScopedNone(insertedRaw) && !INSERTED_ID_RE.test(insertedRaw)) {
608
+ failures.push(`${at} inserted_id is not a 24-hex transcript id or a scoped none`);
609
+ }
610
+ if (inserted) {
611
+ if (disposition !== 'SUPERSEDED_BY_LATER_SESSION') {
612
+ failures.push(`${at} an inserted_id row uses SUPERSEDED_BY_LATER_SESSION`);
613
+ }
614
+ if (!evidence.includes(inserted)) failures.push(`${at} evidence does not name inserted_id ${inserted}`);
615
+ }
616
+ const key = dispositionKey(session_id, inserted);
617
+ if (session_id && seen.has(key)) failures.push(`${at} repeats ${session_id}${inserted ? ` inserted_id ${inserted}` : ''}`);
618
+ if (session_id) seen.set(key, n + 1);
619
+ });
620
+ }
621
+ }
622
+ }
623
+
624
+ const three = byNum.get('3');
625
+ if (three && previous && typeof previous === 'string') {
626
+ const before = dispositionSubjects(previous);
627
+ const after = new Set(dispositionSubjects(content).map((s) => s.key));
628
+ const released = new Set();
629
+ const release = markdownTable(three.body);
630
+ const idCol = columnIndex(release.header, 'session_id');
631
+ const insCol = columnIndex(release.header, 'inserted_id');
632
+ const whyCol = columnIndex(release.header, 'why_it_left', 'why');
633
+ const evCol = columnIndex(release.header, 'evidence');
634
+ if (release.rows.length && (idCol < 0 || whyCol < 0 || evCol < 0)) {
635
+ failures.push('§3 table needs session_id, why it left, and evidence');
636
+ }
637
+ release.rows.forEach((raw, n) => {
638
+ const session_id = cellAt(raw, idCol);
639
+ const inserted = realInsertedId(cellAt(raw, insCol));
640
+ const why = cellAt(raw, whyCol);
641
+ const evidence = cellAt(raw, evCol);
642
+ if (!session_id) failures.push(`§3 row ${n + 1} session_id is blank`);
643
+ if (why.trim().length < MIN_ACCEPTANCE_REASON) failures.push(`§3 row ${n + 1} why it left is shorter than ${MIN_ACCEPTANCE_REASON} characters`);
644
+ if (evidence.trim().length < MIN_ACCEPTANCE_REASON) failures.push(`§3 row ${n + 1} evidence is shorter than ${MIN_ACCEPTANCE_REASON} characters`);
645
+ const key = dispositionKey(session_id, inserted);
646
+ if (after.has(key)) failures.push(`§3 releases ${session_id} that §1 still holds`);
647
+ released.add(key);
648
+ });
649
+ const dropped = before.filter((s) => !after.has(s.key) && !released.has(s.key));
650
+ if (dropped.length) {
651
+ const names = dropped.map((s) => s.inserted_id ? `${s.session_id}#${s.inserted_id}` : s.session_id);
652
+ failures.push(
653
+ `${dropped.length} subject${dropped.length === 1 ? '' : 's'} on the previous revision left this one with no disposition: ${names.sort().join(', ')}`
654
+ );
655
+ }
656
+ }
657
+ return failures;
658
+ }
659
+
404
660
  /** Data rows of the first markdown table in a section body. */
405
661
  function tableRows(body) {
406
662
  const lines = String(body || '').split('\n').map((l) => l.trim());
@@ -526,6 +782,12 @@ export function checkRecord(content, template, { previous = null, doc_id = null
526
782
  }
527
783
  }
528
784
 
785
+ // Session disposition. A records/ batch is checked for its own columns.
786
+ // Board carry-forward above looks for B-### ids and does not see session ids.
787
+ if (template && template.template_id === SESSION_DISPOSITION_TEMPLATE) {
788
+ failures.push(...checkDispositionRecord(text, { previous }));
789
+ }
790
+
529
791
  return { failures, warnings };
530
792
  }
531
793
 
@@ -651,7 +913,7 @@ export function validateDocument(doc_id, content, previous = null, { dir } = {})
651
913
 
652
914
  export const MIN_ACCEPTANCE_REASON = 10;
653
915
 
654
- export function buildAcceptance({ reason, by = null, version = null, person_id = null, client_id = null, session_id = null }) {
916
+ export function buildAcceptance({ reason, by = null, version = null, person_id = null, client_id = null, grant_id = null, door = null, session_id = null }) {
655
917
  const text = String(reason || '').trim();
656
918
  if (text.length < MIN_ACCEPTANCE_REASON) {
657
919
  throw new CodedError(
@@ -661,7 +923,7 @@ export function buildAcceptance({ reason, by = null, version = null, person_id =
661
923
  }
662
924
  return {
663
925
  reason: text, accepted_by: by, accepted_at: new Date().toISOString(), covers_version: version,
664
- person_id, client_id: client_id || 'stdio', session_id
926
+ person_id, client_id: client_id || 'stdio', grant_id: grant_id || null, door: door || null, session_id
665
927
  };
666
928
  }
667
929
 
@@ -686,5 +948,7 @@ export default {
686
948
  parseSections, parseTemplate, countPlaceholders,
687
949
  baseMap, extraMappings, templateFor, isGovernedByShippedCopy,
688
950
  loadShipped, clearShippedCache, checkRecord, validateDocument,
689
- buildAcceptance, isOpenNonconformance, isAcceptedNonconformance
951
+ buildAcceptance, isOpenNonconformance, isAcceptedNonconformance,
952
+ SESSION_DISPOSITION_TEMPLATE, SESSION_DISPOSITION_PREFIX, SESSION_DISPOSITIONS,
953
+ dispositionResolvesOverdue, parseDispositionRows, checkDispositionRecord
690
954
  };
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Refusal deep links (R4).
3
+ *
4
+ * A refused write can hand the human a URL. The URL is a server-generated
5
+ * token stored only as a hash. It is short-lived, single-use, and bound to
6
+ * this process instance plus the client grant (or `unknown`), the claimed
7
+ * tag, and the door the refusal was about. Opening it does not grant a door.
8
+ * The owner still decides on /owner/chooser.
9
+ *
10
+ * The proposed lifetime is 15 minutes (DEEP_LINK.ttl_ms). the owner can set
11
+ * EMET_DEEP_LINK_TTL_MINUTES from 1 to 60. A value outside that range does
12
+ * not lengthen the link.
13
+ */
14
+
15
+ import crypto from 'node:crypto';
16
+ import { setting } from './env.js';
17
+ import { DEEP_LINK, logGrantId } from './grants.js';
18
+
19
+ export const CHOOSER_KINDS = Object.freeze([
20
+ 'deny',
21
+ 'rename_pending',
22
+ 'onboarding_required',
23
+ 'claimed_tag'
24
+ ]);
25
+
26
+ const DOORS = new Set(['owner', 'member', 'guest']);
27
+ const TAG_MAX = 80;
28
+ const TOKEN_MAX = 128;
29
+
30
+ let instanceId = crypto.randomBytes(16).toString('hex');
31
+ let publicUrl = '';
32
+ const links = new Map();
33
+ const decisions = [];
34
+ let breakGlassUses = 0;
35
+ let breakGlassLastAt = null;
36
+
37
+ export function currentInstanceId() {
38
+ return instanceId;
39
+ }
40
+
41
+ export function setInstanceIdForTests(id) {
42
+ instanceId = typeof id === 'string' && id.trim() ? id.trim() : crypto.randomBytes(16).toString('hex');
43
+ }
44
+
45
+ export function setChooserPublicUrl(url) {
46
+ publicUrl = typeof url === 'string' ? url.replace(/\/+$/, '') : '';
47
+ }
48
+
49
+ export function deepLinkTtlMs() {
50
+ const raw = setting('DEEP_LINK_TTL_MINUTES');
51
+ const text = typeof raw === 'string' ? raw.trim() : '';
52
+ if (/^\d+$/.test(text)) {
53
+ const minutes = Number(text);
54
+ if (minutes >= 1 && minutes <= 60) return minutes * 60 * 1000;
55
+ }
56
+ return DEEP_LINK.ttl_ms;
57
+ }
58
+
59
+ export function bindGrantId(id) {
60
+ if (id === 'unknown') return 'unknown';
61
+ const logged = logGrantId(id);
62
+ return logged === 'none' ? 'unknown' : logged;
63
+ }
64
+
65
+ export function bindTag(tag) {
66
+ if (typeof tag !== 'string') return 'unknown';
67
+ const text = tag.trim().slice(0, TAG_MAX);
68
+ return text || 'unknown';
69
+ }
70
+
71
+ export function bindDoor(door) {
72
+ return DOORS.has(door) ? door : 'guest';
73
+ }
74
+
75
+ export function bindCorrelation(id) {
76
+ return typeof id === 'string' && /^[0-9a-f]{16}$/.test(id) ? id : 'none';
77
+ }
78
+
79
+ /** The binding a refusal carries. Null when the kind is not one of the four. */
80
+ export function chooserBinding({ kind, grantId, tag, door } = {}) {
81
+ if (!CHOOSER_KINDS.includes(kind)) return null;
82
+ return {
83
+ kind,
84
+ grant_id: bindGrantId(grantId),
85
+ tag: bindTag(tag),
86
+ door: bindDoor(door)
87
+ };
88
+ }
89
+
90
+ function hashToken(token) {
91
+ return crypto.createHash('sha256').update(String(token)).digest('hex');
92
+ }
93
+
94
+ /**
95
+ * Mint a link. The raw token is returned once, for the refusal payload.
96
+ * The store keeps the hash.
97
+ */
98
+ export function mintDeepLink({ kind, grant_id, tag, door, correlationId, now = Date.now(), ttlMs, instanceId: boundInstance } = {}) {
99
+ if (!CHOOSER_KINDS.includes(kind)) return null;
100
+ const token = crypto.randomBytes(32).toString('base64url');
101
+ const hash = hashToken(token);
102
+ const ttl = Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : deepLinkTtlMs();
103
+ links.set(hash, {
104
+ hash,
105
+ instance_id: typeof boundInstance === 'string' && boundInstance ? boundInstance : instanceId,
106
+ grant_id: bindGrantId(grant_id),
107
+ tag: bindTag(tag),
108
+ door: bindDoor(door),
109
+ kind,
110
+ correlation_id: bindCorrelation(correlationId),
111
+ created_at: now,
112
+ expires_at: now + ttl,
113
+ used_at: null
114
+ });
115
+ const base = publicUrl || '';
116
+ return { url: `${base}/owner/chooser?d=${token}`, token };
117
+ }
118
+
119
+ function publicBinding(row) {
120
+ return {
121
+ grant_id: row.grant_id,
122
+ tag: row.tag,
123
+ door: row.door,
124
+ kind: row.kind,
125
+ correlation_id: row.correlation_id,
126
+ instance_id: row.instance_id,
127
+ link_id: row.hash.slice(0, 12)
128
+ };
129
+ }
130
+
131
+ /**
132
+ * First use consumes the link. A second use is a replay. A different
133
+ * instance does not consume it. A different grant, tag, or door on this
134
+ * instance consumes it and is refused.
135
+ */
136
+ export function presentDeepLink(token, claimed = {}, now = Date.now()) {
137
+ if (typeof token !== 'string' || token.length < 16 || token.length > TOKEN_MAX) {
138
+ return { ok: false, reason: 'unknown' };
139
+ }
140
+ const row = links.get(hashToken(token));
141
+ if (!row) return { ok: false, reason: 'unknown' };
142
+ const instance = claimed.instanceId || instanceId;
143
+ if (row.instance_id !== instance) return { ok: false, reason: 'wrong_instance' };
144
+ if (row.revoked_by) return { ok: false, reason: 'rotated' };
145
+ if (row.expires_at <= now) return { ok: false, reason: 'expired' };
146
+ if (row.used_at) return { ok: false, reason: 'replay' };
147
+ const scopeMismatch = (claimed.grantId != null && bindGrantId(claimed.grantId) !== row.grant_id)
148
+ || (claimed.tag != null && bindTag(claimed.tag) !== row.tag)
149
+ || (claimed.door != null && bindDoor(claimed.door) !== row.door);
150
+ if (scopeMismatch) {
151
+ row.used_at = now;
152
+ return { ok: false, reason: 'wrong_scope' };
153
+ }
154
+ row.used_at = now;
155
+ return { ok: true, binding: publicBinding(row) };
156
+ }
157
+
158
+ /** True when the raw token was stored. It must not be. */
159
+ export function deepLinkContainsRaw(token) {
160
+ const raw = String(token || '');
161
+ if (!raw) return false;
162
+ for (const row of links.values()) {
163
+ if (JSON.stringify(row).includes(raw)) return true;
164
+ }
165
+ return false;
166
+ }
167
+
168
+ /**
169
+ * Put the link on a refusal envelope. The plain reason stays. The URL is
170
+ * chooser_url, and it is appended to the message when that still fits the
171
+ * 500-character cap. The link is not written onto the Error object.
172
+ */
173
+ export function attachChooserLink(errorResponse, error, correlationId) {
174
+ const binding = error && error.chooser;
175
+ if (!binding || !errorResponse || !errorResponse.error) return errorResponse;
176
+ let minted = null;
177
+ try {
178
+ minted = mintDeepLink({ ...binding, correlationId });
179
+ } catch {
180
+ return errorResponse;
181
+ }
182
+ if (!minted) return errorResponse;
183
+ errorResponse.error.chooser_url = minted.url;
184
+ const reason = typeof errorResponse.error.message === 'string' ? errorResponse.error.message : '';
185
+ const extra = ` Open ${minted.url} The link grants nothing. The owner decides. correlation_id: ${correlationId}`;
186
+ if ((reason + extra).length <= 500) errorResponse.error.message = reason + extra;
187
+ return errorResponse;
188
+ }
189
+
190
+ export function recordAccessDecision(entry) {
191
+ const row = {
192
+ at: entry && entry.at ? entry.at : new Date().toISOString(),
193
+ grant_id: bindGrantId(entry && entry.grant_id),
194
+ correlation_id: bindCorrelation(entry && entry.correlation_id),
195
+ decider: typeof entry?.decider === 'string' && entry.decider.trim() ? entry.decider.trim().slice(0, 80) : 'owner',
196
+ decision: typeof entry?.decision === 'string' ? entry.decision.slice(0, 40) : 'none',
197
+ surface: entry && entry.surface === 'break_glass' ? 'break_glass' : 'chooser',
198
+ door: entry && entry.door ? bindDoor(entry.door) : null,
199
+ tag: entry && entry.tag ? bindTag(entry.tag) : 'unknown',
200
+ kind: entry && entry.kind ? String(entry.kind).slice(0, 40) : null,
201
+ issued: entry && entry.issued === true
202
+ };
203
+ decisions.push(row);
204
+ if (decisions.length > 500) decisions.shift();
205
+ return row;
206
+ }
207
+
208
+ export function accessDecisions() {
209
+ return decisions.map((row) => ({ ...row }));
210
+ }
211
+
212
+ export function noteBreakGlassUse(action, fields = {}) {
213
+ breakGlassUses += 1;
214
+ breakGlassLastAt = new Date().toISOString();
215
+ const grant = bindGrantId(fields.grant_id);
216
+ const decider = typeof fields.decider === 'string' && fields.decider.trim() ? fields.decider.trim().slice(0, 80) : 'owner';
217
+ const safeAction = String(action || 'use').replace(/[^a-z_]/g, '').slice(0, 40) || 'use';
218
+ const line = `[emet] break-glass action=${safeAction} decider=${decider} grant_id=${grant} uses=${breakGlassUses}`;
219
+ console.error(line);
220
+ return line;
221
+ }
222
+
223
+ export function breakGlassMetric() {
224
+ return {
225
+ path: '/owner/break-glass',
226
+ uses: breakGlassUses,
227
+ last_at: breakGlassLastAt,
228
+ since_process_start: true,
229
+ rung: 'R4'
230
+ };
231
+ }
232
+
233
+ export function breakGlassStartupLine() {
234
+ return `[emet] break-glass path=/owner/break-glass rung=R4 uses=${breakGlassUses}`;
235
+ }
236
+
237
+ /**
238
+ * Unused deep links die with a rotation. The row stays in this process so
239
+ * the refusal can name rotation instead of waiting out the TTL. all: true
240
+ * is household. Otherwise a tag or a grant id selects one member.
241
+ */
242
+ export function retireUnusedDeepLinks(eventId, filter = {}, now = Date.now()) {
243
+ let n = 0;
244
+ const grants = filter.grantIds ? new Set(filter.grantIds) : null;
245
+ for (const row of links.values()) {
246
+ if (!row || row.used_at || row.revoked_by) continue;
247
+ if (!filter.all) {
248
+ const tagHit = filter.tag && row.tag === filter.tag;
249
+ const grantHit = grants && grants.has(row.grant_id);
250
+ if (!tagHit && !grantHit) continue;
251
+ }
252
+ row.revoked_by = eventId;
253
+ row.revoked_at = now;
254
+ row.retired = true;
255
+ n += 1;
256
+ }
257
+ return n;
258
+ }
259
+
260
+ export function _resetDeepLinksForTests() {
261
+ links.clear();
262
+ decisions.length = 0;
263
+ breakGlassUses = 0;
264
+ breakGlassLastAt = null;
265
+ instanceId = crypto.randomBytes(16).toString('hex');
266
+ publicUrl = '';
267
+ }