@dreamforgestudiollc/emet 0.3.1 → 0.3.3

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 (72) hide show
  1. package/CHANGELOG.md +40 -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/carry-forward-close.js +386 -0
  22. package/src/checkpoint.js +241 -0
  23. package/src/chooser.js +543 -0
  24. package/src/claimed-tag.js +140 -0
  25. package/src/conformance.js +269 -5
  26. package/src/deep-links.js +267 -0
  27. package/src/dispatch.js +112 -18
  28. package/src/error-codes.js +29 -0
  29. package/src/error-log.js +138 -26
  30. package/src/error-report.js +17 -5
  31. package/src/gaps.js +1 -1
  32. package/src/grants.js +230 -0
  33. package/src/http-remote.js +80 -26
  34. package/src/index.js +18 -2
  35. package/src/invites.js +47 -1
  36. package/src/layers.js +1 -1
  37. package/src/lessons-to-checks.js +1 -1
  38. package/src/logger.js +3 -1
  39. package/src/oauth-provider.js +89 -5
  40. package/src/owl.js +232 -0
  41. package/src/owner-approvals.js +24 -267
  42. package/src/owner-session.js +235 -0
  43. package/src/pages.js +1 -1
  44. package/src/persons.js +39 -6
  45. package/src/proof-run.js +70 -0
  46. package/src/redact.js +4 -0
  47. package/src/request-log.js +2 -2
  48. package/src/rotate.js +554 -0
  49. package/src/rune-dispatch.js +1 -1
  50. package/src/session-graph.js +44 -25
  51. package/src/session.js +52 -9
  52. package/src/setup.js +21 -12
  53. package/src/staged-write.js +522 -0
  54. package/src/startup-pages.js +2 -2
  55. package/src/startup-payload.js +3 -3
  56. package/src/subkeys.js +61 -0
  57. package/src/tools.js +290 -79
  58. package/src/transcript-session.js +23 -4
  59. package/src/validation.js +1 -1
  60. package/src/version.js +1 -1
  61. package/src/writer-approval.js +394 -0
  62. package/templates/AREA.md +1 -1
  63. package/templates/BOTHANDOFF.md +2 -2
  64. package/templates/GRANT.md +48 -0
  65. package/templates/INDEX.md +9 -7
  66. package/templates/PROCEDURE.md +1 -1
  67. package/templates/ROSTER.md +2 -2
  68. package/templates/SEED.md +2 -2
  69. package/templates/SESSIONDISPOSITION.md +59 -0
  70. package/templates/STAGING.md +1 -1
  71. package/templates/STANDARD.md +1 -1
  72. package/templates/THREAD.md +1 -1
@@ -1,281 +1,38 @@
1
1
  /**
2
- * Owner page for pending sub-key requests.
2
+ * Owner approvals — retired by R4.
3
3
  *
4
- * Mounted only when EMET_SUBKEYS=1. The passphrase is the one the OAuth
5
- * consent page already checks (MongoOAuthProvider.checkPassphrase against
6
- * EMET_OAUTH_PASSPHRASE), and a wrong guess shares that form's per-address
7
- * lockout. A correct passphrase opens a session that lasts 15 minutes.
8
- * Approve and Deny post that session's CSRF token and call
9
- * decideSubkeyIfPending for the posted key_id. The history event records
10
- * the real owner id and via owner_page. emet_client_approve is unchanged.
4
+ * Superseded by /owner/chooser. This path stays mounted so an old bookmark
5
+ * answers with a pointer instead of disappearing. Sub-key records are not
6
+ * deleted and are not rewritten. Pending rows are listed on the chooser.
7
+ * ISO 9001 7.5.3 / ISO 13485 4.2.5: supersede, retire, retain.
8
+ *
9
+ * The passphrase session is an owner factor, not a writer grant
10
+ * (grants.js OWNER_PAGE). This file does not stamp writes.
11
11
  */
12
12
 
