@flashyid/sdk 0.1.1 → 0.3.0

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.
@@ -1,4 +1,5 @@
1
1
  import { verifyChain, permits } from '../grants/index.js';
2
+ import { verifyChainAgainst } from '../grants/revocation.js';
2
3
  /**
3
4
  * The gate decision for a signed grant chain against a demanded action. Pure.
4
5
  *
@@ -10,10 +11,21 @@ import { verifyChain, permits } from '../grants/index.js';
10
11
  * Every other refusal (unsound chain, out of mandate) stays a DENY.
11
12
  */
12
13
  export function evaluateGrant(chain, demand, opts) {
13
- const verified = verifyChain(chain, opts.nowSec, opts.revokedJtis ?? new Set());
14
+ let verified;
15
+ const stamp = {};
16
+ if (opts.revocations) {
17
+ const verdict = verifyChainAgainst(chain, opts.nowSec, opts.revocations, { asOf: opts.asOf, extraRevoked: opts.revokedJtis });
18
+ verified = verdict.result;
19
+ stamp.revocationsAsOf = verdict.asOf;
20
+ }
21
+ else {
22
+ verified = verifyChain(chain, opts.nowSec, opts.revokedJtis ?? new Set());
23
+ }
14
24
  if (!verified.ok) {
15
- return { action: 'DENY', code: verified.code, reason: verified.detail ?? verified.code };
25
+ return { action: 'DENY', code: verified.code, reason: verified.detail ?? verified.code, ...stamp };
16
26
  }
27
+ // The gate decides against the LEAF's effective authority — the intersection
28
+ // down the whole chain, which verifyChain has just folded — never the root's.
17
29
  const permitted = permits(verified, demand);
18
30
  if (permitted !== true) {
19
31
  if (permitted.code === 'approval_required') {
@@ -23,11 +35,12 @@ export function evaluateGrant(chain, demand, opts) {
23
35
  action: 'ESCALATE',
24
36
  escalateAtOrAbove: verified.lim.approval_at_or_above,
25
37
  reason: permitted.detail ?? permitted.code,
38
+ ...stamp,
26
39
  };
27
40
  }
28
- return { action: 'DENY', code: permitted.code, reason: permitted.detail ?? permitted.code };
41
+ return { action: 'DENY', code: permitted.code, reason: permitted.detail ?? permitted.code, ...stamp };
29
42
  }
30
- return { action: 'ALLOW' };
43
+ return { action: 'ALLOW', ...stamp };
31
44
  }
32
45
  /**
33
46
  * The default: record only, never block. An org with no adapter configured, or
@@ -40,25 +53,52 @@ export const recordOnly = {
40
53
  /** An adapter backed by the grant kernel — the real gate. */
41
54
  export function grantAdapter() {
42
55
  return {
43
- evaluate: (d) => Promise.resolve(evaluateGrant(d.chain, d.demand, { nowSec: d.nowSec, revokedJtis: d.revokedJtis })),
56
+ evaluate: (d) => Promise.resolve(evaluateGrant(d.chain, d.demand, { nowSec: d.nowSec, revokedJtis: d.revokedJtis, revocations: d.revocations, asOf: d.asOf })),
44
57
  };
45
58
  }
46
59
  /**
47
60
  * Run a decision through an adapter with the operational contract: await the
48
- * adapter up to a timeout; if it throws or times out, fall back to record-only
49
- * ALLOW and raise `onUnavailable`. Preserves "never block" for everyone, while
50
- * giving an adapter-configured org a real gate.
61
+ * adapter up to a timeout; if it throws or times out, raise `onUnavailable`
62
+ * and answer per `opts.unavailable` — DENY unless the caller chose otherwise.
63
+ *
64
+ * Until 0.2.0 this fell back to ALLOW unconditionally ("never block"). That
65
+ * made the gate suitable only where enforcement was optional: a mandatory
66
+ * boundary that fails open is not a boundary. The record-only default for
67
+ * orgs with NO adapter is unchanged — `recordOnly` still answers ALLOW — but
68
+ * an adapter that is configured and unreachable now fails closed by default.
51
69
  */
52
70
  export async function enforce(decision, adapter, opts = {}) {
53
71
  const timeoutMs = opts.timeoutMs ?? 5000;
72
+ const mode = opts.unavailable ?? 'deny';
54
73
  try {
55
- return await withTimeout(adapter.evaluate(decision), timeoutMs);
74
+ const answer = await withTimeout(adapter.evaluate(decision), timeoutMs);
75
+ // An adapter that resolves with something that is not one of the three
76
+ // answers — a policy service whose response shape changed, a verdict for
77
+ // another protocol — has not answered. Handing its object back as if it
78
+ // were a verdict lets any caller testing `action !== 'DENY'` proceed, which
79
+ // is the fail-open path with the error message removed. The invariants
80
+ // harness found it: a non-verdict is unavailability, and takes the same
81
+ // fall-back as a throw.
82
+ if (!isVerdict(answer))
83
+ throw new Error(`enforcement adapter returned no verdict (${JSON.stringify(answer) ?? String(answer)})`);
84
+ return answer;
56
85
  }
57
86
  catch (error) {
58
87
  opts.onUnavailable?.(error);
59
- return { action: 'ALLOW', reason: 'enforcement adapter unavailable — recorded only' };
88
+ const why = error instanceof Error ? error.message : String(error);
89
+ if (mode === 'allow')
90
+ return { action: 'ALLOW', reason: `enforcement adapter unavailable — recorded only (${why})` };
91
+ if (mode === 'escalate') {
92
+ return { action: 'ESCALATE', escalateAtOrAbove: 'LOW', reason: `enforcement adapter unavailable — a human decides (${why})` };
93
+ }
94
+ return { action: 'DENY', code: 'adapter_unavailable', reason: `enforcement adapter unavailable — failing closed (${why})` };
60
95
  }
61
96
  }
