@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/oauth-provider.js
CHANGED
|
@@ -44,16 +44,21 @@ 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
46
|
import { CodedError, assignCode } from './error-codes.js';
|
|
47
|
+
import { doorFromIssuedVia, grantIdFromFamily, logGrantId } from './grants.js';
|
|
48
|
+
import { credentialBlocked, currentHouseholdGeneration, refuseRotatedCredential } from './rotate.js';
|
|
49
|
+
import { owlCredentialBlocked, refuseOwlCredential } from './owl.js';
|
|
47
50
|
|
|
48
51
|
const CODE_TTL_MS = 5 * 60 * 1000; // authorization codes: 5 minutes
|
|
49
52
|
const ACCESS_TTL_S = 60 * 60; // access tokens: 1 hour
|
|
50
53
|
const REFRESH_TTL_S = 60 * 60 * 24 * 60; // refresh tokens: 60 days
|
|
51
54
|
const REFRESH_ROTATION_GRACE_S = 60; // a rotated refresh token stays usable this long
|
|
52
|
-
/** The marker on codes and tokens minted from an invite (
|
|
55
|
+
/** The marker on codes and tokens minted from an invite (guest door). */
|
|
53
56
|
export const INVITE_GRANT = 'invite';
|
|
54
57
|
// EMET Member Access tokens carry their own marker, so refresh can check the member flag, not the guest one.
|
|
55
58
|
export const MEMBER_GRANT = 'member';
|
|
56
|
-
|
|
59
|
+
/** Passphrase consents. Stored explicitly so a new owner token is not a legacy row. */
|
|
60
|
+
export const OWNER_GRANT = 'owner';
|
|
61
|
+
const STORED_DOORS = new Set([INVITE_GRANT, MEMBER_GRANT, OWNER_GRANT]);
|
|
57
62
|
|
|
58
63
|
/** How long a fetched Client ID Metadata Document is trusted before refetching. */
|
|
59
64
|
export const CIMD_TTL_MS = 60 * 60 * 1000; // 1 hour
|
|
@@ -622,14 +627,17 @@ export class MongoOAuthProvider {
|
|
|
622
627
|
|
|
623
628
|
/** Called by /oauth/approve AFTER a successful passphrase check. */
|
|
624
629
|
async createAuthorizationCode({ client_id, redirect_uri, code_challenge, scopes, resource, subject, issued_via, source_tag }) {
|
|
630
|
+
const draft = { client_id, clientId: client_id, source_tag };
|
|
631
|
+
if (await owlCredentialBlocked(this._getDb(), this.prefix, draft)) await refuseOwlCredential(draft, 'code');
|
|
625
632
|
const code = randTok(24);
|
|
626
633
|
await this.col('codes').insertOne({
|
|
627
634
|
code: tokenDigest(code), hashed: true, client_id, redirect_uri, code_challenge,
|
|
628
635
|
scopes: scopes || [], resource: resource || null,
|
|
629
636
|
subject: subject || null,
|
|
630
637
|
source_tag: source_tag || null,
|
|
631
|
-
...(
|
|
638
|
+
...(STORED_DOORS.has(issued_via) ? { issued_via } : {}),
|
|
632
639
|
expiresAtMs: Date.now() + CODE_TTL_MS, used: false, createdAt: new Date(),
|
|
640
|
+
rotation_generation: await currentHouseholdGeneration(this._getDb(), this.prefix)
|
|
633
641
|
});
|
|
634
642
|
return code;
|
|
635
643
|
}
|
|
@@ -645,6 +653,8 @@ export class MongoOAuthProvider {
|
|
|
645
653
|
const digest = tokenDigest(authorizationCode);
|
|
646
654
|
const existing = await codes.findOne({ code: digest, client_id: client.client_id });
|
|
647
655
|
if (!existing) throw assignCode(new InvalidGrantError('this authorization code is not recognised - start the connection again'), 'EMET-AUTH-013');
|
|
656
|
+
if (await owlCredentialBlocked(this._getDb(), this.prefix, existing)) await refuseOwlCredential(existing, 'code');
|
|
657
|
+
if (await credentialBlocked(this._getDb(), this.prefix, existing)) await refuseRotatedCredential(existing, 'code');
|
|
648
658
|
if (existing.expiresAtMs < Date.now()) throw assignCode(new InvalidGrantError('this authorization code has expired - start the connection again'), 'EMET-AUTH-014');
|
|
649
659
|
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');
|
|
650
660
|
const claimed = await codes.findOneAndUpdate(
|
|
@@ -670,6 +680,10 @@ export class MongoOAuthProvider {
|
|
|
670
680
|
// (RFC 6749 section 5.2). A plain Error became a 500 server_error, which
|
|
671
681
|
// told the client the server was broken instead of "sign in again".
|
|
672
682
|
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');
|
|
683
|
+
if (await owlCredentialBlocked(this._getDb(), this.prefix, rt)) await refuseOwlCredential(rt, 'refresh');
|
|
684
|
+
// Household rotation refuses before the 60-second lost-response grace.
|
|
685
|
+
// That grace is one client retry. It is not time left on a revoked grant.
|
|
686
|
+
if (await credentialBlocked(this._getDb(), this.prefix, rt)) await refuseRotatedCredential(rt, 'refresh');
|
|
673
687
|
const nowS = Math.floor(Date.now() / 1000);
|
|
674
688
|
if (rt.expiresAt && rt.expiresAt < nowS) throw assignCode(new InvalidGrantError('this refresh token has expired - reconnect to sign in again'), 'EMET-AUTH-018');
|
|
675
689
|
// A token issued before source tags were stored must not mint another
|
|
@@ -719,6 +733,7 @@ export class MongoOAuthProvider {
|
|
|
719
733
|
await tokens.deleteOne({ token: tokenDigest(out.access_token), kind: 'access' });
|
|
720
734
|
await tokens.deleteOne({ token: tokenDigest(out.refresh_token), kind: 'refresh' });
|
|
721
735
|
const fresh = await tokens.findOne({ _id: rt._id });
|
|
736
|
+
if (fresh && await credentialBlocked(this._getDb(), this.prefix, fresh)) await refuseRotatedCredential(fresh, 'refresh');
|
|
722
737
|
if (fresh && fresh.grace_replacement && typeof fresh.rotated_at === 'number' && (nowS - fresh.rotated_at) <= REFRESH_ROTATION_GRACE_S) {
|
|
723
738
|
return { ...fresh.grace_replacement };
|
|
724
739
|
}
|
|
@@ -728,6 +743,24 @@ export class MongoOAuthProvider {
|
|
|
728
743
|
return out;
|
|
729
744
|
}
|
|
730
745
|
|
|
746
|
+
/**
|
|
747
|
+
* End one grant. The grant id is that token family. This is not rotate-all:
|
|
748
|
+
* a bearer, `*`, or `all` is refused, and deletion stays on _revokeFamily.
|
|
749
|
+
*/
|
|
750
|
+
async revokeGrantById(grantId) {
|
|
751
|
+
const family = logGrantId(grantId);
|
|
752
|
+
if (family === 'none' || grantId === 'unknown' || grantId === '*' || grantId === 'all') {
|
|
753
|
+
return { ok: false, reason: 'one_grant' };
|
|
754
|
+
}
|
|
755
|
+
const db = typeof this._getDb === 'function' ? this._getDb() : null;
|
|
756
|
+
if (!db) return { ok: false, reason: 'unavailable' };
|
|
757
|
+
const row = await this.col('tokens').findOne({ family });
|
|
758
|
+
if (!row || grantIdFromFamily(row.family) !== family) return { ok: false, reason: 'missing' };
|
|
759
|
+
const door = doorFromIssuedVia(row.issued_via);
|
|
760
|
+
await this._revokeFamily(row);
|
|
761
|
+
return { ok: true, grant_id: family, door };
|
|
762
|
+
}
|
|
763
|
+
|
|
731
764
|
/** A reused refresh token outside the grace window ends every token in its family. */
|
|
732
765
|
async _revokeFamily(rt) {
|
|
733
766
|
const tokens = this.col('tokens');
|
|
@@ -755,10 +788,17 @@ export class MongoOAuthProvider {
|
|
|
755
788
|
* 'guest' (EMET Guest Access, issued_via 'invite'), or null (passphrase). A legacy token with no
|
|
756
789
|
* issued_via is judged by its subject's person row: role 'member' with door 'member' is a member,
|
|
757
790
|
* any other role 'member' is a guest (every such row before the member door was a guest).
|
|
791
|
+
* That person-row reading is for freeze checks only. verifyAccessToken stamps door from
|
|
792
|
+
* doorFromIssuedVia, so a missing issued_via stays null and is not guessed.
|
|
793
|
+
* See docs/proposals/EMET-0002-grant-doors.md §7.
|
|
758
794
|
*/
|
|
759
795
|
async _tokenDoor(rt) {
|
|
760
796
|
if (rt.issued_via === MEMBER_GRANT) return 'member';
|
|
761
797
|
if (rt.issued_via === INVITE_GRANT) return 'guest';
|
|
798
|
+
// Owner and any other explicit marker are not invite doors. Freeze checks
|
|
799
|
+
// stay on member and guest. A missing marker still falls through to the
|
|
800
|
+
// legacy person-role lookup below.
|
|
801
|
+
if (rt.issued_via === OWNER_GRANT) return null;
|
|
762
802
|
if (rt.issued_via !== undefined && rt.issued_via !== null) return null;
|
|
763
803
|
if (!rt.subject || rt.subject === 'owner') return null;
|
|
764
804
|
const person = await this._getDb().collection('persons').findOne({ person_id: rt.subject });
|
|
@@ -795,17 +835,22 @@ export class MongoOAuthProvider {
|
|
|
795
835
|
const now = Math.floor(Date.now() / 1000);
|
|
796
836
|
const subject = subjectOverride || await this._subject();
|
|
797
837
|
const fam = family || randTok(16);
|
|
838
|
+
const minted = { client_id: clientId, clientId, source_tag: sourceTag, family: fam };
|
|
839
|
+
if (await owlCredentialBlocked(this._getDb(), this.prefix, minted)) await refuseOwlCredential(minted, 'issue');
|
|
840
|
+
const rotation_generation = await currentHouseholdGeneration(this._getDb(), this.prefix);
|
|
798
841
|
// Only a door grant (guest 'invite' or 'member') is marked; passphrase rows keep today's shape.
|
|
799
|
-
const via =
|
|
842
|
+
const via = STORED_DOORS.has(issuedVia) ? { issued_via: issuedVia } : {};
|
|
800
843
|
const access = randTok(32);
|
|
801
844
|
await this.col('tokens').insertOne({
|
|
802
845
|
token: tokenDigest(access), hashed: true, kind: 'access', client_id: clientId, scopes, resource: resource || null,
|
|
803
846
|
subject, ...via, family: fam, source_tag: sourceTag || null, expiresAt: now + ACCESS_TTL_S, createdAt: new Date(),
|
|
847
|
+
rotation_generation
|
|
804
848
|
});
|
|
805
849
|
const refresh = randTok(32);
|
|
806
850
|
await this.col('tokens').insertOne({
|
|
807
851
|
token: tokenDigest(refresh), hashed: true, kind: 'refresh', client_id: clientId, scopes, resource: resource || null,
|
|
808
852
|
subject, ...via, family: fam, source_tag: sourceTag || null, expiresAt: now + REFRESH_TTL_S, createdAt: new Date(),
|
|
853
|
+
rotation_generation
|
|
809
854
|
});
|
|
810
855
|
const out = { access_token: access, token_type: 'bearer', expires_in: ACCESS_TTL_S, refresh_token: refresh };
|
|
811
856
|
if (scopes && scopes.length) out.scope = scopes.join(' ');
|
|
@@ -819,13 +864,20 @@ export class MongoOAuthProvider {
|
|
|
819
864
|
// No double quotes in these messages: they are copied into that header.
|
|
820
865
|
const doc = await this._findToken(token, 'access');
|
|
821
866
|
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');
|
|
867
|
+
if (await owlCredentialBlocked(this._getDb(), this.prefix, doc)) await refuseOwlCredential(doc, 'access');
|
|
868
|
+
if (await credentialBlocked(this._getDb(), this.prefix, doc)) await refuseRotatedCredential(doc, 'access');
|
|
822
869
|
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');
|
|
823
870
|
return {
|
|
824
871
|
token,
|
|
825
872
|
clientId: doc.client_id,
|
|
826
873
|
scopes: doc.scopes || [],
|
|
827
874
|
expiresAt: doc.expiresAt,
|
|
828
|
-
extra: {
|
|
875
|
+
extra: {
|
|
876
|
+
subject: doc.subject || 'owner',
|
|
877
|
+
sourceTag: doc.source_tag || null,
|
|
878
|
+
grantId: grantIdFromFamily(doc.family),
|
|
879
|
+
door: doorFromIssuedVia(doc.issued_via)
|
|
880
|
+
},
|
|
829
881
|
};
|
|
830
882
|
}
|
|
831
883
|
|
|
@@ -837,3 +889,35 @@ export class MongoOAuthProvider {
|
|
|
837
889
|
if (clear && clear.hashed !== true) await tokens.deleteOne({ _id: clear._id });
|
|
838
890
|
}
|
|
839
891
|
}
|
|
892
|
+
|
|
893
|
+
/**
|
|
894
|
+
* R5 credential bookkeeping. These rows live in the OAuth collections and in
|
|
895
|
+
* emet_rotations. They are not a memory layer, a document, or a transcript.
|
|
896
|
+
* A rotated grant is stamped and kept. Nothing here is deleted.
|
|
897
|
+
*/
|
|
898
|
+
async function stampCredentialIds(col, ids, eventId, at) {
|
|
899
|
+
if (!ids.length || !col || typeof col.updateMany !== 'function') return 0;
|
|
900
|
+
const result = await col.updateMany(
|
|
901
|
+
{ _id: { $in: ids } },
|
|
902
|
+
{ $set: { superseded_by: eventId, retired: true, revoked_at: at, deleted: false } }
|
|
903
|
+
);
|
|
904
|
+
return result && result.modifiedCount ? result.modifiedCount : ids.length;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
export async function openRotationEvent(db, prefix, { event, epochId, household, epochSet, tokenIds, codeIds, at }) {
|
|
908
|
+
const rotations = db.collection(`${prefix}rotations`);
|
|
909
|
+
await rotations.insertOne(event);
|
|
910
|
+
if (household) {
|
|
911
|
+
await rotations.updateOne(
|
|
912
|
+
{ _id: epochId },
|
|
913
|
+
{ $set: epochSet, $inc: { generation: 1 } },
|
|
914
|
+
{ upsert: true }
|
|
915
|
+
);
|
|
916
|
+
}
|
|
917
|
+
await stampCredentialIds(db.collection(`${prefix}oauth_tokens`), tokenIds, event._id, at);
|
|
918
|
+
await stampCredentialIds(db.collection(`${prefix}oauth_codes`), codeIds, event._id, at);
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
export async function finishRotationEvent(db, prefix, eventId, fields) {
|
|
922
|
+
await db.collection(`${prefix}rotations`).updateOne({ _id: eventId }, { $set: fields });
|
|
923
|
+
}
|
package/src/owl.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owl MCP clone account (R6).
|
|
3
|
+
*
|
|
4
|
+
* The account `user-EMET--owl` was a second OAuth client so an approval
|
|
5
|
+
* queued by one grant could be decided by another client_id. R6 retires
|
|
6
|
+
* that role. the owner decides a new writer on /owner/chooser. Master Hub
|
|
7
|
+
* prepares the request. The server validates it. This account does not
|
|
8
|
+
* approve.
|
|
9
|
+
*
|
|
10
|
+
* ISO 9001 7.5.3 / ISO 13485 4.2.5: supersede, retire, retain. Rows are
|
|
11
|
+
* not deleted. A startup check fails loudly (stderr and the owl
|
|
12
|
+
* retirement metric; the process does not exit) when an owl grant is
|
|
13
|
+
* active again. Rotate-all (R5) already revokes every grant; the invite step
|
|
14
|
+
* skips this account so a rotation does not hand it a fresh code. This
|
|
15
|
+
* module does not call Railway EMET and does not run a rotation.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { COLLECTION_PREFIX } from './database.js';
|
|
19
|
+
import { assignCode, newCorrelationId } from './error-codes.js';
|
|
20
|
+
import { OWL_ACCOUNT, doorFromIssuedVia, grantIdFromFamily, logClientId, logDoor, logGrantId } from './grants.js';
|
|
21
|
+
import { InvalidGrantError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
|
|
22
|
+
|
|
23
|
+
const POINTER = 'this owl MCP clone account was retired by R6. A new writer is prepared by Master Hub, validated on the server, and decided by the owner at /owner/chooser. This account cannot approve. Records are retained.';
|
|
24
|
+
const MARKER_ID = 'owl-mcp-clone';
|
|
25
|
+
|
|
26
|
+
const metric = {
|
|
27
|
+
ok: null,
|
|
28
|
+
active: null,
|
|
29
|
+
last_line: null,
|
|
30
|
+
checked_at: null
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export function _resetOwlForTests() {
|
|
34
|
+
metric.ok = null;
|
|
35
|
+
metric.active = null;
|
|
36
|
+
metric.last_line = null;
|
|
37
|
+
metric.checked_at = null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function owlRetirementMetric() {
|
|
41
|
+
return {
|
|
42
|
+
rung: 'R6',
|
|
43
|
+
account: OWL_ACCOUNT,
|
|
44
|
+
status: 'retired',
|
|
45
|
+
retained: true,
|
|
46
|
+
deleted: false,
|
|
47
|
+
validator: 'server',
|
|
48
|
+
decision_path: '/owner/chooser',
|
|
49
|
+
ok: metric.ok,
|
|
50
|
+
active: metric.active,
|
|
51
|
+
last_line: metric.last_line,
|
|
52
|
+
checked_at: metric.checked_at,
|
|
53
|
+
since_process_start: true
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Exact account identity. A substring is not a match. */
|
|
58
|
+
export function isOwlIdentity(value) {
|
|
59
|
+
if (value == null) return false;
|
|
60
|
+
if (typeof value === 'string') return value === OWL_ACCOUNT;
|
|
61
|
+
if (typeof value !== 'object') return false;
|
|
62
|
+
const fields = [
|
|
63
|
+
value.clientId, value.client_id, value.sourceTag, value.source_tag,
|
|
64
|
+
value.effectiveTag, value.client_name, value.clientName, value.tag
|
|
65
|
+
];
|
|
66
|
+
return fields.some((field) => field === OWL_ACCOUNT);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function notRetired(doc) {
|
|
70
|
+
return !(doc && (doc.superseded_by || doc.retired === true || doc.used === true));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function unexpired(doc, now) {
|
|
74
|
+
const expMs = Number.isFinite(doc && doc.expiresAtMs)
|
|
75
|
+
? doc.expiresAtMs
|
|
76
|
+
: (Number.isFinite(doc && doc.expiresAt) ? doc.expiresAt * 1000 : null);
|
|
77
|
+
if (expMs == null) return true;
|
|
78
|
+
return expMs > now;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function readAll(db, name) {
|
|
82
|
+
if (!db || typeof db.collection !== 'function') return [];
|
|
83
|
+
try {
|
|
84
|
+
const col = db.collection(name);
|
|
85
|
+
if (!col || typeof col.find !== 'function') return [];
|
|
86
|
+
const cursor = col.find({});
|
|
87
|
+
if (!cursor || typeof cursor.toArray !== 'function') return [];
|
|
88
|
+
return await cursor.toArray();
|
|
89
|
+
} catch {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The account id, plus any registered client whose name or id is that
|
|
96
|
+
* account. A token may carry an opaque registration id.
|
|
97
|
+
*/
|
|
98
|
+
export async function owlClientIds(db, prefix = COLLECTION_PREFIX) {
|
|
99
|
+
const ids = new Set([OWL_ACCOUNT]);
|
|
100
|
+
const clients = await readAll(db, `${prefix}oauth_clients`);
|
|
101
|
+
for (const client of clients) {
|
|
102
|
+
if (client && isOwlIdentity(client) && typeof client.client_id === 'string' && client.client_id) {
|
|
103
|
+
ids.add(client.client_id);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return ids;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function rowIsOwl(doc, ids) {
|
|
110
|
+
if (isOwlIdentity(doc)) return true;
|
|
111
|
+
return typeof doc.client_id === 'string' && ids.has(doc.client_id);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Refused on use. A retired, superseded, or spent row is history and stays readable. */
|
|
115
|
+
export async function owlCredentialBlocked(db, prefix, doc) {
|
|
116
|
+
if (!doc || typeof doc !== 'object' || !notRetired(doc)) return false;
|
|
117
|
+
if (isOwlIdentity(doc)) return true;
|
|
118
|
+
if (!db || typeof doc.client_id !== 'string' || !doc.client_id) return false;
|
|
119
|
+
const ids = await owlClientIds(db, prefix);
|
|
120
|
+
return ids.has(doc.client_id);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function listActiveOwlGrants(db, prefix = COLLECTION_PREFIX, now = Date.now()) {
|
|
124
|
+
const ids = await owlClientIds(db, prefix);
|
|
125
|
+
const rows = [
|
|
126
|
+
...(await readAll(db, `${prefix}oauth_tokens`)),
|
|
127
|
+
...(await readAll(db, `${prefix}oauth_codes`))
|
|
128
|
+
];
|
|
129
|
+
return rows.filter((doc) => doc && notRetired(doc) && unexpired(doc, now) && rowIsOwl(doc, ids));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* One retained marker. Insert once. Later calls do not delete it and do
|
|
134
|
+
* not clear a previous retirement. Historical grants are a different collection.
|
|
135
|
+
*/
|
|
136
|
+
export async function ensureOwlRetirementMarker(db, prefix = COLLECTION_PREFIX, now = new Date()) {
|
|
137
|
+
if (!db || typeof db.collection !== 'function') return null;
|
|
138
|
+
const col = db.collection(`${prefix}owl_retirement`);
|
|
139
|
+
const at = now instanceof Date ? now.toISOString() : new Date(now).toISOString();
|
|
140
|
+
const existing = await col.findOne({ _id: MARKER_ID });
|
|
141
|
+
if (existing) return existing;
|
|
142
|
+
const row = {
|
|
143
|
+
_id: MARKER_ID,
|
|
144
|
+
account: OWL_ACCOUNT,
|
|
145
|
+
status: 'retired',
|
|
146
|
+
superseded_by: 'R6',
|
|
147
|
+
rung: 'R6',
|
|
148
|
+
retained: true,
|
|
149
|
+
deleted: false,
|
|
150
|
+
validator: 'server',
|
|
151
|
+
decision_path: '/owner/chooser',
|
|
152
|
+
at,
|
|
153
|
+
note: 'Historical grants and logs stay readable. This marker does not delete them.'
|
|
154
|
+
};
|
|
155
|
+
await col.insertOne(row);
|
|
156
|
+
return row;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function owlStartupCheck(db, prefix = COLLECTION_PREFIX, now = new Date()) {
|
|
160
|
+
const at = now instanceof Date ? now : new Date(now);
|
|
161
|
+
let active = [];
|
|
162
|
+
let failed = false;
|
|
163
|
+
try {
|
|
164
|
+
await ensureOwlRetirementMarker(db, prefix, at);
|
|
165
|
+
active = await listActiveOwlGrants(db, prefix, at.getTime());
|
|
166
|
+
} catch {
|
|
167
|
+
failed = true;
|
|
168
|
+
}
|
|
169
|
+
const ok = !failed && active.length === 0;
|
|
170
|
+
const line = ok
|
|
171
|
+
? `[emet] owl-retirement check=pass account=${OWL_ACCOUNT} active=0 rung=R6`
|
|
172
|
+
: `[emet] OWL RETIREMENT CHECK FAILED account=${OWL_ACCOUNT} active=${failed ? 'unknown' : active.length} rung=R6 pointer=/owner/chooser`;
|
|
173
|
+
metric.ok = ok;
|
|
174
|
+
metric.active = failed ? null : active.length;
|
|
175
|
+
metric.last_line = line;
|
|
176
|
+
metric.checked_at = at.toISOString();
|
|
177
|
+
if (!ok) console.error(line);
|
|
178
|
+
return {
|
|
179
|
+
ok,
|
|
180
|
+
active: failed ? null : active.length,
|
|
181
|
+
line,
|
|
182
|
+
grant_ids: active.map((doc) => logGrantId(grantIdFromFamily(doc && doc.family)))
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Boot check for both entry points. Stdio (`index.js`) and the remote
|
|
188
|
+
* server (`http-remote.js`) call this. It logs the check line and does
|
|
189
|
+
* not exit. A failure is stderr plus `owlRetirementMetric`.
|
|
190
|
+
*/
|
|
191
|
+
export async function runStartupChecks(db, { prefix = COLLECTION_PREFIX, log } = {}) {
|
|
192
|
+
const write = typeof log === 'function' ? log : console.error;
|
|
193
|
+
let line;
|
|
194
|
+
try {
|
|
195
|
+
const owl = await owlStartupCheck(db, prefix);
|
|
196
|
+
line = owl.line;
|
|
197
|
+
} catch {
|
|
198
|
+
line = `[emet] OWL RETIREMENT CHECK FAILED account=${OWL_ACCOUNT} active=unknown rung=R6 pointer=/owner/chooser`;
|
|
199
|
+
}
|
|
200
|
+
write(line);
|
|
201
|
+
return { line, exited: false };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Log grant_id and correlation_id, then refuse. No token and no invite code. */
|
|
205
|
+
export async function refuseOwlCredential(doc, kind = 'access') {
|
|
206
|
+
const correlation_id = newCorrelationId();
|
|
207
|
+
const grant_id = logGrantId(grantIdFromFamily(doc && doc.family));
|
|
208
|
+
const door = doorFromIssuedVia(doc && doc.issued_via) || 'unknown';
|
|
209
|
+
console.error(`[emet] owl-retired grant_id=${grant_id} correlation_id=${correlation_id} pointer=/owner/chooser`);
|
|
210
|
+
try {
|
|
211
|
+
const { insertErrorLog } = await import('./error-log.js');
|
|
212
|
+
await insertErrorLog({
|
|
213
|
+
emet_code: 'EMET-AUTH-042',
|
|
214
|
+
class_code: 'INTERNAL_ERROR',
|
|
215
|
+
tool: kind === 'refresh' ? 'oauth_refresh' : (kind === 'code' || kind === 'issue' ? 'oauth_code' : 'oauth_access'),
|
|
216
|
+
transport: 'http',
|
|
217
|
+
caller: 'unregistered',
|
|
218
|
+
role: 'guest',
|
|
219
|
+
client_id: logClientId(doc && (doc.client_id || doc.clientId)),
|
|
220
|
+
grant_id,
|
|
221
|
+
door: logDoor(door),
|
|
222
|
+
correlation_id
|
|
223
|
+
});
|
|
224
|
+
} catch {
|
|
225
|
+
console.error('[emet] owl-retired error-log write failed');
|
|
226
|
+
}
|
|
227
|
+
const message = `${POINTER} grant_id: ${grant_id}. correlation_id: ${correlation_id}`;
|
|
228
|
+
const err = kind === 'access' ? new InvalidTokenError(message) : new InvalidGrantError(message);
|
|
229
|
+
err.correlation_id = correlation_id;
|
|
230
|
+
err.grant_id = grant_id;
|
|
231
|
+
throw assignCode(err, 'EMET-AUTH-042');
|
|
232
|
+
}
|