13
- import crypto from 'node:crypto';
14
- import express from 'express';
15
- import { timingSafeEqualStr } from './oauth-provider.js';
16
- import { decideSubkeyIfPending, loadSubkeyRecords } from './subkeys.js';
17
-
18
- const COOKIE_NAME = 'emet_owner';
19
- export const SESSION_MS = 15 * 60 * 1000;
20
- const SESSION_MAX = 200;
21
- const REASON_MAX = 500;
22
- const STORE_MESSAGE = 'The sub-key store is unavailable.';
23
- const NOT_PENDING = 'That sub-key is not awaiting approval. Nothing was changed.';
24
-
25
- function esc(s) {
26
- return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
27
- }
28
-
29
- function readCookie(req, name) {
30
- const raw = req.headers.cookie;
31
- if (!raw || typeof raw !== 'string') return null;
32
- for (const part of raw.split(';')) {
33
- const i = part.indexOf('=');
34
- if (i < 0) continue;
35
- if (part.slice(0, i).trim() !== name) continue;
36
- return part.slice(i + 1).trim();
37
- }
38
- return null;
39
- }
13
+ import { OWNER_APPROVALS_RETIRED } from './grants.js';
14
+ import { sendHtml } from './owner-session.js';
40
15
 
41
- function ownerActor(personId) {
42
- return {
43
- transport: 'http',
44
- authenticated: true,
45
- personId,
46
- ownerId: personId,
47
- sourceTag: 'owner',
48
- sourceBasis: 'login',
49
- clientId: null,
50
- grantId: null
51
- };
52
- }
53
-
54
- function page(body) {
55
- return `<!DOCTYPE html>
56
- <html lang="en">
57
- <head>
58
- <meta charset="utf-8">
59
- <meta name="viewport" content="width=device-width, initial-scale=1">
60
- <title>EMET owner approvals</title>
61
- <style>
62
- body { font-family: system-ui, sans-serif; background: #12141a; color: #e8e6e0; margin: 0; padding: 24px; }
63
- button { font: inherit; margin-right: 8px; }
64
- </style>
65
- </head>
66
- <body>
67
- ${body}
68
- </body>
69
- </html>`;
70
- }
71
-
72
- function sendHtml(res, status, body) {
73
- res.status(status);
74
- res.setHeader('Content-Type', 'text/html; charset=utf-8');
75
- res.setHeader('Cache-Control', 'no-store');
76
- res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
77
- res.send(page(body));
78
- }
16
+ export { SESSION_MS } from './owner-session.js';
79
17
 
