@dreamforgestudiollc/emet 0.2.6 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +10 -0
- package/CHANGELOG.md +26 -1
- package/README.md +34 -8
- package/areas/emet.md +18 -0
- package/areas/garden.md +18 -0
- package/areas/health.md +18 -0
- package/areas/home.md +18 -0
- package/areas/learning.md +18 -0
- package/areas/state.md +18 -0
- package/docs/DEPLOY.md +32 -1
- package/docs/DEVELOPMENT-PRACTICES.md +26 -0
- package/docs/ERROR-CODES-SPEC.md +43 -0
- package/docs/ERROR-CODES.md +332 -0
- package/docs/GUIDED-SETUP.md +16 -0
- package/docs/PERMISSIONS.md +8 -5
- package/docs/ROADMAP.md +10 -10
- package/docs/SETUP.md +115 -12
- package/package.json +4 -2
- package/server.json +7 -3
- package/src/aleph.js +16 -10
- package/src/annotations.js +8 -3
- package/src/atlas-role.js +8 -3
- package/src/attribution.js +12 -12
- package/src/conformance.js +6 -4
- package/src/database.js +28 -12
- package/src/dispatch.js +33 -16
- package/src/error-codes.js +394 -0
- package/src/error-log.js +273 -0
- package/src/error-report.js +245 -0
- package/src/floor.js +6 -4
- package/src/gaps.js +2 -2
- package/src/gem-check.js +27 -26
- package/src/http-remote.js +2 -1
- package/src/index.js +1 -0
- package/src/invites.js +6 -5
- package/src/layers.js +8 -7
- package/src/mongo-connect.js +5 -0
- package/src/oauth-provider.js +28 -27
- package/src/pages.js +806 -0
- package/src/persons.js +2 -1
- package/src/provenance.js +10 -10
- package/src/rune-dispatch.js +10 -10
- package/src/session-graph.js +16 -15
- package/src/session.js +1 -1
- package/src/setup.js +21 -17
- package/src/startup-pages.js +3 -2
- package/src/startup-payload.js +3 -2
- package/src/subkey-store.js +3 -2
- package/src/tools.js +254 -177
- package/src/validation.js +61 -52
- package/src/version.js +1 -1
- package/templates/AREA.md +35 -0
- package/templates/INDEX.md +7 -6
- package/templates/PROCEDURE.md +1 -1
- package/templates/SEED.md +2 -2
- package/templates/STAGING.md +1 -1
- package/templates/THREAD.md +1 -1
package/src/gem-check.js
CHANGED
|
@@ -25,6 +25,7 @@ import { spawnSync } from 'node:child_process';
|
|
|
25
25
|
import { pathToFileURL } from 'node:url';
|
|
26
26
|
import { resolveModulePath } from './module-path.js';
|
|
27
27
|
import { refuseHostAccess, MAX_SOURCE_BYTES, runeSpecifierReason, runeExtensionReason } from './host-reach.js';
|
|
28
|
+
import { CodedError } from './error-codes.js';
|
|
28
29
|
|
|
29
30
|
export const SPEC_REVISION = '2026-10-12';
|
|
30
31
|
export const CHECK_IDS = Object.freeze([
|
|
@@ -114,7 +115,7 @@ function loadSchema(explicit) {
|
|
|
114
115
|
const text = fs.readFileSync(schemaPath(), 'utf8');
|
|
115
116
|
const parsed = JSON.parse(text);
|
|
116
117
|
if (!parsed || parsed.$id !== 'https://github.com/dreamforgestudiollc/EMET-GEMs/raw/main/gem.schema.json') {
|
|
117
|
-
throw new
|
|
118
|
+
throw new CodedError('schema id', { code: 'EMET-GEM-013' });
|
|
118
119
|
}
|
|
119
120
|
schemaCache = parsed;
|
|
120
121
|
return schemaCache;
|
|
@@ -134,7 +135,7 @@ export function parseStrictJson(text) {
|
|
|
134
135
|
}
|
|
135
136
|
function parse() {
|
|
136
137
|
skip();
|
|
137
|
-
if (i >= n) throw new
|
|
138
|
+
if (i >= n) throw new CodedError('unexpected end', { code: 'EMET-GEM-014' });
|
|
138
139
|
const c = s[i];
|
|
139
140
|
if (c === '{') return parseObject();
|
|
140
141
|
if (c === '[') return parseArray();
|
|
@@ -143,10 +144,10 @@ export function parseStrictJson(text) {
|
|
|
143
144
|
if (c === 'f') return atom('false', false);
|
|
144
145
|
if (c === 'n') return atom('null', null);
|
|
145
146
|
if (c === '-' || (c >= '0' && c <= '9')) return parseNumber();
|
|
146
|
-
throw new
|
|
147
|
+
throw new CodedError('unexpected character', { code: 'EMET-GEM-015' });
|
|
147
148
|
}
|
|
148
149
|
function atom(word, value) {
|
|
149
|
-
if (s.slice(i, i + word.length) !== word) throw new
|
|
150
|
+
if (s.slice(i, i + word.length) !== word) throw new CodedError('unexpected token', { code: 'EMET-GEM-016' });
|
|
150
151
|
i += word.length;
|
|
151
152
|
return value;
|
|
152
153
|
}
|
|
@@ -155,22 +156,22 @@ export function parseStrictJson(text) {
|
|
|
155
156
|
if (s[i] === '-') i++;
|
|
156
157
|
if (s[i] === '0') i++;
|
|
157
158
|
else if (s[i] >= '1' && s[i] <= '9') { while (i < n && s[i] >= '0' && s[i] <= '9') i++; }
|
|
158
|
-
else throw new
|
|
159
|
+
else throw new CodedError('bad number', { code: 'EMET-GEM-017' });
|
|
159
160
|
if (i < n && s[i] === '.') {
|
|
160
161
|
i++;
|
|
161
|
-
if (i >= n || s[i] < '0' || s[i] > '9') throw new
|
|
162
|
+
if (i >= n || s[i] < '0' || s[i] > '9') throw new CodedError('bad number', { code: 'EMET-GEM-017' });
|
|
162
163
|
while (i < n && s[i] >= '0' && s[i] <= '9') i++;
|
|
163
164
|
}
|
|
164
165
|
if (i < n && (s[i] === 'e' || s[i] === 'E')) {
|
|
165
166
|
i++;
|
|
166
167
|
if (s[i] === '+' || s[i] === '-') i++;
|
|
167
|
-
if (i >= n || s[i] < '0' || s[i] > '9') throw new
|
|
168
|
+
if (i >= n || s[i] < '0' || s[i] > '9') throw new CodedError('bad number', { code: 'EMET-GEM-017' });
|
|
168
169
|
while (i < n && s[i] >= '0' && s[i] <= '9') i++;
|
|
169
170
|
}
|
|
170
171
|
const lit = s.slice(start, i);
|
|
171
|
-
if (/^0\d/.test(lit) || /^-0\d/.test(lit)) throw new
|
|
172
|
+
if (/^0\d/.test(lit) || /^-0\d/.test(lit)) throw new CodedError('bad number', { code: 'EMET-GEM-017' });
|
|
172
173
|
const num = JSON.parse(lit);
|
|
173
|
-
if (typeof num !== 'number' || !Number.isFinite(num)) throw new
|
|
174
|
+
if (typeof num !== 'number' || !Number.isFinite(num)) throw new CodedError('bad number', { code: 'EMET-GEM-017' });
|
|
174
175
|
return num;
|
|
175
176
|
}
|
|
176
177
|
function parseString() {
|
|
@@ -187,14 +188,14 @@ export function parseStrictJson(text) {
|
|
|
187
188
|
i += 6;
|
|
188
189
|
continue;
|
|
189
190
|
}
|
|
190
|
-
throw new
|
|
191
|
+
throw new CodedError('bad escape', { code: 'EMET-GEM-018' });
|
|
191
192
|
}
|
|
192
193
|
if (c === '"') { i++; return out; }
|
|
193
|
-
if (c < ' ') throw new
|
|
194
|
+
if (c < ' ') throw new CodedError('raw control in string', { code: 'EMET-GEM-019' });
|
|
194
195
|
out += c;
|
|
195
196
|
i++;
|
|
196
197
|
}
|
|
197
|
-
throw new
|
|
198
|
+
throw new CodedError('unterminated string', { code: 'EMET-GEM-020' });
|
|
198
199
|
}
|
|
199
200
|
function parseArray() {
|
|
200
201
|
i++;
|
|
@@ -204,11 +205,11 @@ export function parseStrictJson(text) {
|
|
|
204
205
|
while (i < n) {
|
|
205
206
|
arr.push(parse());
|
|
206
207
|
skip();
|
|
207
|
-
if (s[i] === ',') { i++; skip(); if (s[i] === ']') throw new
|
|
208
|
+
if (s[i] === ',') { i++; skip(); if (s[i] === ']') throw new CodedError('trailing comma', { code: 'EMET-GEM-021' }); continue; }
|
|
208
209
|
if (s[i] === ']') { i++; return arr; }
|
|
209
|
-
throw new
|
|
210
|
+
throw new CodedError('expected comma', { code: 'EMET-GEM-022' });
|
|
210
211
|
}
|
|
211
|
-
throw new
|
|
212
|
+
throw new CodedError('unterminated array', { code: 'EMET-GEM-023' });
|
|
212
213
|
}
|
|
213
214
|
function parseObject() {
|
|
214
215
|
i++;
|
|
@@ -218,27 +219,27 @@ export function parseStrictJson(text) {
|
|
|
218
219
|
if (s[i] === '}') { i++; return obj; }
|
|
219
220
|
while (i < n) {
|
|
220
221
|
skip();
|
|
221
|
-
if (s[i] !== '"') throw new
|
|
222
|
+
if (s[i] !== '"') throw new CodedError('expected key', { code: 'EMET-GEM-024' });
|
|
222
223
|
const key = parseString();
|
|
223
|
-
if (seen.has(key)) throw new
|
|
224
|
+
if (seen.has(key)) throw new CodedError('duplicate key', { code: 'EMET-GEM-025' });
|
|
224
225
|
seen.add(key);
|
|
225
|
-
if (key === '__proto__' || key === 'constructor' || key === 'prototype') throw new
|
|
226
|
+
if (key === '__proto__' || key === 'constructor' || key === 'prototype') throw new CodedError('forbidden key', { code: 'EMET-GEM-026' });
|
|
226
227
|
skip();
|
|
227
|
-
if (s[i] !== ':') throw new
|
|
228
|
+
if (s[i] !== ':') throw new CodedError('expected colon', { code: 'EMET-GEM-027' });
|
|
228
229
|
i++;
|
|
229
230
|
const value = parse();
|
|
230
231
|
Object.defineProperty(obj, key, { value, enumerable: true, writable: true, configurable: true });
|
|
231
232
|
skip();
|
|
232
|
-
if (s[i] === ',') { i++; skip(); if (s[i] === '}') throw new
|
|
233
|
+
if (s[i] === ',') { i++; skip(); if (s[i] === '}') throw new CodedError('trailing comma', { code: 'EMET-GEM-021' }); continue; }
|
|
233
234
|
if (s[i] === '}') { i++; return obj; }
|
|
234
|
-
throw new
|
|
235
|
+
throw new CodedError('expected comma', { code: 'EMET-GEM-022' });
|
|
235
236
|
}
|
|
236
|
-
throw new
|
|
237
|
+
throw new CodedError('unterminated object', { code: 'EMET-GEM-028' });
|
|
237
238
|
}
|
|
238
|
-
if (s.charCodeAt(0) === 0xfeff) throw new
|
|
239
|
+
if (s.charCodeAt(0) === 0xfeff) throw new CodedError('bom', { code: 'EMET-GEM-029' });
|
|
239
240
|
const value = parse();
|
|
240
241
|
skip();
|
|
241
|
-
if (i !== n) throw new
|
|
242
|
+
if (i !== n) throw new CodedError('trailing data', { code: 'EMET-GEM-030' });
|
|
242
243
|
return value;
|
|
243
244
|
}
|
|
244
245
|
|
|
@@ -252,7 +253,7 @@ function jcs(value) {
|
|
|
252
253
|
const t = typeof value;
|
|
253
254
|
if (t === 'boolean') return value ? 'true' : 'false';
|
|
254
255
|
if (t === 'number') {
|
|
255
|
-
if (!Number.isSafeInteger(value)) throw new
|
|
256
|
+
if (!Number.isSafeInteger(value)) throw new CodedError('number is not a safe integer', { code: 'EMET-GEM-031' });
|
|
256
257
|
return JSON.stringify(value);
|
|
257
258
|
}
|
|
258
259
|
if (t === 'string') return JSON.stringify(value);
|
|
@@ -261,7 +262,7 @@ function jcs(value) {
|
|
|
261
262
|
const keys = Object.keys(value).sort();
|
|
262
263
|
return '{' + keys.map((k) => JSON.stringify(k) + ':' + jcs(value[k])).join(',') + '}';
|
|
263
264
|
}
|
|
264
|
-
throw new
|
|
265
|
+
throw new CodedError('unsupported value', { code: 'EMET-GEM-032' });
|
|
265
266
|
}
|
|
266
267
|
|
|
267
268
|
function cmpVer(a, b) {
|
package/src/http-remote.js
CHANGED
|
@@ -121,7 +121,7 @@ function buildServer() {
|
|
|
121
121
|
} catch (e) {
|
|
122
122
|
if (e && e.attributionRefusal) {
|
|
123
123
|
const { ValidationError } = await import('./validation.js');
|
|
124
|
-
return actorStore.run(actor, () => t.handleError(new ValidationError('source', e.message), name, logger));
|
|
124
|
+
return actorStore.run(actor, () => t.handleError(new ValidationError('source', e.message, { code: 'EMET-AUTH-039' }), name, logger));
|
|
125
125
|
}
|
|
126
126
|
throw e;
|
|
127
127
|
}
|
|
@@ -310,4 +310,5 @@ app.post('/mcp', requireBearerAuth({ verifier: provider, resourceMetadataUrl: PR
|
|
|
310
310
|
catch (e) { console.error('[emet] GEM socket failed closed'); }
|
|
311
311
|
app.listen(PORT, HOST, () => console.error(`[emet] listening ${PUBLIC_URL} (bind ${HOST}:${PORT}); /mcp OAuth-protected; PRM ${PRM_URL}`));
|
|
312
312
|
import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => console.error(`[emet] ${msg}`))).catch(() => console.error('[emet] sub-key flag-off sweep failed'));
|
|
313
|
+
import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
|
|
313
314
|
})();
|
package/src/index.js
CHANGED
|
@@ -262,6 +262,7 @@ async function main() {
|
|
|
262
262
|
catch (e) { logger.error('GEM socket failed closed', { error: e && e.message }); }
|
|
263
263
|
|
|
264
264
|
import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => logger.error(msg))).catch((e) => logger.error('sub-key flag-off sweep failed', { error: e && e.message }));
|
|
265
|
+
import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
|
|
265
266
|
|
|
266
267
|
const startupDurationMs = Date.now() - startTime;
|
|
267
268
|
|
package/src/invites.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { slugPersonId } from './persons.js';
|
|
3
3
|
import { setting } from './env.js';
|
|
4
|
+
import { CodedError } from './error-codes.js';
|
|
4
5
|
|
|
5
6
|
const COLLECTION = 'invites';
|
|
6
7
|
|
|
@@ -29,13 +30,13 @@ export const DOORS_FROZEN_REASON =
|
|
|
29
30
|
|
|
30
31
|
export async function createInvite(db, { created_by, display_name, scopes = ['emet.read'], days = 14, source_tag = null } = {}) {
|
|
31
32
|
if (INVITES_FROZEN) {
|
|
32
|
-
const err = new
|
|
33
|
+
const err = new CodedError(INVITES_FROZEN_REASON, { code: 'EMET-AUTH-030' });
|
|
33
34
|
err.code = 'INVITES_FROZEN';
|
|
34
35
|
throw err;
|
|
35
36
|
}
|
|
36
37
|
const requested = Array.isArray(scopes) && scopes.length ? scopes : ['emet.read'];
|
|
37
38
|
if (requested.length !== 1 || requested[0] !== 'emet.read') {
|
|
38
|
-
const err = new
|
|
39
|
+
const err = new CodedError('A guest invite accepts only emet.read', { code: 'EMET-AUTH-031' });
|
|
39
40
|
err.code = 'GUEST_SCOPE';
|
|
40
41
|
throw err;
|
|
41
42
|
}
|
|
@@ -59,7 +60,7 @@ export async function createInvite(db, { created_by, display_name, scopes = ['em
|
|
|
59
60
|
|
|
60
61
|
export async function createMemberAccess(db, { created_by, display_name, days = 14, source_tag = null } = {}) {
|
|
61
62
|
if (MEMBER_ACCESS_FROZEN) {
|
|
62
|
-
const err = new
|
|
63
|
+
const err = new CodedError(MEMBER_ACCESS_FROZEN_REASON, { code: 'EMET-AUTH-034' });
|
|
63
64
|
err.code = 'MEMBER_ACCESS_FROZEN';
|
|
64
65
|
throw err;
|
|
65
66
|
}
|
|
@@ -109,7 +110,7 @@ export async function allocateGuestPersonId(persons, display_name) {
|
|
|
109
110
|
const id = `${base}-${n}`;
|
|
110
111
|
if (!(await taken(id))) return id;
|
|
111
112
|
}
|
|
112
|
-
throw new
|
|
113
|
+
throw new CodedError('could not allocate a person id for this invite', { code: 'EMET-AUTH-001' });
|
|
113
114
|
}
|
|
114
115
|
|
|
115
116
|
function claimedRow(result) {
|
|
@@ -161,7 +162,7 @@ export async function redeemInvite(db, code) {
|
|
|
161
162
|
if (!(e && (e.code === 11000 || /duplicate/i.test(String(e.message || ''))))) throw e;
|
|
162
163
|
}
|
|
163
164
|
}
|
|
164
|
-
if (!saved) throw new
|
|
165
|
+
if (!saved) throw new CodedError('could not allocate a person id for this invite', { code: 'EMET-AUTH-001' });
|
|
165
166
|
await col.updateOne({ digest }, { $set: { person_id } });
|
|
166
167
|
return { ok: true, person_id, scopes, display_name: claimed.display_name || row.display_name, door, source_tag: claimed.source_tag || row.source_tag || null };
|
|
167
168
|
}
|
package/src/layers.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { CodedError } from './error-codes.js';
|
|
1
2
|
/**
|
|
2
3
|
* EMET - Enduring Memory & Epistemic Tiers
|
|
3
4
|
* Copyright (c) 2026 Dreamforge Studio LLC
|
|
@@ -238,7 +239,7 @@ export function resolveLayer(name) {
|
|
|
238
239
|
export function bandFor(layer) {
|
|
239
240
|
const entry = LAYER_CHARTER[layer];
|
|
240
241
|
if (!entry || !Array.isArray(entry.importance_range)) {
|
|
241
|
-
throw new
|
|
242
|
+
throw new CodedError(`Unknown layer '${layer}'. Must be one of: ${LAYERS.join(', ')}`, { code: 'EMET-MEM-001' });
|
|
242
243
|
}
|
|
243
244
|
const [min, max] = entry.importance_range;
|
|
244
245
|
// Rounded so 0.3 + 0.6 reads as 0.45, not 0.44999999999999996.
|
|
@@ -304,20 +305,20 @@ export function resolveImportance(layer, raw, extras = {}) {
|
|
|
304
305
|
} else if (IMPORTANCE_DEGREES.includes(parts[0])) {
|
|
305
306
|
degree = parts[0];
|
|
306
307
|
} else {
|
|
307
|
-
throw new
|
|
308
|
+
throw new CodedError(
|
|
308
309
|
`Unknown importance bucket '${raw}'. Use one of: ${Object.keys(IMPORTANCE_BUCKETS).join(', ')}` +
|
|
309
310
|
` (optional :low|:mid|:high).`
|
|
310
|
-
);
|
|
311
|
+
, { code: 'EMET-MEM-002' });
|
|
311
312
|
}
|
|
312
313
|
}
|
|
313
314
|
|
|
314
315
|
if (bucket && !IMPORTANCE_BUCKETS[bucket]) {
|
|
315
|
-
throw new
|
|
316
|
+
throw new CodedError(
|
|
316
317
|
`Unknown importance bucket '${bucket}'. Use one of: ${Object.keys(IMPORTANCE_BUCKETS).join(', ')}`
|
|
317
|
-
);
|
|
318
|
+
, { code: 'EMET-MEM-003' });
|
|
318
319
|
}
|
|
319
320
|
if (degree && !IMPORTANCE_DEGREES.includes(degree)) {
|
|
320
|
-
throw new
|
|
321
|
+
throw new CodedError(`Unknown importance degree '${degree}'. Use low, mid, or high.`, { code: 'EMET-MEM-004' });
|
|
321
322
|
}
|
|
322
323
|
|
|
323
324
|
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
|
@@ -362,7 +363,7 @@ export function resolveImportance(layer, raw, extras = {}) {
|
|
|
362
363
|
export function policyFor(layer) {
|
|
363
364
|
const entry = LAYER_CHARTER[layer];
|
|
364
365
|
if (!entry) {
|
|
365
|
-
throw new
|
|
366
|
+
throw new CodedError(`Unknown layer '${layer}'. Must be one of: ${LAYERS.join(', ')}`, { code: 'EMET-MEM-001' });
|
|
366
367
|
}
|
|
367
368
|
return {
|
|
368
369
|
revisable: entry.revisable,
|
package/src/mongo-connect.js
CHANGED
|
@@ -36,6 +36,11 @@ let sharedToken = null;
|
|
|
36
36
|
let sharedConnect = null;
|
|
37
37
|
|
|
38
38
|
/** The server's Mongo client, reused by stores that would otherwise connect per call. */
|
|
39
|
+
/** The client already opened for this process, or null. Does not connect. */
|
|
40
|
+
export function readySharedClient() {
|
|
41
|
+
return sharedClient;
|
|
42
|
+
}
|
|
43
|
+
|
|
39
44
|
export function bindSharedClient(client) {
|
|
40
45
|
if (!client) return;
|
|
41
46
|
sharedClient = client;
|
package/src/oauth-provider.js
CHANGED
|
@@ -43,6 +43,7 @@ import { COLLECTION_PREFIX } from './database.js';
|
|
|
43
43
|
import { setting } from './env.js';
|
|
44
44
|
import { InvalidGrantError, InvalidScopeError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
|
|
45
45
|
import { scopesNotGranted } from './scopes.js';
|
|
46
|
+
import { CodedError, assignCode } from './error-codes.js';
|
|
46
47
|
|
|
47
48
|
const CODE_TTL_MS = 5 * 60 * 1000; // authorization codes: 5 minutes
|
|
48
49
|
const ACCESS_TTL_S = 60 * 60; // access tokens: 1 hour
|
|
@@ -122,17 +123,17 @@ export function isCimdClientId(clientId) {
|
|
|
122
123
|
*/
|
|
123
124
|
export function validateCimdDocument(doc, url) {
|
|
124
125
|
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
|
|
125
|
-
throw new
|
|
126
|
+
throw new CodedError('CIMD document must be a JSON object', { code: 'EMET-AUTH-002' });
|
|
126
127
|
}
|
|
127
128
|
if (doc.client_id !== url) {
|
|
128
|
-
throw new
|
|
129
|
+
throw new CodedError(`CIMD document client_id does not match its URL (expected ${url})`, { code: 'EMET-AUTH-003' });
|
|
129
130
|
}
|
|
130
131
|
if (!Array.isArray(doc.redirect_uris) || doc.redirect_uris.length === 0 || !doc.redirect_uris.every(r => typeof r === 'string' && r.length > 0)) {
|
|
131
|
-
throw new
|
|
132
|
+
throw new CodedError('CIMD document must carry a non-empty redirect_uris array of strings', { code: 'EMET-AUTH-004' });
|
|
132
133
|
}
|
|
133
134
|
const method = doc.token_endpoint_auth_method === undefined ? 'none' : doc.token_endpoint_auth_method;
|
|
134
135
|
if (method !== 'none') {
|
|
135
|
-
throw new
|
|
136
|
+
throw new CodedError(`CIMD clients are public; token_endpoint_auth_method must be "none" (got ${method})`, { code: 'EMET-AUTH-005' });
|
|
136
137
|
}
|
|
137
138
|
const { client_secret, client_secret_expires_at, ...rest } = doc;
|
|
138
139
|
return {
|
|
@@ -216,17 +217,17 @@ export async function assertCimdTargetPublic(url, lookup) {
|
|
|
216
217
|
const u = new URL(url);
|
|
217
218
|
const host = u.hostname.replace(/^\[|\]$/g, '');
|
|
218
219
|
if (!host || host === 'localhost' || host.endsWith('.localhost') || host === 'metadata.google.internal') {
|
|
219
|
-
throw new
|
|
220
|
+
throw new CodedError('CIMD host is not a public address', { code: 'EMET-AUTH-006' });
|
|
220
221
|
}
|
|
221
|
-
if (isBlockedCimdAddress(host)) throw new
|
|
222
|
+
if (isBlockedCimdAddress(host)) throw new CodedError('CIMD host is not a public address', { code: 'EMET-AUTH-006' });
|
|
222
223
|
const fn = lookup || dnsPromises.lookup;
|
|
223
224
|
const found = await fn(host, { all: true, verbatim: true });
|
|
224
225
|
const list = Array.isArray(found) ? found : (found ? [found] : []);
|
|
225
|
-
if (!list.length) throw new
|
|
226
|
+
if (!list.length) throw new CodedError('CIMD host did not resolve', { code: 'EMET-AUTH-007' });
|
|
226
227
|
const checked = [];
|
|
227
228
|
for (const item of list) {
|
|
228
229
|
const address = typeof item === 'string' ? item : item && item.address;
|
|
229
|
-
if (isBlockedCimdAddress(address)) throw new
|
|
230
|
+
if (isBlockedCimdAddress(address)) throw new CodedError('CIMD host resolves to a blocked address', { code: 'EMET-AUTH-008' });
|
|
230
231
|
const family = (item && item.family === 6) || String(address).includes(':') ? 6 : 4;
|
|
231
232
|
checked.push({ address, family });
|
|
232
233
|
}
|
|
@@ -535,7 +536,7 @@ export class MongoOAuthProvider {
|
|
|
535
536
|
|
|
536
537
|
async _fetchCimdDocument(url) {
|
|
537
538
|
const host = new URL(url).hostname;
|
|
538
|
-
if (!takeCimdFetchSlot(host)) throw new
|
|
539
|
+
if (!takeCimdFetchSlot(host)) throw new CodedError('CIMD fetch rate limit', { code: 'EMET-AUTH-009' });
|
|
539
540
|
const checked = await assertCimdTargetPublic(url, this._lookup);
|
|
540
541
|
const chosen = checked[0];
|
|
541
542
|
const controller = new AbortController();
|
|
@@ -550,13 +551,13 @@ export class MongoOAuthProvider {
|
|
|
550
551
|
const res = this._fetch
|
|
551
552
|
? await this._fetch(url, init)
|
|
552
553
|
: await pinnedHttpsGet(url, init, this._https);
|
|
553
|
-
if (!res || !res.ok) throw new
|
|
554
|
+
if (!res || !res.ok) throw new CodedError(`HTTP ${res ? res.status : 'no response'}`, { code: 'EMET-AUTH-010' });
|
|
554
555
|
const text = await res.text();
|
|
555
556
|
if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > CIMD_MAX_BYTES) {
|
|
556
|
-
throw new
|
|
557
|
+
throw new CodedError(`document exceeds ${CIMD_MAX_BYTES} bytes`, { code: 'EMET-AUTH-011' });
|
|
557
558
|
}
|
|
558
559
|
try { return JSON.parse(text); }
|
|
559
|
-
catch { throw new
|
|
560
|
+
catch { throw new CodedError('document is not valid JSON', { code: 'EMET-AUTH-012' }); }
|
|
560
561
|
} finally {
|
|
561
562
|
clearTimeout(timer);
|
|
562
563
|
}
|
|
@@ -635,7 +636,7 @@ export class MongoOAuthProvider {
|
|
|
635
636
|
|
|
636
637
|
async challengeForAuthorizationCode(client, authorizationCode) {
|
|
637
638
|
const doc = await this.col('codes').findOne({ code: tokenDigest(authorizationCode), client_id: client.client_id });
|
|
638
|
-
if (!doc) throw new InvalidGrantError('this authorization code is not recognised - start the connection again');
|
|
639
|
+
if (!doc) throw assignCode(new InvalidGrantError('this authorization code is not recognised - start the connection again'), 'EMET-AUTH-013');
|
|
639
640
|
return doc.code_challenge;
|
|
640
641
|
}
|
|
641
642
|
|
|
@@ -643,15 +644,15 @@ export class MongoOAuthProvider {
|
|
|
643
644
|
const codes = this.col('codes');
|
|
644
645
|
const digest = tokenDigest(authorizationCode);
|
|
645
646
|
const existing = await codes.findOne({ code: digest, client_id: client.client_id });
|
|
646
|
-
if (!existing) throw new InvalidGrantError('this authorization code is not recognised - start the connection again');
|
|
647
|
-
if (existing.expiresAtMs < Date.now()) throw new InvalidGrantError('this authorization code has expired - start the connection again');
|
|
648
|
-
if (redirectUri && existing.redirect_uri && redirectUri !== existing.redirect_uri) throw new InvalidGrantError('redirect_uri does not match the one this code was issued for');
|
|
647
|
+
if (!existing) throw assignCode(new InvalidGrantError('this authorization code is not recognised - start the connection again'), 'EMET-AUTH-013');
|
|
648
|
+
if (existing.expiresAtMs < Date.now()) throw assignCode(new InvalidGrantError('this authorization code has expired - start the connection again'), 'EMET-AUTH-014');
|
|
649
|
+
if (redirectUri && existing.redirect_uri && redirectUri !== existing.redirect_uri) throw assignCode(new InvalidGrantError('redirect_uri does not match the one this code was issued for'), 'EMET-AUTH-015');
|
|
649
650
|
const claimed = await codes.findOneAndUpdate(
|
|
650
651
|
{ code: digest, client_id: client.client_id, used: false },
|
|
651
652
|
{ $set: { used: true } }
|
|
652
653
|
);
|
|
653
654
|
const doc = claimed && Object.prototype.hasOwnProperty.call(claimed, 'value') ? claimed.value : claimed;
|
|
654
|
-
if (!doc) throw new InvalidGrantError('this authorization code has already been used - start the connection again');
|
|
655
|
+
if (!doc) throw assignCode(new InvalidGrantError('this authorization code has already been used - start the connection again'), 'EMET-AUTH-016');
|
|
655
656
|
return this._issueTokens(client.client_id, doc.scopes || [], doc.resource || (resource ? resource.href : null), doc.subject || null, doc.issued_via || null, null, doc.source_tag || null);
|
|
656
657
|
}
|
|
657
658
|
|
|
@@ -668,21 +669,21 @@ export class MongoOAuthProvider {
|
|
|
668
669
|
// Every refusal here is an OAuth error the SDK maps to 400 invalid_grant
|
|
669
670
|
// (RFC 6749 section 5.2). A plain Error became a 500 server_error, which
|
|
670
671
|
// told the client the server was broken instead of "sign in again".
|
|
671
|
-
if (!rt) throw new InvalidGrantError('this refresh token is not recognised (it may have been revoked, or issued to another client) - reconnect to sign in again');
|
|
672
|
+
if (!rt) throw assignCode(new InvalidGrantError('this refresh token is not recognised (it may have been revoked, or issued to another client) - reconnect to sign in again'), 'EMET-AUTH-017');
|
|
672
673
|
const nowS = Math.floor(Date.now() / 1000);
|
|
673
|
-
if (rt.expiresAt && rt.expiresAt < nowS) throw new InvalidGrantError('this refresh token has expired - reconnect to sign in again');
|
|
674
|
+
if (rt.expiresAt && rt.expiresAt < nowS) throw assignCode(new InvalidGrantError('this refresh token has expired - reconnect to sign in again'), 'EMET-AUTH-018');
|
|
674
675
|
// A token issued before source tags were stored must not mint another
|
|
675
676
|
// token with an empty tag. The client signs in again; the new consent
|
|
676
677
|
// binds a registered tag. Expiry is reported first, so an expired
|
|
677
678
|
// legacy token still says it has expired.
|
|
678
679
|
if (!rt.source_tag) {
|
|
679
|
-
throw new InvalidGrantError('this login has no source tag bound. Sign in again so the new consent binds a registered tag.');
|
|
680
|
+
throw assignCode(new InvalidGrantError('this login has no source tag bound. Sign in again so the new consent binds a registered tag.'), 'EMET-AUTH-019');
|
|
680
681
|
}
|
|
681
682
|
if (typeof rt.rotated_at === 'number') {
|
|
682
683
|
const withinGrace = (nowS - rt.rotated_at) <= REFRESH_ROTATION_GRACE_S && rt.grace_replacement;
|
|
683
684
|
if (withinGrace) return { ...rt.grace_replacement };
|
|
684
685
|
await this._revokeFamily(rt);
|
|
685
|
-
throw new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again');
|
|
686
|
+
throw assignCode(new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again'), 'EMET-AUTH-020');
|
|
686
687
|
}
|
|
687
688
|
// R6: a token minted from an invite stops refreshing while invites are
|
|
688
689
|
// frozen, so a re-freeze ends it within one access-token lifetime instead
|
|
@@ -692,10 +693,10 @@ export class MongoOAuthProvider {
|
|
|
692
693
|
// likewise against EMET_INVITES.
|
|
693
694
|
const door = await this._tokenDoor(rt);
|
|
694
695
|
if (door === 'member' && await this._memberAccessIsFrozen()) {
|
|
695
|
-
throw new InvalidGrantError('this login came from EMET Member Access, and member access is off on this install - it can no longer be refreshed');
|
|
696
|
+
throw assignCode(new InvalidGrantError('this login came from EMET Member Access, and member access is off on this install - it can no longer be refreshed'), 'EMET-AUTH-021');
|
|
696
697
|
}
|
|
697
698
|
if (door === 'guest' && await this._invitesAreFrozen()) {
|
|
698
|
-
throw new InvalidGrantError('this login came from an invite, and invites are off on this install - it can no longer be refreshed');
|
|
699
|
+
throw assignCode(new InvalidGrantError('this login came from an invite, and invites are off on this install - it can no longer be refreshed'), 'EMET-AUTH-022');
|
|
699
700
|
}
|
|
700
701
|
// Defect 1: a refresh keeps or narrows the scopes granted, never widens
|
|
701
702
|
// them (RFC 6749 section 6: a requested scope not originally granted is
|
|
@@ -704,7 +705,7 @@ export class MongoOAuthProvider {
|
|
|
704
705
|
const granted = rt.scopes || [];
|
|
705
706
|
const wider = scopesNotGranted(granted, requested);
|
|
706
707
|
if (wider.length) {
|
|
707
|
-
throw new InvalidScopeError(`a refresh cannot widen scope: ${wider.join(', ')} was not granted (granted: ${granted.join(', ')})`);
|
|
708
|
+
throw assignCode(new InvalidScopeError(`a refresh cannot widen scope: ${wider.join(', ')} was not granted (granted: ${granted.join(', ')})`), 'EMET-AUTH-023');
|
|
708
709
|
}
|
|
709
710
|
const useScopes = requested.length ? requested : granted;
|
|
710
711
|
const family = rt.family || randTok(16);
|
|
@@ -722,7 +723,7 @@ export class MongoOAuthProvider {
|
|
|
722
723
|
return { ...fresh.grace_replacement };
|
|
723
724
|
}
|
|
724
725
|
await this._revokeFamily(fresh || rt);
|
|
725
|
-
throw new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again');
|
|
726
|
+
throw assignCode(new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again'), 'EMET-AUTH-020');
|
|
726
727
|
}
|
|
727
728
|
return out;
|
|
728
729
|
}
|
|
@@ -817,8 +818,8 @@ export class MongoOAuthProvider {
|
|
|
817
818
|
// Error here became a 500 server_error for every expired or revoked login.
|
|
818
819
|
// No double quotes in these messages: they are copied into that header.
|
|
819
820
|
const doc = await this._findToken(token, 'access');
|
|
820
|
-
if (!doc) throw new InvalidTokenError('this access token is not recognised (it may have been revoked or replaced) - sign in again');
|
|
821
|
-
if (doc.expiresAt && doc.expiresAt * 1000 < Date.now()) throw new InvalidTokenError('this access token has expired - refresh it or sign in again');
|
|
821
|
+
if (!doc) throw assignCode(new InvalidTokenError('this access token is not recognised (it may have been revoked or replaced) - sign in again'), 'EMET-AUTH-024');
|
|
822
|
+
if (doc.expiresAt && doc.expiresAt * 1000 < Date.now()) throw assignCode(new InvalidTokenError('this access token has expired - refresh it or sign in again'), 'EMET-AUTH-025');
|
|
822
823
|
return {
|
|
823
824
|
token,
|
|
824
825
|
clientId: doc.client_id,
|