97
+ const ACTIONS = new Set(['ALLOW', 'DENY', 'ESCALATE']);
98
+ /** One of the three answers, and nothing else. */
99
+ function isVerdict(answer) {
100
+ return typeof answer === 'object' && answer !== null && 'action' in answer && typeof answer.action === 'string' && ACTIONS.has(answer.action);
101
+ }
62
102
  /** Reject if the promise does not settle within `ms`. */
63
103
  export function withTimeout(promise, ms) {
64
104
  return new Promise((resolve, reject) => {
@@ -9,6 +9,8 @@ export interface IssueRootInput {
9
9
  lim?: Limit;
10
10
  iat: number;
11
11
  exp: number;
12
+ /** Not-before, optional. Every link beneath starts no earlier. */
13
+ nbf?: number;
12
14
  jti: string;
13
15
  }
14
16
  /** Mint the root link of a chain, issued from the accountable human. */
@@ -22,9 +24,12 @@ export interface AttenuateInput {
22
24
  res?: string[];
23
25
  /** Limit for the child — must be no looser than the parent's. Defaults to the parent's. */
24
26
  lim?: Limit;
27
+ /** Issued-at. Must not precede the parent's — a child cannot predate the link that created it. */
25
28
  iat: number;
26
29
  /** Child expiry. Capped at the parent's (a child never outlives its parent). */
27
30
  exp: number;
31
+ /** Child not-before. Raised to the parent's when lower (a child never starts before its parent). */
32
+ nbf?: number;
28
33
  jti: string;
29
34
  }
30
35
  /**
@@ -38,10 +43,17 @@ export declare function attenuate(chain: GrantChain, input: AttenuateInput): Gra
38
43
  /**
39
44
  * Verify a chain end to end and resolve the authority in effect, or refuse with
40
45
  * the first reason it fails. Enforces continuity (each issuer is the holder
41
- * above), the narrowing invariant at every hop, expiry at `nowSec`, and
42
- * (optionally) revocation. Independent of how the chain was built — a chain
43
- * that widened by any route is caught here, which is why attenuate's guard is
44
- * not the only line of defense.
46
+ * above AND each link binds its specific parent by `par`), the narrowing
47
+ * invariant at every hop, expiry at `nowSec`, and (optionally) revocation.
48
+ * Independent of how the chain was built — a chain that widened, or was spliced
49
+ * together from links of different chains, by any route is caught here, which
50
+ * is why attenuate's guard is not the only line of defense.
51
+ *
52
+ * This is a check over the chain's STRUCTURE, not its signatures: it proves the
53
+ * links narrow and link to one another, not that an issuer signed them. A
54
+ * relying party verifies the signature separately — `verifyAssertion` /
55
+ * `authorize` in the SDK do both, and are what a consumer should call. Running
56
+ * `verifyChain` alone on wire data proves narrowing, never authenticity.
45
57
  */
46
58
  export declare function verifyChain(chain: GrantChain, nowSec: number, revokedJtis?: ReadonlySet<string>): GrantResult;
47
59
  export interface Demand {
@@ -70,7 +70,9 @@ export function issueRoot(input) {
70
70
  lim: input.lim ? { ...input.lim } : {},
71
71
  iat: input.iat,
72
72
  exp: input.exp,
73
+ ...(input.nbf !== undefined ? { nbf: input.nbf } : {}),
73
74
  jti: input.jti,
75
+ par: null, // the root binds no parent
74
76
  },
75
77
  ];
76
78
  }
@@ -94,6 +96,15 @@ export function attenuate(chain, input) {
94
96
  return refuse('chain_widened', chain.length, 'resource widened');
95
97
  if (!limitWithin(lim, parent.lim))
96
98
  return refuse('chain_widened', chain.length, 'limit loosened');
99
+ // A child issued before its parent was not created by it. Harmless while one
100
+ // key signs the whole chain; fatal once links are independently signed, so it
101
+ // is refused at build time as well as at verify time (source audit, 2026-08).
102
+ if (input.iat < parent.iat)
103
+ return refuse('broken_chain', chain.length, 'child issued before its parent');
104
+ // Not-before is the mirror of expiry: exp is capped at the parent's, nbf is
105
+ // raised to the parent's. A chain's window is the intersection of its links'.
106
+ const nbfCandidates = [input.nbf, parent.nbf].filter((x) => x !== undefined);
107
+ const nbf = nbfCandidates.length ? Math.max(...nbfCandidates) : undefined;
97
108
  const child = {
98
109
  iss: parent.sub, // the parent's holder is this child's issuer
99
110
  sub: input.holder,
@@ -102,24 +113,38 @@ export function attenuate(chain, input) {
102
113
  lim,
103
114
  iat: input.iat,
104
115
  exp: Math.min(input.exp, parent.exp), // never outlive the parent
116
+ ...(nbf !== undefined ? { nbf } : {}),
105
117
  jti: input.jti,
118
+ par: parent.jti, // bind this specific parent, so the link cannot be spliced elsewhere
106
119
  };
107
120
  return [...chain, child];
108
121
  }
109
122
  /**
110
123
  * Verify a chain end to end and resolve the authority in effect, or refuse with
111
124
  * the first reason it fails. Enforces continuity (each issuer is the holder
112
- * above), the narrowing invariant at every hop, expiry at `nowSec`, and
113
- * (optionally) revocation. Independent of how the chain was built — a chain
114
- * that widened by any route is caught here, which is why attenuate's guard is
115
- * not the only line of defense.
125
+ * above AND each link binds its specific parent by `par`), the narrowing
126
+ * invariant at every hop, expiry at `nowSec`, and (optionally) revocation.
127
+ * Independent of how the chain was built — a chain that widened, or was spliced
128
+ * together from links of different chains, by any route is caught here, which
129
+ * is why attenuate's guard is not the only line of defense.
130
+ *
131
+ * This is a check over the chain's STRUCTURE, not its signatures: it proves the
132
+ * links narrow and link to one another, not that an issuer signed them. A
133
+ * relying party verifies the signature separately — `verifyAssertion` /
134
+ * `authorize` in the SDK do both, and are what a consumer should call. Running
135
+ * `verifyChain` alone on wire data proves narrowing, never authenticity.
116
136
  */
117
137
  export function verifyChain(chain, nowSec, revokedJtis = new Set()) {
118
138
  const first = chain[0];
119
139
  if (!first)
120
140
  return refuse('empty_chain');
141
+ // The root binds no parent; a root that names one is malformed (a spliced
142
+ // sub-chain presented as if it were whole).
143
+ if (first.par !== null)
144
+ return refuse('broken_chain', 0, 'root link must not bind a parent');
121
145
  let effLim = { ...first.lim };
122
146
  let effExp = first.exp;
147
+ let effNbf = first.nbf;
123
148
  for (let i = 0; i < chain.length; i++) {
124
149
  const link = chain[i];
125
150
  if (!link)
@@ -131,12 +156,26 @@ export function verifyChain(chain, nowSec, revokedJtis = new Set()) {
131
156
  return refuse('revoked', i);
132
157
  if (link.exp <= nowSec)
133
158
  return refuse('expired', i);
159
+ // A link is in force from its not-before, when it carries one. Checked per
160
+ // link, so the effective window is the intersection: the latest nbf and the
161
+ // earliest exp across the chain.
162
+ if (link.nbf !== undefined && nowSec < link.nbf)
163
+ return refuse('not_yet_valid', i);
134
164
  if (i > 0) {
135
165
  const parent = chain[i - 1];
136
166
  if (!parent)
137
167
  return refuse('broken_chain', i);
138
168
  if (link.iss !== parent.sub)
139
169
  return refuse('broken_chain', i, 'issuer is not the holder above');
170
+ // A child dated before its parent was not created by it. `attenuate`
171
+ // refuses to build one; this refuses one that arrived by any other route.
172
+ if (link.iat < parent.iat)
173
+ return refuse('broken_chain', i, 'link issued before its parent');
174
+ // Parent binding: the link must name its exact parent, not merely some
175
+ // link with a matching holder. This is what refuses a splice — a leaf
176
+ // lifted from one chain and dropped under a same-holder parent in another.
177
+ if (link.par !== parent.jti)
178
+ return refuse('broken_chain', i, 'link does not bind its stated parent (splice)');
140
179
  if (!isSubset(link.scp, parent.scp))
141
180
  return refuse('chain_widened', i, 'scope widened');
142
181
  if (!isSubset(link.res, parent.res))
@@ -145,6 +184,8 @@ export function verifyChain(chain, nowSec, revokedJtis = new Set()) {
145
184
  return refuse('chain_widened', i, 'limit loosened');
146
185
  effLim = tightestLimit(effLim, link.lim);
147
186
  effExp = Math.min(effExp, link.exp);
187
+ if (link.nbf !== undefined)
188
+ effNbf = effNbf === undefined ? link.nbf : Math.max(effNbf, link.nbf);
148
189
  }
149
190
  }
150
191
  const leaf = chain[chain.length - 1];
@@ -158,6 +199,7 @@ export function verifyChain(chain, nowSec, revokedJtis = new Set()) {
158
199
  res: [...leaf.res],
159
200
  lim: effLim,
160
201
  exp: effExp,
202
+ ...(effNbf !== undefined ? { nbf: effNbf } : {}),
161
203
  chain: chain.map((l) => l.jti),
162
204
  };
163
205
  return effective;
@@ -12,5 +12,7 @@
12
12
  export * from './types.js';
13
13
  export { issueRoot, attenuate, verifyChain, permits, rootsWithin } from './grants.js';
14
14
  export type { IssueRootInput, AttenuateInput, Demand } from './grants.js';
15
+ export { emptyRevocationList, revoke, revokedAsOf, revocationOf, extendsList, validateRevocationList, verifyChainAgainst, isAccountableSigner, REVOCATION_LIST_VERSION, REVOCATION_REASON_MIN, REVOCATION_SIGNER_PREFIXES, } from './revocation.js';
16
+ export type { RevocationEntry, RevocationList, RevocationRefusal, RevocationRefusalCode, RevokeInput, ChainVerdict } from './revocation.js';
15
17
  export { grantFromCharterRole } from './fromCharter.js';
16
18
  export type { CharterRoleInput, FromCharterInput } from './fromCharter.js';
@@ -11,4 +11,5 @@
11
11
  */
12
12
  export * from './types.js';
13
13
  export { issueRoot, attenuate, verifyChain, permits, rootsWithin } from './grants.js';
14
+ export { emptyRevocationList, revoke, revokedAsOf, revocationOf, extendsList, validateRevocationList, verifyChainAgainst, isAccountableSigner, REVOCATION_LIST_VERSION, REVOCATION_REASON_MIN, REVOCATION_SIGNER_PREFIXES, } from './revocation.js';
14
15
  export { grantFromCharterRole } from './fromCharter.js';
@@ -0,0 +1,130 @@
1
+ import type { GrantChain, GrantResult } from './types.js';
2
+ /**
3
+ * The revocation list — `revocation/1`.
4
+ *
5
+ * `verifyChain` has always taken a `revokedJtis` set and walked revocation
6
+ * down the chain (invariant 3). What it never had was the record that set comes
7
+ * FROM: a relying party was expected to already know what had been revoked,
8
+ * "which is the one thing it cannot know about another organization" (source
9
+ * audit, finding "No revocation pointer on the link"). This is that record.
10
+ *
11
+ * Shape, and the rules that hold it:
12
+ * - It is APPEND-ONLY. Every entry carries a `seq` one past the entry before
13
+ * it, and `head` is the latest. A list is never edited: a mistaken
14
+ * revocation is corrected by issuing a new grant, never by removing the
15
+ * entry, because a reader that fetched revision 5 must find revision 5
16
+ * intact inside revision 7 (`extendsList`).
17
+ * - Every entry is SIGNED BY A PERSON OR AN ORGANISATION — `by` is a
18
+ * `person/` or `org/` id, never `agent/`. A revocation is a correction to
19
+ * the record, and the estate's posture for corrections is that somebody who
20
+ * can be asked why signs it. A reason of at least 24 characters is refused
21
+ * otherwise, for the same reason: "rotated" tells the next reader nothing.
22
+ * - It is DETERMINISTIC. No clock: the time of a revocation is an argument
23
+ * (`atSec`), and entries do not go backwards in time.
24
+ * - A verdict names the REVISION it was computed against (`asOf`), so a
25
+ * relying party can say "revoked as of revision 7" and an auditor can
26
+ * recompute it with the same revision rather than today's.
27
+ *
28
+ * Nothing here signs the list as a document; that is `signRevocationList` /
29
+ * `verifyRevocationList` in `src/sdk/revocation.ts`, which use the same EdDSA
30
+ * key and JWKS the assertions do. This module is pure and dependency-free, like
31
+ * the rest of the kernel.
32
+ */
33
+ export declare const REVOCATION_LIST_VERSION: "revocation/1";
34
+ /** The shortest reason the list accepts. The estate's bound for a correction. */
35
+ export declare const REVOCATION_REASON_MIN = 24;
36
+ /** The signer prefixes a revocation may carry. An `agent/` cannot withdraw authority. */
37
+ export declare const REVOCATION_SIGNER_PREFIXES: readonly ["person/", "org/"];
38
+ export interface RevocationEntry {
39
+ /** 1-based position in the list. Entry n has seq n; `head` is the last. */
40
+ seq: number;
41
+ /** The revoked grant id — the `jti` of a link. */
42
+ jti: string;
43
+ /** Who withdrew it: a `person/` or `org/` id. */
44
+ by: string;
45
+ /** Why, in at least 24 characters. */
46
+ reason: string;
47
+ /** When, seconds since epoch. Never earlier than the entry before. */
48
+ at: number;
49
+ }
50
+ export interface RevocationList {
51
+ v: typeof REVOCATION_LIST_VERSION;
52
+ /** The issuer whose grants this list revokes — the `iss` the signed form carries. */
53
+ issuer: string;
54
+ /** The latest revision: `entries.length`. Revision 0 is the empty list. */
55
+ head: number;
56
+ entries: RevocationEntry[];
57
+ }
58
+ export type RevocationRefusalCode = 'reason_too_short' | 'unaccountable_signer' | 'malformed_id' | 'already_revoked' | 'out_of_order' | 'malformed_list';
59
+ export interface RevocationRefusal {
60
+ ok: false;
61
+ code: RevocationRefusalCode;
62
+ detail?: string;
63
+ }
64
+ /** Revision 0: nothing revoked. */
65
+ export declare function emptyRevocationList(issuer: string): RevocationList;
66
+ /** Is this an id the estate lets sign a correction? */
67
+ export declare function isAccountableSigner(by: unknown): by is string;
68
+ export interface RevokeInput {
69
+ /** The grant (link) id to revoke. */
70
+ jti: string;
71
+ /** The person or organisation withdrawing it. */
72
+ by: string;
73
+ /** Why — at least 24 characters. */
74
+ reason: string;
75
+ /** When, seconds since epoch. Injected, never read from a clock. */
76
+ atSec: number;
77
+ }
78
+ /**
79
+ * Append a revocation. Returns a NEW list one revision ahead, or a refusal; the
80
+ * input list is never mutated. Refuses by name rather than clamping, so a
81
+ * caller that passes a short reason or an agent signer learns which rule it
82
+ * broke rather than finding its revocation quietly absent.
83
+ */
84
+ export declare function revoke(list: RevocationList, input: RevokeInput): RevocationList | RevocationRefusal;
85
+ /**
86
+ * The revoked ids as of a revision. `asOf` defaults to the head; a revision the
87
+ * list does not hold (negative, non-integer, or past the head) THROWS, because
88
+ * "as of revision 9" computed from a list that ends at 7 is a claim nothing
89
+ * computed — the same reason a derived field is never accepted as input.
90
+ */
91
+ export declare function revokedAsOf(list: RevocationList, asOf?: number): ReadonlySet<string>;
92
+ /** The entry that revoked `jti` at or before `asOf`, if any. */
93
+ export declare function revocationOf(list: RevocationList, jti: string, asOf?: number): RevocationEntry | undefined;
94
+ /**
95
+ * Is `next` the same list, later? A reader that cached revision n refuses a
96
+ * document that claims to be a later revision but rewrote anything in 1..n:
97
+ * same issuer, head not lower, and every entry it already held byte-for-byte
98
+ * where it was. This is the append-only rule from the reader's side.
99
+ */
100
+ export declare function extendsList(previous: RevocationList, next: RevocationList): boolean;
101
+ /**
102
+ * Is this a well-formed revocation/1 list? Every rule `revoke` enforces on the
103
+ * way in is enforced again here on the way out of the wire, so a caller that
104
+ * assembles a list by hand and never calls `revoke` still cannot hand a
105
+ * verifier a short reason, an agent signer, a gap in the sequence, or a clock
106
+ * that runs backwards. Returns the typed list, or a refusal naming the entry.
107
+ */
108
+ export declare function validateRevocationList(v: unknown): RevocationList | RevocationRefusal;
109
+ /** A chain verdict that says which revision of the list it was computed against. */
110
+ export interface ChainVerdict {
111
+ result: GrantResult;
112
+ /** The revision of `list` the verdict holds for. */
113
+ asOf: number;
114
+ /** The list's issuer, so the verdict is attributable. */
115
+ issuer: string;
116
+ }
117
+ /**
118
+ * `verifyChain` against a revocation list at a revision. The result is the
119
+ * kernel's — a revoked link, or any ancestor, refuses `revoked` at the highest
120
+ * revoked index, and everything beneath it is dead with it — plus the revision
121
+ * it was computed against, so the verdict can be restated and recomputed. A
122
+ * `revoked` refusal's detail names the entry: which link, who withdrew it, why.
123
+ *
124
+ * `extraRevoked` lets a relying party fold in ids it knows about from
125
+ * elsewhere (its own local withdrawals); they are unioned, never substituted.
126
+ */
127
+ export declare function verifyChainAgainst(chain: GrantChain, nowSec: number, list: RevocationList, opts?: {
128
+ asOf?: number;
129
+ extraRevoked?: ReadonlySet<string>;
130
+ }): ChainVerdict;
@@ -0,0 +1,183 @@
1
+ import { verifyChain } from './grants.js';
2
+ /**
3
+ * The revocation list — `revocation/1`.
4
+ *
5
+ * `verifyChain` has always taken a `revokedJtis` set and walked revocation
6
+ * down the chain (invariant 3). What it never had was the record that set comes
7
+ * FROM: a relying party was expected to already know what had been revoked,
8
+ * "which is the one thing it cannot know about another organization" (source
9
+ * audit, finding "No revocation pointer on the link"). This is that record.
10
+ *
11
+ * Shape, and the rules that hold it:
12
+ * - It is APPEND-ONLY. Every entry carries a `seq` one past the entry before
13
+ * it, and `head` is the latest. A list is never edited: a mistaken
14
+ * revocation is corrected by issuing a new grant, never by removing the
15
+ * entry, because a reader that fetched revision 5 must find revision 5
16
+ * intact inside revision 7 (`extendsList`).
17
+ * - Every entry is SIGNED BY A PERSON OR AN ORGANISATION — `by` is a
18
+ * `person/` or `org/` id, never `agent/`. A revocation is a correction to
19
+ * the record, and the estate's posture for corrections is that somebody who
20
+ * can be asked why signs it. A reason of at least 24 characters is refused
21
+ * otherwise, for the same reason: "rotated" tells the next reader nothing.
22
+ * - It is DETERMINISTIC. No clock: the time of a revocation is an argument
23
+ * (`atSec`), and entries do not go backwards in time.
24
+ * - A verdict names the REVISION it was computed against (`asOf`), so a
25
+ * relying party can say "revoked as of revision 7" and an auditor can
26
+ * recompute it with the same revision rather than today's.
27
+ *
28
+ * Nothing here signs the list as a document; that is `signRevocationList` /
29
+ * `verifyRevocationList` in `src/sdk/revocation.ts`, which use the same EdDSA
30
+ * key and JWKS the assertions do. This module is pure and dependency-free, like
31
+ * the rest of the kernel.
32
+ */
33
+ export const REVOCATION_LIST_VERSION = 'revocation/1';
34
+ /** The shortest reason the list accepts. The estate's bound for a correction. */
35
+ export const REVOCATION_REASON_MIN = 24;
36
+ /** The signer prefixes a revocation may carry. An `agent/` cannot withdraw authority. */
37
+ export const REVOCATION_SIGNER_PREFIXES = ['person/', 'org/'];
38
+ function refuse(code, detail) {
39
+ return { ok: false, code, detail };
40
+ }
41
+ /** Revision 0: nothing revoked. */
42
+ export function emptyRevocationList(issuer) {
43
+ return { v: REVOCATION_LIST_VERSION, issuer, head: 0, entries: [] };
44
+ }
45
+ /** Is this an id the estate lets sign a correction? */
46
+ export function isAccountableSigner(by) {
47
+ return typeof by === 'string' && REVOCATION_SIGNER_PREFIXES.some((p) => by.startsWith(p) && by.length > p.length);
48
+ }
49
+ /**
50
+ * Append a revocation. Returns a NEW list one revision ahead, or a refusal; the
51
+ * input list is never mutated. Refuses by name rather than clamping, so a
52
+ * caller that passes a short reason or an agent signer learns which rule it
53
+ * broke rather than finding its revocation quietly absent.
54
+ */
55
+ export function revoke(list, input) {
56
+ if (typeof input.jti !== 'string' || input.jti.length === 0)
57
+ return refuse('malformed_id', 'jti must be a non-empty string');
58
+ if (!isAccountableSigner(input.by)) {
59
+ return refuse('unaccountable_signer', `a revocation is signed by a person/ or org/ id, not ${JSON.stringify(input.by)}`);
60
+ }
61
+ const reason = typeof input.reason === 'string' ? input.reason.trim() : '';
62
+ if (reason.length < REVOCATION_REASON_MIN) {
63
+ return refuse('reason_too_short', `reason must be at least ${REVOCATION_REASON_MIN} characters (got ${reason.length})`);
64
+ }
65
+ if (!Number.isFinite(input.atSec))
66
+ return refuse('out_of_order', 'atSec must be a finite number of seconds');
67
+ const last = list.entries[list.entries.length - 1];
68
+ if (last && input.atSec < last.at) {
69
+ return refuse('out_of_order', `entry dated ${input.atSec} precedes the previous entry at ${last.at}; the list only moves forward`);
70
+ }
71
+ if (list.entries.some((e) => e.jti === input.jti))
72
+ return refuse('already_revoked', `${input.jti} is already revoked`);
73
+ const entry = { seq: list.head + 1, jti: input.jti, by: input.by, reason, at: input.atSec };
74
+ return { v: REVOCATION_LIST_VERSION, issuer: list.issuer, head: list.head + 1, entries: [...list.entries, entry] };
75
+ }
76
+ /**
77
+ * The revoked ids as of a revision. `asOf` defaults to the head; a revision the
78
+ * list does not hold (negative, non-integer, or past the head) THROWS, because
79
+ * "as of revision 9" computed from a list that ends at 7 is a claim nothing
80
+ * computed — the same reason a derived field is never accepted as input.
81
+ */
82
+ export function revokedAsOf(list, asOf = list.head) {
83
+ if (!Number.isInteger(asOf) || asOf < 0 || asOf > list.head) {
84
+ throw new RangeError(`revocation list ${list.issuer} holds revisions 0..${list.head}; asOf ${asOf} is not one of them`);
85
+ }
86
+ const out = new Set();
87
+ for (const e of list.entries)
88
+ if (e.seq <= asOf)
89
+ out.add(e.jti);
90
+ return out;
91
+ }
92
+ /** The entry that revoked `jti` at or before `asOf`, if any. */
93
+ export function revocationOf(list, jti, asOf = list.head) {
94
+ return list.entries.find((e) => e.jti === jti && e.seq <= asOf);
95
+ }
96
+ /**
97
+ * Is `next` the same list, later? A reader that cached revision n refuses a
98
+ * document that claims to be a later revision but rewrote anything in 1..n:
99
+ * same issuer, head not lower, and every entry it already held byte-for-byte
100
+ * where it was. This is the append-only rule from the reader's side.
101
+ */
102
+ export function extendsList(previous, next) {
103
+ if (previous.issuer !== next.issuer)
104
+ return false;
105
+ if (next.head < previous.head)
106
+ return false;
107
+ for (let i = 0; i < previous.entries.length; i++) {
108
+ if (!sameEntry(previous.entries[i], next.entries[i]))
109
+ return false;
110
+ }
111
+ return true;
112
+ }
113
+ function sameEntry(a, b) {
114
+ return a !== undefined && b !== undefined && a.seq === b.seq && a.jti === b.jti && a.by === b.by && a.reason === b.reason && a.at === b.at;
115
+ }
116
+ /**
117
+ * Is this a well-formed revocation/1 list? Every rule `revoke` enforces on the
118
+ * way in is enforced again here on the way out of the wire, so a caller that
119
+ * assembles a list by hand and never calls `revoke` still cannot hand a
120
+ * verifier a short reason, an agent signer, a gap in the sequence, or a clock
121
+ * that runs backwards. Returns the typed list, or a refusal naming the entry.
122
+ */
123
+ export function validateRevocationList(v) {
124
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
125
+ return refuse('malformed_list', 'not an object');
126
+ const l = v;
127
+ if (l.v !== REVOCATION_LIST_VERSION)
128
+ return refuse('malformed_list', `v must be ${REVOCATION_LIST_VERSION}`);
129
+ if (typeof l.issuer !== 'string' || l.issuer.length === 0)
130
+ return refuse('malformed_list', 'issuer must be a non-empty string');
131
+ if (!Array.isArray(l.entries))
132
+ return refuse('malformed_list', 'entries must be an array');
133
+ if (l.head !== l.entries.length)
134
+ return refuse('malformed_list', `head ${String(l.head)} is not the entry count ${l.entries.length}`);
135
+ let rebuilt = emptyRevocationList(l.issuer);
136
+ for (let i = 0; i < l.entries.length; i++) {
137
+ const e = l.entries[i];
138
+ if (typeof e !== 'object' || e === null)
139
+ return refuse('malformed_list', `entry ${i} is not an object`);
140
+ const r = e;
141
+ if (r.seq !== i + 1)
142
+ return refuse('malformed_list', `entry ${i} has seq ${String(r.seq)}, expected ${i + 1}`);
143
+ if (typeof r.reason !== 'string' || typeof r.by !== 'string' || typeof r.jti !== 'string' || typeof r.at !== 'number') {
144
+ return refuse('malformed_list', `entry ${i} is missing a field`);
145
+ }
146
+ if (r.reason !== r.reason.trim())
147
+ return refuse('malformed_list', `entry ${i} reason carries surrounding whitespace`);
148
+ const next = revoke(rebuilt, { jti: r.jti, by: r.by, reason: r.reason, atSec: r.at });
149
+ if ('ok' in next)
150
+ return { ...next, detail: `entry ${i}: ${next.detail ?? next.code}` };
151
+ rebuilt = next;
152
+ }
153
+ return rebuilt;
154
+ }
155
+ /**
156
+ * `verifyChain` against a revocation list at a revision. The result is the
157
+ * kernel's — a revoked link, or any ancestor, refuses `revoked` at the highest
158
+ * revoked index, and everything beneath it is dead with it — plus the revision
159
+ * it was computed against, so the verdict can be restated and recomputed. A
160
+ * `revoked` refusal's detail names the entry: which link, who withdrew it, why.
161
+ *
162
+ * `extraRevoked` lets a relying party fold in ids it knows about from
163
+ * elsewhere (its own local withdrawals); they are unioned, never substituted.
164
+ */
165
+ export function verifyChainAgainst(chain, nowSec, list, opts = {}) {
166
+ const asOf = opts.asOf ?? list.head;
167
+ const revoked = new Set(revokedAsOf(list, asOf));
168
+ for (const jti of opts.extraRevoked ?? [])
169
+ revoked.add(jti);
170
+ const result = verifyChain(chain, nowSec, revoked);
171
+ if (!result.ok && result.code === 'revoked' && result.at !== undefined) {
172
+ const link = chain[result.at];
173
+ const entry = link ? revocationOf(list, link.jti, asOf) : undefined;
174
+ if (entry) {
175
+ return {
176
+ result: { ...result, detail: `link ${entry.jti} revoked by ${entry.by} at revision ${entry.seq}: ${entry.reason}` },
177
+ asOf,
178
+ issuer: list.issuer,
179
+ };
180
+ }
181
+ }
182
+ return { result, asOf, issuer: list.issuer };
183
+ }
@@ -44,8 +44,25 @@ export interface GrantLink {
44
44
  iat: number;
45
45
  /** Expiry, seconds since epoch. The chain's effective expiry is the minimum of all links. */
46
46
  exp: number;
47
+ /**
48
+ * Not-before, seconds since epoch — optional. A link is not yet in force
49
+ * before it, and `verifyChain` refuses `not_yet_valid` at a `nowSec` below it.
50
+ * The chain's effective not-before is the MAXIMUM across every link that
51
+ * carries one (the mirror of `exp`): a child may start later than its parent,
52
+ * never earlier, and `attenuate` raises a child's `nbf` to the parent's.
53
+ */
54
+ nbf?: number;
47
55
  /** Unique id — the unit of revocation, and (downstream) of idempotency. */
48
56
  jti: string;
57
+ /**
58
+ * The `jti` of the parent link this attenuates, and `null` for the root. This
59
+ * is what makes continuity parent-*specific* rather than "issued by whoever
60
+ * holds the link above me": without it, two parents that share a holder (same
61
+ * `sub`) are interchangeable, so a leaf signed under one chain can be spliced
62
+ * onto another. `verifyChain` refuses a link whose `par` is not exactly the
63
+ * previous link's `jti`, and refuses a root whose `par` is not `null`.
64
+ */
65
+ par: string | null;
49
66
  }
50
67
  /** A delegation chain, root-first. chain[0].iss is the accountable human. */
51
68
  export type GrantChain = GrantLink[];
@@ -54,7 +71,7 @@ export type GrantChain = GrantLink[];
54
71
  * generic failure — a relying party (and an auditor) needs to know *why* a
55
72
  * chain did not hold, and the reason is part of the published contract.
56
73
  */
57
- export type RefusalCode = 'chain_widened' | 'broken_chain' | 'expired' | 'revoked' | 'out_of_mandate' | 'approval_required' | 'scope_unmapped' | 'untrusted_root' | 'empty_chain';
74
+ export type RefusalCode = 'chain_widened' | 'broken_chain' | 'expired' | 'not_yet_valid' | 'revoked' | 'out_of_mandate' | 'approval_required' | 'scope_unmapped' | 'untrusted_root' | 'adapter_unavailable' | 'empty_chain';
58
75
  export interface Refusal {
59
76
  ok: false;
60
77
  code: RefusalCode;
@@ -77,6 +94,8 @@ export interface EffectiveGrant {
77
94
  lim: Limit;
78
95
  /** Effective expiry: the minimum expiry across every link. */
79
96
  exp: number;
97
+ /** Effective not-before: the maximum `nbf` across the links that carry one; absent when none does. */
98
+ nbf?: number;
80
99
  /** The chain of jtis, root-first — the audit trail. */
81
100
  chain: string[];
82
101
  }
package/dist/index.d.ts CHANGED
@@ -14,5 +14,7 @@ export { evaluateGrant, enforce, withTimeout, recordOnly, grantAdapter, } from '
14
14
  export type { EnforcementAction, EnforcementResult, EnforcementAdapter, EvaluateOptions, DecisionInput, EnforceOptions, } from './enforce/gate.js';
15
15
  export { agentSubject, parseAgentSubject, isAgentSubject, fromDirectoryId, toDirectoryId, AGENT_SUBJECT } from './grants/subject.js';
16
16
  export type { AgentSubject } from './grants/subject.js';
17
+ export { mintIssuerToken, mintConsentToken, mintGrantToken, railGrantFromChain } from './rail/tokens.js';
18
+ export type { RailSigner, IssuerTokenInput, ConsentTokenInput, GrantTokenInput } from './rail/tokens.js';
17
19
  export { grantsFromCharter, summarizeGrants, trustedRootsFromCharters } from './init/charterGrants.js';
18
20
  export type { CharterInput, CharterGrantsOptions, RoleGrant, RoleRefusal, CharterGrantsResult, ClientRegistrar, } from './init/charterGrants.js';
package/dist/index.js CHANGED
@@ -15,4 +15,8 @@ export { evaluateGrant, enforce, withTimeout, recordOnly, grantAdapter, } from '
15
15
  // surrogate lived only in this suite's fixtures until 2026-08-31; it is
16
16
  // exported so the estate's directory can link to it rather than invent it.
17
17
  export { agentSubject, parseAgentSubject, isAgentSubject, fromDirectoryId, toDirectoryId, AGENT_SUBJECT } from './grants/subject.js';
18
+ // Rail tokens — flashyID minting the three tokens Flashy Rails verifies
19
+ // (issuer / consent / grant). The complement of the rail's FlashyIdVerifier;
20
+ // `railGrantFromChain` bridges the delegation kernel to the rail's flat grant.
21
+ export { mintIssuerToken, mintConsentToken, mintGrantToken, railGrantFromChain } from './rail/tokens.js';
18
22
  export { grantsFromCharter, summarizeGrants, trustedRootsFromCharters } from './init/charterGrants.js';