80
- function pendingRows(data) {
81
- return Object.values((data && data.keys) || {})
82
- .filter((k) => k && k.status === 'pending' && k.key_id && k.tag)
83
- .sort((a, b) => String(a.requested_at || '').localeCompare(String(b.requested_at || '')) || String(a.key_id).localeCompare(String(b.key_id)));
18
+ function retiredBody() {
19
+ const next = OWNER_APPROVALS_RETIRED.superseded_by;
20
+ return `<h1>Owner approvals retired</h1>
21
+ <p>This page was retired by R4. It is superseded by <a href="${next}">${next}</a>. Pending sub-keys are listed there. Records are retained. Nothing was deleted.</p>
22
+ <p>ISO 9001 7.5.3 / ISO 13485 4.2.5. Break-glass recovery is <a href="/owner/break-glass">/owner/break-glass</a>.</p>`;
84
23
  }
85
24
 
86
- function listHtml(rows, csrf, note) {
87
- const noteHtml = note ? `<p>${esc(note)}</p>` : '';
88
- if (!rows.length) return `${noteHtml}<h1>Pending sub-keys</h1><p>No pending sub-key requests.</p>`;
89
- const body = rows.map((row) => {
90
- const prefix = esc(String(row.key_id).slice(0, 8));
91
- return `<tr><td>${esc(row.tag)}</td><td>${prefix}</td><td>${esc(row.requested_at || '')}</td><td>
92
- <form method="post" action="/owner/approvals/decide">
93
- <input type="hidden" name="csrf" value="${esc(csrf)}">
94
- <input type="hidden" name="key_id" value="${esc(row.key_id)}">
95
- <input type="text" name="reason" maxlength="${REASON_MAX}" placeholder="Reason (optional)">
96
- <button type="submit" name="decision" value="approve">Approve</button>
97
- <button type="submit" name="decision" value="deny">Deny</button>
98
- </form>
99
- </td></tr>`;
100
- }).join('\n');
101
- return `${noteHtml}<h1>Pending sub-keys</h1>
102
- <table>
103
- <thead><tr><th>Tag</th><th>Key</th><th>Requested</th><th></th></tr></thead>
104
- <tbody>
105
- ${body}
106
- </tbody>
107
- </table>`;
108
- }
109
-
110
- function notPending(res) {
111
- res.locals.reason = 'not_pending';
112
- sendHtml(res, 400, `<p>${NOT_PENDING}</p>`);
25
+ function retired(req, res) {
26
+ res.locals.reason = 'owner_approvals_retired';
27
+ sendHtml(res, 410, retiredBody(), 'EMET owner approvals');
113
28
  }
114
29
 
115
30
  /**
116
31
  * @param {import('express').Express} app
117
- * @param {{ checkPassphrase: (input: string) => boolean, throttle: { check: Function, recordFailure: Function, recordSuccess: Function }, deps: object | Function, ownerId: string | Function, now?: () => number }} options
32
+ * @param {object} [_options] kept so the Railway EMET mount stays the same call.
118
33
  */
119
- export function mountOwnerApprovals(app, options = {}) {
120
- const checkPassphrase = options.checkPassphrase;
121
- const throttle = options.throttle;
122
- const now = options.now || Date.now;
123
- const sessions = new Map();
124
- const parseBody = express.urlencoded({ extended: false });
125
- const depsOf = () => (typeof options.deps === 'function' ? options.deps() : options.deps);
126
-
127
- async function resolveOwner() {
128
- try { const id = await (typeof options.ownerId === 'function' ? options.ownerId() : options.ownerId); return (typeof id === 'string' && id.trim()) || null; }
129
- catch { return null; }
130
- }
131
-
132
- function sweep() {
133
- const t = now();
134
- for (const [id, row] of sessions) if (!row || row.expires <= t) sessions.delete(id);
135
- while (sessions.size > SESSION_MAX) sessions.delete(sessions.keys().next().value);
136
- }
137
-
138
- function sessionOf(req) {
139
- sweep();
140
- const raw = readCookie(req, COOKIE_NAME);
141
- if (!raw || !/^[0-9a-f]{64}$/.test(raw)) return null;
142
- return sessions.get(raw) || null;
143
- }
144
-
145
- async function renderList(req, res, note) {
146
- const session = sessionOf(req);
147
- if (!session) {
148
- sendHtml(res, 200, `<h1>Owner approvals</h1>
149
- <p>Enter the owner passphrase.</p>
150
- <form method="post" action="/owner/approvals/login">
151
- <label>Passphrase <input type="password" name="passphrase" autocomplete="current-password"></label>
152
- <button type="submit">Continue</button>
153
- </form>`);
154
- return;
155
- }
156
- let rows = [];
157
- try {
158
- rows = pendingRows(await loadSubkeyRecords(depsOf()));
159
- } catch {
160
- res.locals.reason = 'subkey_store';
161
- sendHtml(res, 503, `<p>${STORE_MESSAGE}</p>`);
162
- return;
163
- }
164
- sendHtml(res, 200, listHtml(rows, session.csrf, note));
165
- }
166
-
167
- app.get('/owner/approvals', (req, res) => {
168
- renderList(req, res).catch((e) => {
169
- console.error('[emet] owner approvals', e && e.message ? e.message : e);
170
- if (!res.headersSent) {
171
- res.locals.reason = 'owner_approvals_error';
172
- sendHtml(res, 500, '<p>Something went wrong.</p>');
173
- }
174
- });
175
- });
176
-
177
- app.post('/owner/approvals/login', parseBody, (req, res) => {
178
- const limit = throttle.check(req.ip);
179
- if (!limit.allowed) {
180
- res.locals.reason = 'throttled';
181
- res.setHeader('Retry-After', String(limit.retryAfterS));
182
- sendHtml(res, 429, '<p>Too many attempts. Try again later.</p>');
183
- return;
184
- }
185
- const passphrase = (req.body && req.body.passphrase) || '';
186
- let ok = false;
187
- try { ok = checkPassphrase(passphrase) === true; }
188
- catch (e) {
189
- console.error('[emet] owner passphrase check', e && e.message ? e.message : e);
190
- res.locals.reason = 'passphrase_check_error';
191
- sendHtml(res, 500, '<p>Something went wrong.</p>');
192
- return;
193
- }
194
- if (!ok) {
195
- throttle.recordFailure(req.ip);
196
- res.locals.reason = 'bad_passphrase';
197
- sendHtml(res, 401, '<p>Incorrect passphrase.</p>');
198
- return;
199
- }
200
- throttle.recordSuccess(req.ip);
201
- sweep();
202
- const id = crypto.randomBytes(32).toString('hex');
203
- const csrf = crypto.randomBytes(32).toString('hex');
204
- sessions.set(id, { csrf, expires: now() + SESSION_MS });
205
- res.cookie(COOKIE_NAME, id, {
206
- httpOnly: true,
207
- sameSite: 'strict',
208
- path: '/owner',
209
- maxAge: SESSION_MS,
210
- secure: req.secure === true
211
- });
212
- res.locals.reason = 'owner_session';
213
- res.redirect(303, '/owner/approvals');
214
- });
215
-
216
- app.post('/owner/approvals/decide', parseBody, (req, res) => {
217
- const session = sessionOf(req);
218
- if (!session) {
219
- res.locals.reason = 'no_owner_session';
220
- sendHtml(res, 401, '<p>Sign in again.</p>');
221
- return;
222
- }
223
- const posted = (req.body && req.body.csrf) || '';
224
- if (!timingSafeEqualStr(posted, session.csrf)) {
225
- res.locals.reason = 'bad_csrf';
226
- sendHtml(res, 403, '<p>The form expired. Reload the page and try again.</p>');
227
- return;
228
- }
229
- const decision = req.body && req.body.decision;
230
- const keyId = typeof (req.body && req.body.key_id) === 'string' ? req.body.key_id.trim() : '';
231
- const reason = typeof (req.body && req.body.reason) === 'string' ? req.body.reason.trim() : '';
232
- if (decision !== 'approve' && decision !== 'deny') {
233
- res.locals.reason = 'bad_decision';
234
- sendHtml(res, 400, '<p>Decision must be approve or deny. Nothing was changed.</p>');
235
- return;
236
- }
237
- if (reason.length > REASON_MAX) {
238
- res.locals.reason = 'reason_too_long';
239
- sendHtml(res, 400, '<p>The reason is too long. Nothing was changed.</p>');
240
- return;
241
- }
242
- finishDecide(req, res, keyId, decision, reason).catch((e) => {
243
- console.error('[emet] owner decide', e && e.message ? e.message : e);
244
- if (!res.headersSent) {
245
- res.locals.reason = 'owner_decide_error';
246
- sendHtml(res, 500, '<p>Something went wrong. Nothing was changed.</p>');
247
- }
248
- });
249
- });
250
-
251
- async function finishDecide(req, res, keyId, decision, reason) {
252
- const personId = await resolveOwner();
253
- if (!personId) {
254
- res.locals.reason = 'owner_unavailable';
255
- sendHtml(res, 400, '<p>The owner id is unavailable. Nothing was changed.</p>');
256
- return;
257
- }
258
- let result = null;
259
- try {
260
- result = await decideSubkeyIfPending(depsOf(), ownerActor(personId), personId, {
261
- key_id: keyId, decision, reason, via: 'owner_page'
262
- }, new Date(now()));
263
- } catch (e) {
264
- if (e && e.attributionRefusal && !/sub-key store/.test(String(e.message))) {
265
- res.locals.reason = 'decide_refused';
266
- sendHtml(res, 400, `<p>${esc(e.message)}</p>`);
267
- return;
268
- }
269
- res.locals.reason = 'subkey_store';
270
- sendHtml(res, 503, `<p>${STORE_MESSAGE}</p>`);
271
- return;
272
- }
273
- if (!result) {
274
- notPending(res);
275
- return;
276
- }
277
- res.locals.reason = decision === 'approve' ? 'subkey_approved' : 'subkey_denied';
278
- const verb = decision === 'approve' ? 'Approved' : 'Denied';
279
- await renderList(req, res, `${verb} ${result.tag}.`);
280
- }
34
+ export function mountOwnerApprovals(app, _options = {}) {
35
+ app.get('/owner/approvals', retired);
36
+ app.post('/owner/approvals/login', retired);
37
+ app.post('/owner/approvals/decide', retired);
281
38
  }
@@ -0,0 +1,235 @@
1
+ /**
2
+ * Owner passphrase session shared by the chooser and break-glass.
3
+ *
4
+ * This is the owner factor from OWNER_PAGE: the same passphrase as OAuth
5
+ * consent, the same per-address lockout, and no grant id. A member or guest
6
+ * grant is not this session.
7
+ */
8
+
9
+ import crypto from 'node:crypto';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import express from 'express';
14
+
15
+ export const SESSION_MS = 15 * 60 * 1000;
16
+ export const COOKIE_NAME = 'emet_owner';
17
+ const SESSION_MAX = 200;
18
+ const NEXT_OK = new Set(['/owner/chooser', '/owner/break-glass']);
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
+
41
+ export function esc(s) {
42
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
43
+ }
44
+
45
+ export function readCookie(req, name) {
46
+ const raw = req.headers.cookie;
47
+ if (!raw || typeof raw !== 'string') return null;
48
+ for (const part of raw.split(';')) {
49
+ const i = part.indexOf('=');
50
+ if (i < 0) continue;
51
+ if (part.slice(0, i).trim() !== name) continue;
52
+ return part.slice(i + 1).trim();
53
+ }
54
+ return null;
55
+ }
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
+
67
+ export function htmlPage(title, body) {
68
+ return `<!DOCTYPE html>
69
+ <html lang="en">
70
+ <head>
71
+ <meta charset="utf-8">
72
+ <meta name="viewport" content="width=device-width, initial-scale=1">
73
+ <title>${esc(title)}</title>
74
+ <style>
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; }
77
+ a { color: #8eb4d6; }
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; }
80
+ button { margin-right: 8px; }
81
+ input::placeholder { color: #3d4450; }
82
+ table { border-collapse: collapse; }
83
+ td, th { text-align: left; padding: 4px 10px 4px 0; vertical-align: top; }
84
+ code { color: #d9c27a; }
85
+ .note { color: #d9a441; }
86
+ </style>
87
+ </head>
88
+ <body>
89
+ <div class="sheet">
90
+ ${body}
91
+ </div>
92
+ </body>
93
+ </html>`;
94
+ }
95
+
96
+ export function sendHtml(res, status, body, title = 'EMET') {
97
+ res.status(status);
98
+ res.setHeader('Content-Type', 'text/html; charset=utf-8');
99
+ res.setHeader('Cache-Control', 'no-store');
100
+ res.setHeader('Content-Security-Policy', OWNER_PAGE_CSP);
101
+ res.send(htmlPage(title, body));
102
+ }
103
+
104
+ export function ownerPageActor(personId) {
105
+ return {
106
+ transport: 'http',
107
+ authenticated: true,
108
+ personId,
109
+ ownerId: personId,
110
+ sourceTag: 'owner',
111
+ sourceBasis: 'login',
112
+ clientId: null,
113
+ grantId: null
114
+ };
115
+ }
116
+
117
+ /**
118
+ * A door grant requires this session. Guest is the default only after the
119
+ * owner is signed in. A missing session cannot grant owner or member.
120
+ */
121
+ export function ownerMayGrant(session, decision) {
122
+ if (!session || !session.csrf) return false;
123
+ return decision === 'owner' || decision === 'member' || decision === 'guest';
124
+ }
125
+
126
+ export function createOwnerGate({ checkPassphrase, throttle, now = Date.now } = {}) {
127
+ const sessions = new Map();
128
+
129
+ function sweep() {
130
+ const t = now();
131
+ for (const [id, row] of sessions) if (!row || row.expires <= t) sessions.delete(id);
132
+ while (sessions.size > SESSION_MAX) sessions.delete(sessions.keys().next().value);
133
+ }
134
+
135
+ function sessionOf(req) {
136
+ sweep();
137
+ const raw = readCookie(req, COOKIE_NAME);
138
+ if (!raw || !/^[0-9a-f]{64}$/.test(raw)) return null;
139
+ const row = sessions.get(raw);
140
+ if (!row) return null;
141
+ return { csrf: row.csrf, expires: row.expires, id: raw };
142
+ }
143
+
144
+ function login(req, res) {
145
+ const next = NEXT_OK.has(req.body && req.body.next) ? req.body.next : '/owner/break-glass';
146
+ const limit = throttle.check(req.ip);
147
+ if (!limit.allowed) {
148
+ res.locals.reason = 'throttled';
149
+ res.setHeader('Retry-After', String(limit.retryAfterS));
150
+ sendHtml(res, 429, '<p>Too many attempts. Try again later.</p>', 'EMET owner');
151
+ return;
152
+ }
153
+ const passphrase = (req.body && req.body.passphrase) || '';
154
+ let ok = false;
155
+ try { ok = checkPassphrase(passphrase) === true; }
156
+ catch (e) {
157
+ console.error('[emet] owner passphrase check', e && e.message ? e.message : e);
158
+ res.locals.reason = 'passphrase_check_error';
159
+ sendHtml(res, 500, '<p>Something went wrong.</p>', 'EMET owner');
160
+ return;
161
+ }
162
+ if (!ok) {
163
+ throttle.recordFailure(req.ip);
164
+ res.locals.reason = 'bad_passphrase';
165
+ sendHtml(res, 401, '<p>Incorrect passphrase.</p>', 'EMET owner');
166
+ return;
167
+ }
168
+ throttle.recordSuccess(req.ip);
169
+ sweep();
170
+ const id = crypto.randomBytes(32).toString('hex');
171
+ const csrf = crypto.randomBytes(32).toString('hex');
172
+ sessions.set(id, { csrf, expires: now() + SESSION_MS });
173
+ res.cookie(COOKIE_NAME, id, {
174
+ httpOnly: true,
175
+ sameSite: 'strict',
176
+ path: '/owner',
177
+ maxAge: SESSION_MS,
178
+ secure: req.secure === true
179
+ });
180
+ res.locals.reason = 'owner_session';
181
+ res.redirect(303, next);
182
+ }
183
+
184
+ function endOtherSessions(keepId) {
185
+ if (typeof keepId !== 'string' || !keepId) return 0;
186
+ let ended = 0;
187
+ for (const id of [...sessions.keys()]) {
188
+ if (id === keepId) continue;
189
+ sessions.delete(id);
190
+ ended += 1;
191
+ }
192
+ return ended;
193
+ }
194
+
195
+ return { sessionOf, login, now, endOtherSessions };
196
+ }
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
+
219
+ export function mountOwnerLogin(app, gate) {
220
+ mountOwnerGraphic(app);
221
+ if (app.get('emetOwnerLogin')) return;
222
+ app.set('emetOwnerLogin', true);
223
+ app.post('/owner/login', express.urlencoded({ extended: false }), (req, res) => gate.login(req, res));
224
+ }
225
+
226
+ export function loginForm(nextPath) {
227
+ const next = NEXT_OK.has(nextPath) ? nextPath : '/owner/break-glass';
228
+ return `<h1>Owner</h1>
229
+ <p>Enter the owner passphrase. A member or guest grant does not sign this page in.</p>
230
+ <form method="post" action="/owner/login">
231
+ <input type="hidden" name="next" value="${esc(next)}">
232
+ <label>Passphrase <input type="password" name="passphrase" autocomplete="current-password"></label>
233
+ <button type="submit">Continue</button>
234
+ </form>`;
235
+ }
package/src/pages.js CHANGED
@@ -534,7 +534,7 @@ function selectorFor(doc) {
534
534
  function requireSlug(area, tool) {
535
535
  const slug = String(area || '').trim();
536
536
  if (!areaSlug(`areas/${slug}.md`)) {
537
- throw new ValidationError('area', `${tool}: area must be a slug like "health".`, { code: 'EMET-PAGE-004' });
537
+ throw new ValidationError('area', `${tool}: area must be a slug like "finances".`, { code: 'EMET-PAGE-004' });
538
538
  }
539
539
  return slug;
540
540
  }
package/src/persons.js CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { AsyncLocalStorage } from 'node:async_hooks';
13
+ import { grantIdFromFamily, httpDoor } from './grants.js';
13
14
 
14
15
  const COLLECTION = 'persons';
15
16
  /** Stdio has no login. Every local write is stamped with this one subject. */
@@ -17,7 +18,7 @@ export const LOCAL_SUBJECT = 'local';
17
18
  export const actorStore = new AsyncLocalStorage();
18
19
  export function currentActor() {
19
20
  const s = actorStore.getStore();
20
- if (typeof s === 'string' && s.trim()) return { personId: s.trim(), scopes: [] };
21
+ if (typeof s === 'string' && s.trim()) return { personId: s.trim(), scopes: [], grantId: null, door: 'stdio' };
21
22
  if (s && typeof s === 'object') {
22
23
  return {
23
24
  personId: s.personId || null,
@@ -25,10 +26,12 @@ export function currentActor() {
25
26
  scopes: Array.isArray(s.scopes) ? s.scopes : [],
26
27
  transport: s.transport || null,
27
28
  authenticated: s.authenticated === true,
28
- sourceTag: typeof s.sourceTag === 'string' ? s.sourceTag : null
29
+ sourceTag: typeof s.sourceTag === 'string' ? s.sourceTag : null,
30
+ grantId: s.transport === 'http' ? grantIdFromFamily(s.grantId) : null,
31
+ door: s.transport === 'http' ? httpDoor(s.door) : 'stdio'
29
32
  };
30
33
  }
31
- return { personId: null, clientId: null, scopes: [], transport: null, authenticated: false };
34
+ return { personId: null, clientId: null, scopes: [], transport: null, authenticated: false, grantId: null, door: null };
32
35
  }
33
36
  export function currentPersonId() {
34
37
  return currentActor().personId;
@@ -44,12 +47,22 @@ export function writerStamp() {
44
47
  const s = actorStore.getStore();
45
48
  if (!s || typeof s === 'string') {
46
49
  const id = typeof s === 'string' && s.trim() ? s.trim() : LOCAL_SUBJECT;
47
- return { person_id: id, client_id: 'stdio' };
50
+ return { person_id: id, client_id: 'stdio', grant_id: null, door: 'stdio' };
48
51
  }
49
52
  if (s.transport === 'http') {
50
- return { person_id: s.personId || null, client_id: s.clientId === undefined ? null : s.clientId };
53
+ return {
54
+ person_id: s.personId || null,
55
+ client_id: s.clientId === undefined ? null : s.clientId,
56
+ grant_id: grantIdFromFamily(s.grantId),
57
+ door: httpDoor(s.door)
58
+ };
51
59
  }
52
- return { person_id: s.personId || LOCAL_SUBJECT, client_id: s.clientId === undefined ? 'stdio' : s.clientId };
60
+ return {
61
+ person_id: s.personId || LOCAL_SUBJECT,
62
+ client_id: s.clientId === undefined ? 'stdio' : s.clientId,
63
+ grant_id: null,
64
+ door: 'stdio'
65
+ };
53
66
  }
54
67
 
55
68
  /**
@@ -79,6 +92,8 @@ export function declaredAttribution() {
79
92
  declared: s.declaredTag || null, basis: s.sourceBasis || null, login,
80
93
  effective: s.effectiveTag || null, clientId: s.clientId || null,
81
94
  approval: s.approvalState || null,
95
+ grantId: grantIdFromFamily(s.grantId),
96
+ door: httpDoor(s.door),
82
97
  rememberedTags: Array.isArray(s.rememberedTags) ? s.rememberedTags : [],
83
98
  ...(s.subkeyId ? { keyId: s.subkeyId } : {})
84
99
  };
@@ -131,6 +146,24 @@ export function personFromAuth(extra) {
131
146
  return null;
132
147
  }
133
148
 
149
+ /**
150
+ * HTTP CallTool actor. Grant and door are copied from the verified token
151
+ * (`auth.extra`) and from nowhere else. Stdio does not use this.
152
+ */
153
+ export function httpToolActor(extra) {
154
+ const auth = extra && extra.authInfo;
155
+ return {
156
+ personId: personFromAuth(extra),
157
+ clientId: (auth && auth.clientId) || 'http:visitor',
158
+ scopes: (auth && auth.scopes) || [],
159
+ transport: 'http',
160
+ sourceTag: (auth && auth.extra && auth.extra.sourceTag) || null,
161
+ grantId: (auth && auth.extra && auth.extra.grantId) || null,
162
+ door: (auth && auth.extra && auth.extra.door) || null,
163
+ authenticated: Boolean(auth)
164
+ };
165
+ }
166
+
134
167
  export async function getPerson(db, person_id) {
135
168
  if (!db || !person_id) return null;
136
169
  return db.collection(COLLECTION).findOne({ person_id });