@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.
- package/CHANGELOG.md +40 -0
- package/README.md +29 -6
- package/docs/BOOTSTRAP.md +2 -0
- package/docs/BOTS.md +8 -7
- package/docs/DEPLOY.md +6 -0
- package/docs/ERROR-CODES-SPEC.md +2 -2
- package/docs/ERROR-CODES.md +29 -0
- package/docs/GUIDED-SETUP.md +1 -1
- package/docs/PERMISSIONS.md +5 -5
- package/docs/SETUP.md +10 -4
- package/docs/SUBKEYS.md +4 -4
- package/package.json +2 -2
- package/server.json +8 -4
- package/src/aleph.js +34 -13
- package/src/annotations.js +6 -2
- package/src/approve-throttle.js +3 -0
- package/src/atlas-role.js +1 -1
- package/src/attribution.js +76 -28
- package/src/bound-door.js +170 -0
- package/src/break-glass.js +531 -0
- package/src/carry-forward-close.js +386 -0
- package/src/checkpoint.js +241 -0
- package/src/chooser.js +543 -0
- package/src/claimed-tag.js +140 -0
- package/src/conformance.js +269 -5
- package/src/deep-links.js +267 -0
- package/src/dispatch.js +112 -18
- package/src/error-codes.js +29 -0
- package/src/error-log.js +138 -26
- package/src/error-report.js +17 -5
- package/src/gaps.js +1 -1
- package/src/grants.js +230 -0
- package/src/http-remote.js +80 -26
- package/src/index.js +18 -2
- package/src/invites.js +47 -1
- package/src/layers.js +1 -1
- package/src/lessons-to-checks.js +1 -1
- package/src/logger.js +3 -1
- package/src/oauth-provider.js +89 -5
- package/src/owl.js +232 -0
- package/src/owner-approvals.js +24 -267
- package/src/owner-session.js +235 -0
- package/src/pages.js +1 -1
- package/src/persons.js +39 -6
- package/src/proof-run.js +70 -0
- package/src/redact.js +4 -0
- package/src/request-log.js +2 -2
- package/src/rotate.js +554 -0
- package/src/rune-dispatch.js +1 -1
- package/src/session-graph.js +44 -25
- package/src/session.js +52 -9
- package/src/setup.js +21 -12
- package/src/staged-write.js +522 -0
- package/src/startup-pages.js +2 -2
- package/src/startup-payload.js +3 -3
- package/src/subkeys.js +61 -0
- package/src/tools.js +290 -79
- package/src/transcript-session.js +23 -4
- package/src/validation.js +1 -1
- package/src/version.js +1 -1
- package/src/writer-approval.js +394 -0
- package/templates/AREA.md +1 -1
- package/templates/BOTHANDOFF.md +2 -2
- package/templates/GRANT.md +48 -0
- package/templates/INDEX.md +9 -7
- package/templates/PROCEDURE.md +1 -1
- package/templates/ROSTER.md +2 -2
- package/templates/SEED.md +2 -2
- package/templates/SESSIONDISPOSITION.md +59 -0
- package/templates/STAGING.md +1 -1
- package/templates/STANDARD.md +1 -1
- package/templates/THREAD.md +1 -1
package/src/chooser.js
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owner / member / guest chooser (R4a).
|
|
3
|
+
*
|
|
4
|
+
* A deep link opens this page and is consumed on that open. The owner
|
|
5
|
+
* passphrase session is what grants a door. Guest is the least-privilege
|
|
6
|
+
* default. Owner and member require that same session. The link itself
|
|
7
|
+
* grants nothing.
|
|
8
|
+
*
|
|
9
|
+
* Pending sub-keys from the retired /owner/approvals path are listed here.
|
|
10
|
+
* Their records stay in the sub-key store.
|
|
11
|
+
*
|
|
12
|
+
* Prepared writer requests are listed here too. Master Hub prepares.
|
|
13
|
+
* The server validates. This owner session decides. The request row stays.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import crypto from 'node:crypto';
|
|
17
|
+
import express from 'express';
|
|
18
|
+
import { setting } from './env.js';
|
|
19
|
+
import { DOORS } from './grants.js';
|
|
20
|
+
import { timingSafeEqualStr } from './oauth-provider.js';
|
|
21
|
+
import {
|
|
22
|
+
presentDeepLink, deepLinkTtlMs, recordAccessDecision, bindGrantId, bindTag, bindDoor
|
|
23
|
+
} from './deep-links.js';
|
|
24
|
+
import {
|
|
25
|
+
esc, sendHtml, loginForm, ownerPageActor, ownerMayGrant, mountOwnerLogin, readCookie, createOwnerGate
|
|
26
|
+
} from './owner-session.js';
|
|
27
|
+
import { rotationForms } from './rotate.js';
|
|
28
|
+
|
|
29
|
+
const CHOOSER_COOKIE = 'emet_chooser';
|
|
30
|
+
const REASON_MAX = 500;
|
|
31
|
+
const STORE_MESSAGE = 'The sub-key store is unavailable.';
|
|
32
|
+
const opened = new Map();
|
|
33
|
+
|
|
34
|
+
export function _resetChooserForTests() {
|
|
35
|
+
opened.clear();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function sweepOpened(now) {
|
|
39
|
+
for (const [id, row] of opened) if (!row || row.expires <= now) opened.delete(id);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function stashOf(req, now) {
|
|
43
|
+
sweepOpened(now);
|
|
44
|
+
const raw = readCookie(req, CHOOSER_COOKIE);
|
|
45
|
+
if (!raw || !/^[0-9a-f]{64}$/.test(raw)) return null;
|
|
46
|
+
return opened.get(raw) || null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function pendingSubkeys(data) {
|
|
50
|
+
return Object.values((data && data.keys) || {})
|
|
51
|
+
.filter((k) => k && k.status === 'pending' && k.key_id && k.tag)
|
|
52
|
+
.sort((a, b) => String(a.requested_at || '').localeCompare(String(b.requested_at || '')) || String(a.key_id).localeCompare(String(b.key_id)));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function retainedSubkeys(data) {
|
|
56
|
+
return Object.values((data && data.keys) || {})
|
|
57
|
+
.filter((k) => k && k.status && k.status !== 'pending' && k.key_id && k.tag)
|
|
58
|
+
.sort((a, b) => String(a.tag).localeCompare(String(b.tag)) || String(a.key_id).localeCompare(String(b.key_id)));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function historyLine(row) {
|
|
62
|
+
const events = Array.isArray(row.history) ? row.history : [];
|
|
63
|
+
if (!events.length) return esc(row.status);
|
|
64
|
+
return events.map((ev) => {
|
|
65
|
+
if (!ev) return '';
|
|
66
|
+
return esc([ev.event, ev.via, ev.at].filter(Boolean).join(' '));
|
|
67
|
+
}).filter(Boolean).join('<br>');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function writerSection(session, writers) {
|
|
71
|
+
if (!session) return '';
|
|
72
|
+
if (writers == null) return '<h2>Writer requests</h2><p>Writer requests could not be listed. Nothing was changed.</p>';
|
|
73
|
+
if (!writers.length) return '<h2>Writer requests</h2><p>No writer requests are on file.</p>';
|
|
74
|
+
const body = writers.map((row) => {
|
|
75
|
+
const buttons = row.status === 'validated'
|
|
76
|
+
? `<form method="post" action="/owner/chooser/writer">
|
|
77
|
+
<input type="hidden" name="csrf" value="${esc(session.csrf)}">
|
|
78
|
+
<input type="hidden" name="request_id" value="${esc(row.request_id)}">
|
|
79
|
+
<button type="submit" name="decision" value="approve">Approve</button>
|
|
80
|
+
<button type="submit" name="decision" value="deny">Deny</button>
|
|
81
|
+
</form>`
|
|
82
|
+
: '';
|
|
83
|
+
return `<tr><td>${esc(row.claimed_tag)}</td><td>${esc(row.door)}</td><td>${esc(row.status)}</td><td>${esc(row.preparer)}</td><td>${esc(row.validator)}</td><td>${esc(row.correlation_id)}</td><td>${buttons}</td></tr>`;
|
|
84
|
+
}).join('\n');
|
|
85
|
+
return `<h2>Writer requests</h2>
|
|
86
|
+
<p>Master Hub prepares. The server validates. Only this owner session decides.</p>
|
|
87
|
+
<table><thead><tr><th>Tag</th><th>Door</th><th>Status</th><th>Preparer</th><th>Validator</th><th>Correlation</th><th></th></tr></thead><tbody>${body}</tbody></table>`;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function doorRadios() {
|
|
91
|
+
return `<fieldset>
|
|
92
|
+
<legend>Door</legend>
|
|
93
|
+
<label><input type="radio" name="decision" value="guest" checked> Guest</label>
|
|
94
|
+
<label><input type="radio" name="decision" value="member"> Member</label>
|
|
95
|
+
<label><input type="radio" name="decision" value="owner"> Owner</label>
|
|
96
|
+
</fieldset>
|
|
97
|
+
<p>Guest is the least-privilege default. Only this owner session can grant owner or member.</p>`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function loadKeys(deps) {
|
|
101
|
+
if (setting('SUBKEYS') !== '1') return { skipped: true, rows: [], retained: [] };
|
|
102
|
+
const { loadSubkeyRecords } = await import('./subkeys.js');
|
|
103
|
+
const data = await loadSubkeyRecords(deps);
|
|
104
|
+
return { skipped: false, rows: pendingSubkeys(data), retained: retainedSubkeys(data) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function bindingFields(binding) {
|
|
108
|
+
if (!binding) return '';
|
|
109
|
+
return `<input type="hidden" name="bind_grant" value="${esc(binding.grant_id)}">
|
|
110
|
+
<input type="hidden" name="bind_tag" value="${esc(binding.tag)}">
|
|
111
|
+
<input type="hidden" name="bind_door" value="${esc(binding.door)}">`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function pageBody({ session, stash, keys, writers, note }) {
|
|
115
|
+
const parts = [];
|
|
116
|
+
if (note) parts.push(`<p class="note">${esc(note)}</p>`);
|
|
117
|
+
if (!session) {
|
|
118
|
+
parts.push(loginForm('/owner/chooser'));
|
|
119
|
+
parts.push('<p>Break-glass recovery, with no AI client, is <a href="/owner/break-glass">/owner/break-glass</a>.</p>');
|
|
120
|
+
return parts.join('\n');
|
|
121
|
+
}
|
|
122
|
+
const binding = stash && stash.binding;
|
|
123
|
+
if (binding) {
|
|
124
|
+
parts.push(`<h1>Chooser</h1>
|
|
125
|
+
<p>This link is for grant <code>${esc(binding.grant_id)}</code>, tag <code>${esc(binding.tag)}</code>, door <code>${esc(binding.door)}</code> (${esc(binding.kind)}). correlation_id <code>${esc(binding.correlation_id)}</code>. The link grants nothing.</p>`);
|
|
126
|
+
} else {
|
|
127
|
+
parts.push('<h1>Chooser</h1><p>No refusal link is open. Guest is selected unless you choose another door.</p>');
|
|
128
|
+
}
|
|
129
|
+
const tagField = binding
|
|
130
|
+
? `<p>Tag <code>${esc(binding.tag)}</code></p>`
|
|
131
|
+
: `<label>Tag <input type="text" name="tag" maxlength="80" autocomplete="off"></label>`;
|
|
132
|
+
parts.push(`<form method="post" action="/owner/chooser/decide">
|
|
133
|
+
<input type="hidden" name="csrf" value="${esc(session.csrf)}">
|
|
134
|
+
${bindingFields(binding)}
|
|
135
|
+
${tagField}
|
|
136
|
+
${doorRadios()}
|
|
137
|
+
<button type="submit">Grant this door</button>
|
|
138
|
+
</form>`);
|
|
139
|
+
if (keys && keys.skipped) {
|
|
140
|
+
parts.push('<p>Sub-keys are off in this process. Nothing was listed from that store.</p>');
|
|
141
|
+
} else if (keys) {
|
|
142
|
+
if (!keys.rows.length) parts.push('<h2>Pending sub-keys</h2><p>No pending sub-key requests.</p>');
|
|
143
|
+
else {
|
|
144
|
+
const body = keys.rows.map((row) => `<tr><td>${esc(row.tag)}</td><td>${esc(String(row.key_id).slice(0, 8))}</td><td>${esc(row.requested_at || '')}</td><td>
|
|
145
|
+
<form method="post" action="/owner/chooser/subkey">
|
|
146
|
+
<input type="hidden" name="csrf" value="${esc(session.csrf)}">
|
|
147
|
+
<input type="hidden" name="key_id" value="${esc(row.key_id)}">
|
|
148
|
+
<input type="text" name="reason" maxlength="${REASON_MAX}" placeholder="Reason (optional)">
|
|
149
|
+
<button type="submit" name="decision" value="approve">Approve</button>
|
|
150
|
+
<button type="submit" name="decision" value="deny">Deny</button>
|
|
151
|
+
</form>
|
|
152
|
+
</td></tr>`).join('\n');
|
|
153
|
+
parts.push(`<h2>Pending sub-keys</h2>
|
|
154
|
+
<table>
|
|
155
|
+
<thead><tr><th>Tag</th><th>Key</th><th>Requested</th><th></th></tr></thead>
|
|
156
|
+
<tbody>${body}</tbody>
|
|
157
|
+
</table>`);
|
|
158
|
+
}
|
|
159
|
+
parts.push('<h2>Retained records</h2>');
|
|
160
|
+
if (!keys.retained.length) parts.push('<p>No earlier sub-key decisions are in this store.</p>');
|
|
161
|
+
else {
|
|
162
|
+
const body = keys.retained.map((row) => `<tr><td>${esc(row.tag)}</td><td>${esc(row.status)}</td><td>${historyLine(row)}</td></tr>`).join('\n');
|
|
163
|
+
parts.push(`<table><thead><tr><th>Tag</th><th>Status</th><th>History</th></tr></thead><tbody>${body}</tbody></table>`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
parts.push(writerSection(session, writers));
|
|
167
|
+
parts.push(rotationForms(session.csrf));
|
|
168
|
+
parts.push('<p>Break-glass recovery is <a href="/owner/break-glass">/owner/break-glass</a>.</p>');
|
|
169
|
+
return parts.join('\n');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function issueDoor(db, door, tag, decider) {
|
|
173
|
+
if (door === 'owner') {
|
|
174
|
+
return { issued: false, note: 'Owner door is the passphrase consent on this host. This page did not mint a token.' };
|
|
175
|
+
}
|
|
176
|
+
if (!db) return { issued: false, note: 'The store is unavailable. Nothing was issued.' };
|
|
177
|
+
try {
|
|
178
|
+
if (door === 'member') {
|
|
179
|
+
const { createMemberAccess } = await import('./invites.js');
|
|
180
|
+
const invite = await createMemberAccess(db, { created_by: decider, display_name: tag, source_tag: tag });
|
|
181
|
+
return { issued: true, invite };
|
|
182
|
+
}
|
|
183
|
+
const { createInvite } = await import('./invites.js');
|
|
184
|
+
const invite = await createInvite(db, { created_by: decider, display_name: tag, source_tag: tag });
|
|
185
|
+
return { issued: true, invite };
|
|
186
|
+
} catch (e) {
|
|
187
|
+
if (e && e.code === 'INVITES_FROZEN') return { issued: false, note: 'EMET Guest Access is off on this install. Nothing was issued.' };
|
|
188
|
+
if (e && e.code === 'MEMBER_ACCESS_FROZEN') return { issued: false, note: 'EMET Member Access is off on this install. Nothing was issued.' };
|
|
189
|
+
return { issued: false, note: 'That door did not issue a code. Nothing was issued.' };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* @param {import('express').Express} app
|
|
195
|
+
* @param {{ gate?: object, checkPassphrase?: Function, throttle?: object, deps?: object | Function, ownerId?: string | Function, db?: object | Function, now?: () => number }} options
|
|
196
|
+
*/
|
|
197
|
+
export function mountChooser(app, options = {}) {
|
|
198
|
+
const now = options.now || Date.now;
|
|
199
|
+
const gate = options.gate || createOwnerGate({
|
|
200
|
+
checkPassphrase: options.checkPassphrase,
|
|
201
|
+
throttle: options.throttle,
|
|
202
|
+
now
|
|
203
|
+
});
|
|
204
|
+
mountOwnerLogin(app, gate);
|
|
205
|
+
const parseBody = express.urlencoded({ extended: false });
|
|
206
|
+
const depsOf = () => (typeof options.deps === 'function' ? options.deps() : options.deps);
|
|
207
|
+
const dbOf = () => (typeof options.db === 'function' ? options.db() : options.db);
|
|
208
|
+
|
|
209
|
+
async function resolveOwner() {
|
|
210
|
+
try {
|
|
211
|
+
const id = await (typeof options.ownerId === 'function' ? options.ownerId() : options.ownerId);
|
|
212
|
+
return (typeof id === 'string' && id.trim()) || null;
|
|
213
|
+
} catch { return null; }
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function prefixOf() {
|
|
217
|
+
return typeof options.prefix === 'string' && options.prefix ? options.prefix : 'emet_';
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function render(req, res, note) {
|
|
221
|
+
const session = gate.sessionOf(req);
|
|
222
|
+
let keys = null;
|
|
223
|
+
let writers = null;
|
|
224
|
+
if (session) {
|
|
225
|
+
try {
|
|
226
|
+
keys = await loadKeys(depsOf());
|
|
227
|
+
} catch {
|
|
228
|
+
res.locals.reason = 'subkey_store';
|
|
229
|
+
sendHtml(res, 503, `<p>${STORE_MESSAGE}</p>`, 'EMET chooser');
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
const { listWriterRequests } = await import('./writer-approval.js');
|
|
234
|
+
writers = await listWriterRequests(dbOf(), prefixOf());
|
|
235
|
+
} catch {
|
|
236
|
+
writers = null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
sendHtml(res, 200, pageBody({ session, stash: stashOf(req, now()), keys, writers, note }), 'EMET chooser');
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
app.get('/owner/chooser', (req, res) => {
|
|
243
|
+
const token = typeof req.query.d === 'string' ? req.query.d : '';
|
|
244
|
+
if (token) {
|
|
245
|
+
const openedLink = presentDeepLink(token, {}, now());
|
|
246
|
+
if (!openedLink.ok) {
|
|
247
|
+
res.locals.reason = openedLink.reason;
|
|
248
|
+
const text = {
|
|
249
|
+
expired: 'This link has expired. Nothing was granted.',
|
|
250
|
+
replay: 'This link was already used. Nothing was granted.',
|
|
251
|
+
wrong_instance: 'This link is for another instance. Nothing was granted.',
|
|
252
|
+
wrong_scope: 'This link does not match that client, tag, or door. Nothing was granted.',
|
|
253
|
+
rotated: 'This link was revoked by rotation. Nothing was granted. Sign in, assign the tag, and initialize from the chooser.',
|
|
254
|
+
unknown: 'This link is not valid. Nothing was granted.'
|
|
255
|
+
}[openedLink.reason] || 'This link is not valid. Nothing was granted.';
|
|
256
|
+
const clientError = openedLink.reason === 'expired' || openedLink.reason === 'replay' || openedLink.reason === 'wrong_scope' || openedLink.reason === 'wrong_instance' || openedLink.reason === 'rotated';
|
|
257
|
+
sendHtml(res, clientError ? 400 : 404, `<p>${esc(text)}</p><p><a href="/owner/chooser">Chooser</a></p>`, 'EMET chooser');
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const nonce = crypto.randomBytes(32).toString('hex');
|
|
261
|
+
const ttl = Math.max(1000, openedLink.binding ? deepLinkTtlMs() : 1000);
|
|
262
|
+
opened.set(nonce, { binding: openedLink.binding, expires: now() + ttl });
|
|
263
|
+
res.cookie(CHOOSER_COOKIE, nonce, {
|
|
264
|
+
httpOnly: true,
|
|
265
|
+
sameSite: 'strict',
|
|
266
|
+
path: '/owner',
|
|
267
|
+
maxAge: ttl,
|
|
268
|
+
secure: req.secure === true
|
|
269
|
+
});
|
|
270
|
+
res.locals.reason = 'chooser_opened';
|
|
271
|
+
res.redirect(303, '/owner/chooser');
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
render(req, res).catch((e) => {
|
|
275
|
+
console.error('[emet] chooser', e && e.message ? e.message : e);
|
|
276
|
+
if (!res.headersSent) {
|
|
277
|
+
res.locals.reason = 'chooser_error';
|
|
278
|
+
sendHtml(res, 500, '<p>Something went wrong.</p>', 'EMET chooser');
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
app.post('/owner/chooser/decide', parseBody, (req, res) => {
|
|
284
|
+
finishDecide(req, res).catch((e) => {
|
|
285
|
+
console.error('[emet] chooser decide', e && e.message ? e.message : e);
|
|
286
|
+
if (!res.headersSent) {
|
|
287
|
+
res.locals.reason = 'chooser_decide_error';
|
|
288
|
+
sendHtml(res, 500, '<p>Something went wrong. Nothing was granted.</p>', 'EMET chooser');
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
|
|
293
|
+
app.post('/owner/chooser/writer', parseBody, (req, res) => {
|
|
294
|
+
finishWriter(req, res).catch((e) => {
|
|
295
|
+
console.error('[emet] chooser writer', e && e.message ? e.message : e);
|
|
296
|
+
if (!res.headersSent) {
|
|
297
|
+
res.locals.reason = 'chooser_writer_error';
|
|
298
|
+
sendHtml(res, 500, '<p>Something went wrong. Nothing was changed.</p>', 'EMET chooser');
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
app.post('/owner/chooser/subkey', parseBody, (req, res) => {
|
|
304
|
+
finishSubkey(req, res).catch((e) => {
|
|
305
|
+
console.error('[emet] chooser subkey', e && e.message ? e.message : e);
|
|
306
|
+
if (!res.headersSent) {
|
|
307
|
+
res.locals.reason = 'chooser_subkey_error';
|
|
308
|
+
sendHtml(res, 500, '<p>Something went wrong. Nothing was changed.</p>', 'EMET chooser');
|
|
309
|
+
}
|
|
310
|
+
});
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
function postedBinding(body) {
|
|
314
|
+
if (!body || (body.bind_grant == null && body.bind_tag == null && body.bind_door == null)) return null;
|
|
315
|
+
return {
|
|
316
|
+
grant_id: bindGrantId(body.bind_grant),
|
|
317
|
+
tag: bindTag(body.bind_tag),
|
|
318
|
+
door: bindDoor(body.bind_door)
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
async function finishDecide(req, res) {
|
|
323
|
+
const session = gate.sessionOf(req);
|
|
324
|
+
const raw = req.body && req.body.decision;
|
|
325
|
+
const decision = DOORS.includes(raw) ? raw : (raw == null || raw === '' ? 'guest' : null);
|
|
326
|
+
if (!ownerMayGrant(session, decision || 'guest')) {
|
|
327
|
+
res.locals.reason = 'owner_only';
|
|
328
|
+
sendHtml(res, 401, '<p>Only the owner session can grant a door. Nothing was granted.</p>', 'EMET chooser');
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (!decision) {
|
|
332
|
+
res.locals.reason = 'bad_decision';
|
|
333
|
+
sendHtml(res, 400, '<p>Door must be owner, member, or guest. Nothing was granted.</p>', 'EMET chooser');
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const posted = (req.body && req.body.csrf) || '';
|
|
337
|
+
if (!timingSafeEqualStr(posted, session.csrf)) {
|
|
338
|
+
res.locals.reason = 'bad_csrf';
|
|
339
|
+
sendHtml(res, 403, '<p>The form expired. Reload the page and try again.</p>', 'EMET chooser');
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const stash = stashOf(req, now());
|
|
343
|
+
const claimed = postedBinding(req.body);
|
|
344
|
+
if (stash && stash.binding) {
|
|
345
|
+
const bound = stash.binding;
|
|
346
|
+
if (!claimed || claimed.grant_id !== bound.grant_id || claimed.tag !== bound.tag || claimed.door !== bound.door) {
|
|
347
|
+
res.locals.reason = 'wrong_scope';
|
|
348
|
+
sendHtml(res, 403, '<p>That link is bound to a different client, tag, or door. Nothing was granted.</p>', 'EMET chooser');
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
const personId = await resolveOwner();
|
|
353
|
+
if (!personId) {
|
|
354
|
+
res.locals.reason = 'owner_unavailable';
|
|
355
|
+
sendHtml(res, 400, '<p>The owner id is unavailable. Nothing was granted.</p>', 'EMET chooser');
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const binding = stash && stash.binding;
|
|
359
|
+
const tag = binding ? binding.tag : bindTag(req.body && req.body.tag);
|
|
360
|
+
if ((decision === 'member' || decision === 'guest') && tag === 'unknown') {
|
|
361
|
+
res.locals.reason = 'tag_required';
|
|
362
|
+
sendHtml(res, 400, '<p>A tag is required for member or guest. Nothing was granted.</p>', 'EMET chooser');
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
let db = null;
|
|
366
|
+
try { db = dbOf() || null; } catch { db = null; }
|
|
367
|
+
const issued = await issueDoor(db, decision, tag === 'unknown' ? 'owner' : tag, personId);
|
|
368
|
+
recordAccessDecision({
|
|
369
|
+
grant_id: binding ? binding.grant_id : 'unknown',
|
|
370
|
+
correlation_id: binding ? binding.correlation_id : 'none',
|
|
371
|
+
decider: personId,
|
|
372
|
+
decision,
|
|
373
|
+
surface: 'chooser',
|
|
374
|
+
door: decision,
|
|
375
|
+
tag,
|
|
376
|
+
kind: binding ? binding.kind : 'direct',
|
|
377
|
+
issued: issued.issued
|
|
378
|
+
});
|
|
379
|
+
if (stash) opened.delete(readCookie(req, CHOOSER_COOKIE));
|
|
380
|
+
res.locals.reason = issued.issued ? 'door_issued' : 'door_recorded';
|
|
381
|
+
const bits = [`Recorded ${decision} for ${tag}.`];
|
|
382
|
+
if (issued.note) bits.push(issued.note);
|
|
383
|
+
if (issued.invite && issued.invite.code) bits.push(`Invite code, shown once: ${issued.invite.code}`);
|
|
384
|
+
await render(req, res, bits.join(' '));
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function finishSubkey(req, res) {
|
|
388
|
+
const session = gate.sessionOf(req);
|
|
389
|
+
if (!session) {
|
|
390
|
+
res.locals.reason = 'no_owner_session';
|
|
391
|
+
sendHtml(res, 401, '<p>Sign in again. Nothing was changed.</p>', 'EMET chooser');
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
const posted = (req.body && req.body.csrf) || '';
|
|
395
|
+
if (!timingSafeEqualStr(posted, session.csrf)) {
|
|
396
|
+
res.locals.reason = 'bad_csrf';
|
|
397
|
+
sendHtml(res, 403, '<p>The form expired. Reload the page and try again.</p>', 'EMET chooser');
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
const decision = req.body && req.body.decision;
|
|
401
|
+
const keyId = typeof (req.body && req.body.key_id) === 'string' ? req.body.key_id.trim() : '';
|
|
402
|
+
const reason = typeof (req.body && req.body.reason) === 'string' ? req.body.reason.trim() : '';
|
|
403
|
+
if (decision !== 'approve' && decision !== 'deny') {
|
|
404
|
+
res.locals.reason = 'bad_decision';
|
|
405
|
+
sendHtml(res, 400, '<p>Decision must be approve or deny. Nothing was changed.</p>', 'EMET chooser');
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
if (reason.length > REASON_MAX) {
|
|
409
|
+
res.locals.reason = 'reason_too_long';
|
|
410
|
+
sendHtml(res, 400, '<p>The reason is too long. Nothing was changed.</p>', 'EMET chooser');
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const personId = await resolveOwner();
|
|
414
|
+
if (!personId) {
|
|
415
|
+
res.locals.reason = 'owner_unavailable';
|
|
416
|
+
sendHtml(res, 400, '<p>The owner id is unavailable. Nothing was changed.</p>', 'EMET chooser');
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
const { decideSubkeyIfPending } = await import('./subkeys.js');
|
|
420
|
+
let result = null;
|
|
421
|
+
try {
|
|
422
|
+
result = await decideSubkeyIfPending(depsOf(), ownerPageActor(personId), personId, {
|
|
423
|
+
key_id: keyId, decision, reason, via: 'owner_chooser'
|
|
424
|
+
}, new Date(now()));
|
|
425
|
+
} catch (e) {
|
|
426
|
+
if (e && e.attributionRefusal && !/sub-key store/.test(String(e.message))) {
|
|
427
|
+
res.locals.reason = 'decide_refused';
|
|
428
|
+
sendHtml(res, 400, `<p>${esc(e.message)}</p>`, 'EMET chooser');
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
res.locals.reason = 'subkey_store';
|
|
432
|
+
sendHtml(res, 503, `<p>${STORE_MESSAGE}</p>`, 'EMET chooser');
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
if (!result) {
|
|
436
|
+
res.locals.reason = 'not_pending';
|
|
437
|
+
sendHtml(res, 400, '<p>That sub-key is not awaiting approval. Nothing was changed.</p>', 'EMET chooser');
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
recordAccessDecision({
|
|
441
|
+
grant_id: 'unknown',
|
|
442
|
+
correlation_id: 'none',
|
|
443
|
+
decider: personId,
|
|
444
|
+
decision,
|
|
445
|
+
surface: 'chooser',
|
|
446
|
+
tag: result.tag,
|
|
447
|
+
kind: 'legacy_subkey',
|
|
448
|
+
issued: false
|
|
449
|
+
});
|
|
450
|
+
res.locals.reason = decision === 'approve' ? 'subkey_approved' : 'subkey_denied';
|
|
451
|
+
const verb = decision === 'approve' ? 'Approved' : 'Denied';
|
|
452
|
+
await render(req, res, `${verb} ${result.tag}.`);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function finishWriter(req, res) {
|
|
456
|
+
const session = gate.sessionOf(req);
|
|
457
|
+
if (!session) {
|
|
458
|
+
res.locals.reason = 'no_owner_session';
|
|
459
|
+
sendHtml(res, 401, '<p>Only the owner session can grant a writer.</p>', 'EMET chooser');
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const posted = (req.body && req.body.csrf) || '';
|
|
463
|
+
if (!timingSafeEqualStr(posted, session.csrf)) {
|
|
464
|
+
res.locals.reason = 'bad_csrf';
|
|
465
|
+
sendHtml(res, 403, '<p>The form expired. Reload the page and try again.</p>', 'EMET chooser');
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
const decision = req.body && req.body.decision;
|
|
469
|
+
const requestId = typeof (req.body && req.body.request_id) === 'string' ? req.body.request_id.trim() : '';
|
|
470
|
+
if (decision !== 'approve' && decision !== 'deny') {
|
|
471
|
+
res.locals.reason = 'bad_decision';
|
|
472
|
+
sendHtml(res, 400, '<p>Decision must be approve or deny. Nothing was changed.</p>', 'EMET chooser');
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const personId = await resolveOwner();
|
|
476
|
+
if (!personId) {
|
|
477
|
+
res.locals.reason = 'owner_unavailable';
|
|
478
|
+
sendHtml(res, 400, '<p>The owner id is unavailable. Nothing was changed.</p>', 'EMET chooser');
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
let db = null;
|
|
482
|
+
try { db = dbOf() || null; } catch { db = null; }
|
|
483
|
+
const { claimWriterDecision, releaseWriterClaim, stampWriterIssued } = await import('./writer-approval.js');
|
|
484
|
+
let recorded;
|
|
485
|
+
try {
|
|
486
|
+
recorded = await claimWriterDecision(db, prefixOf(), {
|
|
487
|
+
requestId,
|
|
488
|
+
decision,
|
|
489
|
+
decider: personId,
|
|
490
|
+
ownerSession: true
|
|
491
|
+
}, new Date(now()));
|
|
492
|
+
} catch (e) {
|
|
493
|
+
res.locals.reason = 'not_validated';
|
|
494
|
+
sendHtml(res, 400, `<p>${esc(e && e.message ? e.message : 'That writer request is not awaiting a decision. Nothing was changed.')}</p>`, 'EMET chooser');
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
let issued = { issued: false };
|
|
498
|
+
if (decision === 'approve') {
|
|
499
|
+
try {
|
|
500
|
+
issued = await issueDoor(db, recorded.door, recorded.claimed_tag, personId);
|
|
501
|
+
if (!issued.issued) {
|
|
502
|
+
res.locals.reason = 'writer_not_issued';
|
|
503
|
+
sendHtml(res, 400, `<p>${esc(issued.note || 'That door did not issue a code. Nothing was changed.')}</p>`, 'EMET chooser');
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
recorded = await stampWriterIssued(db, prefixOf(), { requestId });
|
|
507
|
+
} catch (e) {
|
|
508
|
+
res.locals.reason = 'writer_refused';
|
|
509
|
+
sendHtml(res, 400, `<p>${esc(e && e.message ? e.message : 'Nothing was changed.')}</p>`, 'EMET chooser');
|
|
510
|
+
return;
|
|
511
|
+
} finally {
|
|
512
|
+
if (!issued.issued) await releaseWriterClaim(db, prefixOf(), { requestId }, new Date(now()));
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
recordAccessDecision({
|
|
516
|
+
grant_id: recorded.grant_id || 'unknown',
|
|
517
|
+
correlation_id: recorded.correlation_id || 'none',
|
|
518
|
+
decider: personId,
|
|
519
|
+
decision,
|
|
520
|
+
surface: 'chooser',
|
|
521
|
+
door: recorded.door,
|
|
522
|
+
tag: recorded.claimed_tag,
|
|
523
|
+
kind: 'writer',
|
|
524
|
+
issued: issued.issued
|
|
525
|
+
});
|
|
526
|
+
res.locals.reason = decision === 'approve' ? 'writer_approved' : 'writer_denied';
|
|
527
|
+
const bits = [`Recorded ${decision} for ${recorded.claimed_tag}.`];
|
|
528
|
+
if (issued.note) bits.push(issued.note);
|
|
529
|
+
if (issued.invite && issued.invite.code) bits.push(`Invite code, shown once: ${issued.invite.code}`);
|
|
530
|
+
if (issued.issued && recorded.claimed_tag === 'grok-project') {
|
|
531
|
+
let sophiaNote = 'The BOUND door listing was not written. The invite code above is still the door.';
|
|
532
|
+
try {
|
|
533
|
+
const { sophiaListingAfterWriterIssue } = await import('./bound-door.js');
|
|
534
|
+
const listing = await sophiaListingAfterWriterIssue({
|
|
535
|
+
recorded, issued, deps: depsOf(), by: personId, now: new Date(now())
|
|
536
|
+
});
|
|
537
|
+
if (listing.written) sophiaNote = 'Listed grok-project as its own door.';
|
|
538
|
+
} catch { /* the invite still stands */ }
|
|
539
|
+
bits.push(sophiaNote);
|
|
540
|
+
}
|
|
541
|
+
await render(req, res, bits.join(' '));
|
|
542
|
+
}
|
|
543
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claimed-tag-only attribution (R3).
|
|
3
|
+
*
|
|
4
|
+
* A write is claimed-tag-only when it is HTTP, the door has no grant id, and
|
|
5
|
+
* the source tag is a caller claim (declared, legacy, or auto). A bound login
|
|
6
|
+
* tag and a sub-key are credentials. Stdio is the local door and is not this path.
|
|
7
|
+
*
|
|
8
|
+
* EMET_CLAIMED_TAG_KILL_DATE (YYYY-MM-DD, UTC) is the owner's date. Before that day
|
|
9
|
+
* the write is kept and the receipt warns. On that day and after, the write
|
|
10
|
+
* is refused. Unset uses PROPOSED_CLAIMED_TAG_KILL_DATE.
|
|
11
|
+
*
|
|
12
|
+
* The traffic counter is this process. Railway EMET is one long-lived process.
|
|
13
|
+
* It is not a backfill of older rows.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { setting } from './env.js';
|
|
17
|
+
import { ValidationError as EmetValidationError } from './validation.js';
|
|
18
|
+
import { chooserBinding } from './deep-links.js';
|
|
19
|
+
|
|
20
|
+
export const PROPOSED_CLAIMED_TAG_KILL_DATE = '2026-12-15';
|
|
21
|
+
export const CLAIMED_TAG_WINDOW_DAYS = 7;
|
|
22
|
+
|
|
23
|
+
const CLAIMED_FROM = new Set(['declared', 'legacy', 'auto']);
|
|
24
|
+
const ONBOARDING = 'keyed link, then owner sign-in, then assign tag, then initialize';
|
|
25
|
+
const events = [];
|
|
26
|
+
|
|
27
|
+
let invalidKillWarned = '';
|
|
28
|
+
|
|
29
|
+
export function _resetClaimedTagForTests() {
|
|
30
|
+
events.length = 0;
|
|
31
|
+
invalidKillWarned = '';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The date in force, and whether the owner's setting was usable.
|
|
36
|
+
* A value that is not YYYY-MM-DD does not move the date. It is reported
|
|
37
|
+
* (kill_date_invalid on claimed_tag_traffic) and warned once per distinct value.
|
|
38
|
+
*/
|
|
39
|
+
export function claimedTagKillSetting() {
|
|
40
|
+
const raw = setting('CLAIMED_TAG_KILL_DATE');
|
|
41
|
+
const text = typeof raw === 'string' ? raw.trim() : '';
|
|
42
|
+
if (!text) {
|
|
43
|
+
return { kill_date: PROPOSED_CLAIMED_TAG_KILL_DATE, source: 'proposed', invalid: false, raw: null };
|
|
44
|
+
}
|
|
45
|
+
if (/^\d{4}-\d{2}-\d{2}$/.test(text)) {
|
|
46
|
+
return { kill_date: text, source: 'env', invalid: false, raw: text };
|
|
47
|
+
}
|
|
48
|
+
const shown = text.slice(0, 80);
|
|
49
|
+
if (invalidKillWarned !== shown) {
|
|
50
|
+
invalidKillWarned = shown;
|
|
51
|
+
console.error(`EMET_CLAIMED_TAG_KILL_DATE ${JSON.stringify(shown)} is not YYYY-MM-DD. The kill date stays ${PROPOSED_CLAIMED_TAG_KILL_DATE} until the setting is a date.`);
|
|
52
|
+
}
|
|
53
|
+
return { kill_date: PROPOSED_CLAIMED_TAG_KILL_DATE, source: 'invalid', invalid: true, raw: shown };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function claimedTagKillDate() {
|
|
57
|
+
return claimedTagKillSetting().kill_date;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function claimedTagKillReached(now = new Date(), kill = claimedTagKillDate()) {
|
|
61
|
+
return now.toISOString().slice(0, 10) >= kill;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** HTTP, no door grant, source taken from a claim. */
|
|
65
|
+
export function isClaimedTagOnly({ transport, grant_id, sourceFrom } = {}) {
|
|
66
|
+
return transport === 'http' && (grant_id === null || grant_id === undefined) && CLAIMED_FROM.has(sourceFrom);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function noteClaimedTag(row) {
|
|
70
|
+
events.push({
|
|
71
|
+
t: row.t || new Date().toISOString(),
|
|
72
|
+
caller: typeof row.caller === 'string' && row.caller.trim() ? row.caller.trim().slice(0, 80) : 'unregistered',
|
|
73
|
+
tool: typeof row.tool === 'string' && row.tool ? row.tool.slice(0, 80) : 'write',
|
|
74
|
+
grant_id: 'unknown',
|
|
75
|
+
source_basis: 'claimed'
|
|
76
|
+
});
|
|
77
|
+
const cutoff = Date.now() - 30 * 86400000;
|
|
78
|
+
while (events.length && Date.parse(events[0].t) < cutoff) events.shift();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Warn, or refuse once the kill date has arrived. Notes the attempt either way.
|
|
83
|
+
* Returns { claimed, warning }. Throws EMET-AUTH-040 when the path is closed.
|
|
84
|
+
*/
|
|
85
|
+
export function guardClaimedTag({ transport, grant_id, sourceFrom, caller, tool, now = new Date() } = {}) {
|
|
86
|
+
if (!isClaimedTagOnly({ transport, grant_id, sourceFrom })) return { claimed: false, warning: null };
|
|
87
|
+
const kill = claimedTagKillDate();
|
|
88
|
+
noteClaimedTag({ t: now.toISOString(), caller, tool });
|
|
89
|
+
if (claimedTagKillReached(now, kill)) {
|
|
90
|
+
// The coded throw stays `throw new ValidationError` so the error-code
|
|
91
|
+
// snapshot still sees EMET-AUTH-040. The local constructor returns that
|
|
92
|
+
// error with the chooser binding attached. `new` uses the returned object.
|
|
93
|
+
function ValidationError(field, message, options) {
|
|
94
|
+
const err = new EmetValidationError(field, message, options);
|
|
95
|
+
err.chooser = chooserBinding({ kind: 'claimed_tag', grantId: 'unknown', tag: caller, door: 'guest' });
|
|
96
|
+
return err;
|
|
97
|
+
}
|
|
98
|
+
throw new ValidationError(
|
|
99
|
+
'source',
|
|
100
|
+
`This write is attributed only by a claimed source tag, and that path ended on ${kill}. A write needs a credential: ${ONBOARDING}. Nothing was written.`,
|
|
101
|
+
{ code: 'EMET-AUTH-040' }
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
claimed: true,
|
|
106
|
+
warning: `Claimed source tag only (no grant). This path warns until ${kill} and is refused on that date. A write needs a credential: ${ONBOARDING}.`
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Remaining claimed-tag attempts in the window, for emet_status. */
|
|
111
|
+
export function claimedTagTraffic(now = new Date()) {
|
|
112
|
+
const days = CLAIMED_TAG_WINDOW_DAYS;
|
|
113
|
+
const since = now.getTime() - days * 86400000;
|
|
114
|
+
const callers = new Map();
|
|
115
|
+
let count = 0;
|
|
116
|
+
for (const row of events) {
|
|
117
|
+
const t = Date.parse(row.t);
|
|
118
|
+
if (!Number.isFinite(t) || t < since) continue;
|
|
119
|
+
count += 1;
|
|
120
|
+
callers.set(row.caller, (callers.get(row.caller) || 0) + 1);
|
|
121
|
+
}
|
|
122
|
+
const cfg = claimedTagKillSetting();
|
|
123
|
+
return {
|
|
124
|
+
window_days: days,
|
|
125
|
+
count,
|
|
126
|
+
callers: [...callers.entries()]
|
|
127
|
+
.map(([caller, n]) => ({ caller, count: n }))
|
|
128
|
+
.sort((a, b) => b.count - a.count || (a.caller < b.caller ? -1 : a.caller > b.caller ? 1 : 0)),
|
|
129
|
+
kill_date: cfg.kill_date,
|
|
130
|
+
proposed_kill_date: PROPOSED_CLAIMED_TAG_KILL_DATE,
|
|
131
|
+
// env: the owner's date parsed. default: unset, the proposed date.
|
|
132
|
+
// invalid_env: the setting was not YYYY-MM-DD, so the date did not move.
|
|
133
|
+
kill_date_source: cfg.source === 'env' ? 'env' : cfg.source === 'invalid' ? 'invalid_env' : 'default',
|
|
134
|
+
kill_date_invalid: cfg.invalid,
|
|
135
|
+
kill_date_raw: cfg.raw,
|
|
136
|
+
// This process only. Not a count of older rows.
|
|
137
|
+
since_process_start: true,
|
|
138
|
+
mode: claimedTagKillReached(now, cfg.kill_date) ? 'refuse' : 'warn'
|
|
139
|
+
};
|
|
140
|
+
}
|