@flashyid/sdk 0.1.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.
Files changed (40) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +171 -0
  3. package/dist/cjs/enforce/gate.js +81 -0
  4. package/dist/cjs/grants/fromCharter.js +36 -0
  5. package/dist/cjs/grants/grants.js +227 -0
  6. package/dist/cjs/grants/index.js +37 -0
  7. package/dist/cjs/grants/subject.js +107 -0
  8. package/dist/cjs/grants/types.js +24 -0
  9. package/dist/cjs/index.js +49 -0
  10. package/dist/cjs/init/charterGrants.js +83 -0
  11. package/dist/cjs/package.json +1 -0
  12. package/dist/cjs/sdk/index.js +27 -0
  13. package/dist/cjs/sdk/sign.js +22 -0
  14. package/dist/cjs/sdk/verify.js +138 -0
  15. package/dist/enforce/gate.d.ts +88 -0
  16. package/dist/enforce/gate.js +74 -0
  17. package/dist/grants/fromCharter.d.ts +43 -0
  18. package/dist/grants/fromCharter.js +33 -0
  19. package/dist/grants/grants.d.ts +93 -0
  20. package/dist/grants/grants.js +220 -0
  21. package/dist/grants/index.d.ts +16 -0
  22. package/dist/grants/index.js +14 -0
  23. package/dist/grants/subject.d.ts +78 -0
  24. package/dist/grants/subject.js +99 -0
  25. package/dist/grants/types.d.ts +83 -0
  26. package/dist/grants/types.js +20 -0
  27. package/dist/index.d.ts +18 -0
  28. package/dist/index.js +18 -0
  29. package/dist/init/charterGrants.d.ts +96 -0
  30. package/dist/init/charterGrants.js +78 -0
  31. package/dist/init/cli.d.ts +23 -0
  32. package/dist/init/cli.js +102 -0
  33. package/dist/sdk/index.d.ts +16 -0
  34. package/dist/sdk/index.js +13 -0
  35. package/dist/sdk/sign.d.ts +42 -0
  36. package/dist/sdk/sign.js +19 -0
  37. package/dist/sdk/verify.d.ts +85 -0
  38. package/dist/sdk/verify.js +134 -0
  39. package/docs/enforcement-gate.md +56 -0
  40. package/package.json +63 -0
@@ -0,0 +1,96 @@
1
+ import { type CharterRoleInput } from '../grants/fromCharter.js';
2
+ import { type GrantChain, type Refusal } from '../grants/types.js';
3
+ /**
4
+ * `flashyid init`, minus the network: turn an organization's charter into the
5
+ * root grants its roles hold.
6
+ *
7
+ * The charter is already the grant (see grants/fromCharter). This maps *every*
8
+ * role in a charter at once, which is what the init command does when it reads a
9
+ * repository's `flashyos.roles.json` — one root grant per role, each issued from
10
+ * the charter's accountable human. Pure and deterministic: the caller supplies
11
+ * the clock and the jti factory, so a command, a test, and an audit produce the
12
+ * same grants from the same charter.
13
+ *
14
+ * Registering the resulting client with the live provider (RFC 7591 dynamic
15
+ * registration) is a separate, network-bearing step — see `ClientRegistrar` —
16
+ * kept out of this module so the mapping stays verifiable offline.
17
+ */
18
+ /** The subset of an AAO charter this mapping reads. */
19
+ export interface CharterInput {
20
+ /** The human at the root of every chain. */
21
+ accountableTo: string;
22
+ roles: CharterRoleInput[];
23
+ /** Used to derive a stable holder id per role. Falls back to "org". */
24
+ slug?: string;
25
+ }
26
+ export interface CharterGrantsOptions {
27
+ iat: number;
28
+ exp: number;
29
+ /** Produce the jti for a role's grant (deterministic in tests, random in prod). */
30
+ jtiFor: (roleName: string) => string;
31
+ /** Produce the holder id for a role. Defaults to `<slug>/<role>`. */
32
+ holderFor?: (roleName: string) => string;
33
+ /** Optional capability→scope registry; an unmapped capability fails the run. */
34
+ scopeRegistry?: Readonly<Record<string, string>>;
35
+ }
36
+ export interface RoleGrant {
37
+ role: string;
38
+ holder: string;
39
+ grant: GrantChain;
40
+ }
41
+ export interface RoleRefusal {
42
+ role: string;
43
+ refusal: Refusal;
44
+ }
45
+ export interface CharterGrantsResult {
46
+ grants: RoleGrant[];
47
+ refusals: RoleRefusal[];
48
+ /** True when every role mapped — the init run only proceeds when this holds. */
49
+ ok: boolean;
50
+ }
51
+ /**
52
+ * The roots a relying party accepts, derived from the charters it federates with.
53
+ *
54
+ * This is the mesh binding made concrete. On the network an agent from org A
55
+ * signs in at org B; org B verifies the assertion is genuinely from Flashy ID,
56
+ * but a genuine assertion can carry a chain rooted at any accountable human
57
+ * anywhere. Org B decides *whose* authority it honours by naming the orgs it
58
+ * federates with — and every AAO charter already names the one human every one
59
+ * of its chains roots at: `accountableTo`. Passing this set to `authorize`'s
60
+ * `trustedRoots` is how "sign in with Flashy ID" stops meaning "belongs to
61
+ * someone" and starts meaning "belongs to someone this org agreed to trust".
62
+ *
63
+ * A charter with no `accountableTo` contributes nothing rather than a blank
64
+ * root, because an empty string would silently trust every chain that forgot to
65
+ * set one.
66
+ */
67
+ export declare function trustedRootsFromCharters(charters: Iterable<Pick<CharterInput, 'accountableTo'>>): Set<string>;
68
+ /**
69
+ * Map an entire charter to grants. A role whose capability is unmapped (under a
70
+ * registry) collects into `refusals` rather than issuing a narrower grant
71
+ * quietly — an init run with any refusal is not `ok`, and the command fails
72
+ * loudly rather than registering a client with silently-dropped authority.
73
+ */
74
+ export declare function grantsFromCharter(charter: CharterInput, opts: CharterGrantsOptions): CharterGrantsResult;
75
+ /**
76
+ * A one-line-per-role summary of an init run, in the shape the command prints.
77
+ * Verifies each grant as it renders — a grant that maps but does not verify is a
78
+ * bug in the kernel, and the summary surfaces it rather than hiding it.
79
+ */
80
+ export declare function summarizeGrants(result: CharterGrantsResult, nowSec: number): string[];
81
+ /**
82
+ * The network seam: registering the mapped client with the live Flashy ID
83
+ * provider via RFC 7591 dynamic client registration. Defined as an interface so
84
+ * the mapping above stays offline-verifiable; a real implementation POSTs to the
85
+ * provider's registration endpoint and returns the issued client credentials.
86
+ */
87
+ export interface ClientRegistrar {
88
+ register(input: {
89
+ clientName: string;
90
+ /** The role grants this client will exercise. */
91
+ grants: RoleGrant[];
92
+ }): Promise<{
93
+ clientId: string;
94
+ clientSecret: string;
95
+ }>;
96
+ }
@@ -0,0 +1,78 @@
1
+ import { grantFromCharterRole } from '../grants/fromCharter.js';
2
+ import { verifyChain } from '../grants/grants.js';
3
+ /**
4
+ * The roots a relying party accepts, derived from the charters it federates with.
5
+ *
6
+ * This is the mesh binding made concrete. On the network an agent from org A
7
+ * signs in at org B; org B verifies the assertion is genuinely from Flashy ID,
8
+ * but a genuine assertion can carry a chain rooted at any accountable human
9
+ * anywhere. Org B decides *whose* authority it honours by naming the orgs it
10
+ * federates with — and every AAO charter already names the one human every one
11
+ * of its chains roots at: `accountableTo`. Passing this set to `authorize`'s
12
+ * `trustedRoots` is how "sign in with Flashy ID" stops meaning "belongs to
13
+ * someone" and starts meaning "belongs to someone this org agreed to trust".
14
+ *
15
+ * A charter with no `accountableTo` contributes nothing rather than a blank
16
+ * root, because an empty string would silently trust every chain that forgot to
17
+ * set one.
18
+ */
19
+ export function trustedRootsFromCharters(charters) {
20
+ const roots = new Set();
21
+ for (const charter of charters) {
22
+ const root = charter?.accountableTo?.trim();
23
+ if (root)
24
+ roots.add(root);
25
+ }
26
+ return roots;
27
+ }
28
+ /**
29
+ * Map an entire charter to grants. A role whose capability is unmapped (under a
30
+ * registry) collects into `refusals` rather than issuing a narrower grant
31
+ * quietly — an init run with any refusal is not `ok`, and the command fails
32
+ * loudly rather than registering a client with silently-dropped authority.
33
+ */
34
+ export function grantsFromCharter(charter, opts) {
35
+ const holderFor = opts.holderFor ?? ((role) => `${charter.slug ?? 'org'}/${role}`);
36
+ const grants = [];
37
+ const refusals = [];
38
+ for (const role of charter.roles) {
39
+ const holder = holderFor(role.name);
40
+ const result = grantFromCharterRole({
41
+ accountableTo: charter.accountableTo,
42
+ role,
43
+ holder,
44
+ iat: opts.iat,
45
+ exp: opts.exp,
46
+ jti: opts.jtiFor(role.name),
47
+ scopeRegistry: opts.scopeRegistry,
48
+ });
49
+ if ('ok' in result) {
50
+ refusals.push({ role: role.name, refusal: result });
51
+ }
52
+ else {
53
+ grants.push({ role: role.name, holder, grant: result });
54
+ }
55
+ }
56
+ return { grants, refusals, ok: refusals.length === 0 };
57
+ }
58
+ /**
59
+ * A one-line-per-role summary of an init run, in the shape the command prints.
60
+ * Verifies each grant as it renders — a grant that maps but does not verify is a
61
+ * bug in the kernel, and the summary surfaces it rather than hiding it.
62
+ */
63
+ export function summarizeGrants(result, nowSec) {
64
+ const lines = [];
65
+ for (const { role, grant } of result.grants) {
66
+ const v = verifyChain(grant, nowSec);
67
+ const leaf = grant[grant.length - 1];
68
+ if (!leaf)
69
+ continue;
70
+ const status = v.ok ? 'ok' : `INVALID:${v.code}`;
71
+ const approval = leaf.lim.approval_at_or_above ?? '—';
72
+ lines.push(`${role.padEnd(22)} ${leaf.scp.join(', ')} [${approval}] ${status}`);
73
+ }
74
+ for (const { role, refusal } of result.refusals) {
75
+ lines.push(`${role.padEnd(22)} REFUSED: ${refusal.code}${refusal.detail ? ` (${refusal.detail})` : ''}`);
76
+ }
77
+ return lines;
78
+ }
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ export interface InitArgs {
3
+ /** The charter file to read. Defaults to flashyos.roles.json in the cwd. */
4
+ file: string;
5
+ /** Emit the grants as JSON instead of the human summary. */
6
+ json: boolean;
7
+ }
8
+ export declare function parseInitArgs(argv: readonly string[]): InitArgs;
9
+ export interface InitDeps {
10
+ readFile: (path: string) => string;
11
+ nowSec: number;
12
+ jtiFor: (roleName: string) => string;
13
+ log: (line: string) => void;
14
+ /** Grant lifetime in seconds. Default 90 days. */
15
+ expiresInSec?: number;
16
+ }
17
+ /**
18
+ * Run the init mapping and print it. Returns a process exit code: 0 on a clean
19
+ * run, 1 when the file is missing/malformed or any role's capability is
20
+ * unmapped — an init run that would register a client with silently-dropped
21
+ * authority fails loudly instead.
22
+ */
23
+ export declare function runInit(argv: readonly string[], deps: InitDeps): number;
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from 'node:fs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { grantsFromCharter, summarizeGrants } from './charterGrants.js';
6
+ /**
7
+ * `flashyid init` — read an organization's charter and issue the root grants its
8
+ * roles hold. The charter is already the grant, so this is a file read and a
9
+ * mapping, not a policy language to learn.
10
+ *
11
+ * Everything below the arg parse is pure and dependency-injected, so a command,
12
+ * a test, and an audit produce the same output from the same charter. The one
13
+ * network-bearing step — registering the resulting client with the live
14
+ * provider (RFC 7591) — is deliberately not here; it's the `ClientRegistrar`
15
+ * seam in charterGrants, wired by the caller that has the provider's URL.
16
+ */
17
+ const NINETY_DAYS_SEC = 90 * 24 * 3600;
18
+ export function parseInitArgs(argv) {
19
+ let file = 'flashyos.roles.json';
20
+ let json = false;
21
+ // `flashyid init [file]` — the subcommand token is routing, not a filename.
22
+ const args = argv[0] === 'init' ? argv.slice(1) : argv;
23
+ for (let i = 0; i < args.length; i++) {
24
+ const a = args[i];
25
+ if (a === '--json')
26
+ json = true;
27
+ else if (a === '--file' || a === '-f')
28
+ file = args[++i] ?? file;
29
+ else if (a && !a.startsWith('-'))
30
+ file = a;
31
+ }
32
+ return { file, json };
33
+ }
34
+ /**
35
+ * Run the init mapping and print it. Returns a process exit code: 0 on a clean
36
+ * run, 1 when the file is missing/malformed or any role's capability is
37
+ * unmapped — an init run that would register a client with silently-dropped
38
+ * authority fails loudly instead.
39
+ */
40
+ export function runInit(argv, deps) {
41
+ const args = parseInitArgs(argv);
42
+ let raw;
43
+ try {
44
+ raw = deps.readFile(args.file);
45
+ }
46
+ catch {
47
+ deps.log(`✗ could not read ${args.file}`);
48
+ return 1;
49
+ }
50
+ let charter;
51
+ try {
52
+ charter = JSON.parse(raw);
53
+ }
54
+ catch {
55
+ deps.log(`✗ ${args.file} is not valid JSON`);
56
+ return 1;
57
+ }
58
+ if (!charter.accountableTo || !Array.isArray(charter.roles)) {
59
+ deps.log('✗ a charter needs an accountableTo and a roles[] array');
60
+ return 1;
61
+ }
62
+ const exp = deps.nowSec + (deps.expiresInSec ?? NINETY_DAYS_SEC);
63
+ const result = grantsFromCharter(charter, { iat: deps.nowSec, exp, jtiFor: deps.jtiFor });
64
+ if (args.json) {
65
+ deps.log(JSON.stringify(result.grants, null, 2));
66
+ }
67
+ else {
68
+ const slug = charter.slug ?? 'org';
69
+ deps.log(`Reading ${args.file} .......... ${slug}, ${charter.roles.length} roles`);
70
+ deps.log(`Root grant ${charter.accountableTo} → ${slug}`);
71
+ for (const line of summarizeGrants(result, deps.nowSec))
72
+ deps.log(` ${line}`);
73
+ }
74
+ if (!result.ok) {
75
+ deps.log(`✗ ${result.refusals.length} role(s) refused — nothing issued`);
76
+ return 1;
77
+ }
78
+ return 0;
79
+ }
80
+ // Bin entry: wire the real filesystem, clock, and randomness. The invoked path
81
+ // is realpath'd before comparing: npm installs the bin as a symlink in .bin, so
82
+ // a naive `file://${process.argv[1]}` comparison never matches there.
83
+ function isDirectInvocation() {
84
+ const invoked = process.argv[1];
85
+ if (!invoked)
86
+ return false;
87
+ try {
88
+ return import.meta.url === pathToFileURL(realpathSync(invoked)).href;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ if (isDirectInvocation()) {
95
+ const code = runInit(process.argv.slice(2), {
96
+ readFile: (p) => readFileSync(p, 'utf8'),
97
+ nowSec: Math.floor(Date.now() / 1000),
98
+ jtiFor: () => randomUUID(),
99
+ log: (s) => console.log(s),
100
+ });
101
+ process.exit(code);
102
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @flashyid/sdk — verify a Flashy ID assertion and the delegation it carries.
3
+ *
4
+ * The whole consumer surface a relying party needs:
5
+ * - verifyAssertion: is this genuinely from Flashy ID? (signature, iss, aud, exp)
6
+ * - authorize: and does its delegation permit *this* action?
7
+ *
8
+ * plus the grant kernel re-exported, so a consumer that wants to inspect or
9
+ * re-check a chain itself has one import for everything.
10
+ */
11
+ export { verifyAssertion, authorize } from './verify.js';
12
+ export type { FlashyIdAssertion, VerifyOptions } from './verify.js';
13
+ export { signAssertion } from './sign.js';
14
+ export type { SignAssertionInput } from './sign.js';
15
+ export { issueRoot, attenuate, verifyChain, permits, rootsWithin, grantFromCharterRole, impactRank, IMPACT_ORDER, } from '../grants/index.js';
16
+ export type { GrantChain, GrantLink, Limit, Impact, RefusalCode, Refusal, EffectiveGrant, GrantResult, Demand, IssueRootInput, AttenuateInput, } from '../grants/index.js';
@@ -0,0 +1,13 @@
1
+ /**
2
+ * @flashyid/sdk — verify a Flashy ID assertion and the delegation it carries.
3
+ *
4
+ * The whole consumer surface a relying party needs:
5
+ * - verifyAssertion: is this genuinely from Flashy ID? (signature, iss, aud, exp)
6
+ * - authorize: and does its delegation permit *this* action?
7
+ *
8
+ * plus the grant kernel re-exported, so a consumer that wants to inspect or
9
+ * re-check a chain itself has one import for everything.
10
+ */
11
+ export { verifyAssertion, authorize } from './verify.js';
12
+ export { signAssertion } from './sign.js';
13
+ export { issueRoot, attenuate, verifyChain, permits, rootsWithin, grantFromCharterRole, impactRank, IMPACT_ORDER, } from '../grants/index.js';
@@ -0,0 +1,42 @@
1
+ import { type KeyLike } from 'jose';
2
+ import { type GrantChain } from '../grants/types.js';
3
+ /**
4
+ * The issuer half of @flashyid/sdk: mint a Flashy ID assertion.
5
+ *
6
+ * `verifyAssertion` is what a relying party runs; this is what the issuer runs
7
+ * to produce the JWS it verifies — an OIDC-shaped EdDSA token carrying the
8
+ * identity (`sub`) and the delegation chain (`del`) the holder acts under. The
9
+ * two are complements: anything this signs, verifyAssertion accepts (given the
10
+ * matching public key), and the round trip is the SDK's own test.
11
+ *
12
+ * The private key never leaves the issuer. A relying party holds only the
13
+ * public JWKS — it can check an assertion but never mint one.
14
+ */
15
+ export interface SignAssertionInput {
16
+ /** The EdDSA private key (jose KeyLike or the raw key). Issuer-only. */
17
+ privateKey: KeyLike | Uint8Array;
18
+ /** The issuer — the value that lands in `iss`, e.g. https://id.flashyid.com. */
19
+ issuer: string;
20
+ /** The relying party this assertion is for — lands in `aud`. */
21
+ audience: string;
22
+ /** The acting principal: an agent surrogate, an org id, or a human. */
23
+ subject: string;
24
+ /** The delegation chain the subject acts under, root-first. */
25
+ delegation?: GrantChain;
26
+ /** Seconds until the assertion expires. Default 3600 (one hour). */
27
+ expiresInSec?: number;
28
+ /** The token id — carry the same value you use for replay/idempotency. */
29
+ jti?: string;
30
+ /** The signing key id, published in the JWKS so a verifier can select it. */
31
+ kid?: string;
32
+ /** Any additional claims to include alongside the standard ones. */
33
+ extraClaims?: Record<string, unknown>;
34
+ /**
35
+ * Issued-at, seconds since epoch. Defaults to now. Note a verifier checks the
36
+ * assertion's expiry against the real clock, so in production leave this
37
+ * unset; it exists for deterministic issuance in tests.
38
+ */
39
+ iatSec?: number;
40
+ }
41
+ /** Mint and sign a Flashy ID assertion, returning the compact JWS string. */
42
+ export declare function signAssertion(input: SignAssertionInput): Promise<string>;
@@ -0,0 +1,19 @@
1
+ import { SignJWT } from 'jose';
2
+ /** Mint and sign a Flashy ID assertion, returning the compact JWS string. */
3
+ export async function signAssertion(input) {
4
+ const iat = input.iatSec ?? Math.floor(Date.now() / 1000);
5
+ const exp = iat + (input.expiresInSec ?? 3600);
6
+ const payload = { ...(input.extraClaims ?? {}) };
7
+ if (input.delegation)
8
+ payload.del = input.delegation;
9
+ const signer = new SignJWT(payload)
10
+ .setProtectedHeader({ alg: 'EdDSA', ...(input.kid ? { kid: input.kid } : {}) })
11
+ .setIssuer(input.issuer)
12
+ .setAudience(input.audience)
13
+ .setSubject(input.subject)
14
+ .setIssuedAt(iat)
15
+ .setExpirationTime(exp);
16
+ if (input.jti)
17
+ signer.setJti(input.jti);
18
+ return signer.sign(input.privateKey);
19
+ }
@@ -0,0 +1,85 @@
1
+ import { type JWTVerifyGetKey, type KeyLike } from 'jose';
2
+ import { type Demand } from '../grants/grants.js';
3
+ import { type GrantChain, type GrantResult } from '../grants/types.js';
4
+ /**
5
+ * @flashyid/sdk — the relying-party verify surface.
6
+ *
7
+ * A relying party asks two questions of a Flashy ID assertion, and this answers
8
+ * both from one import:
9
+ *
10
+ * 1. Is this assertion genuinely from Flashy ID? — signature against the
11
+ * published JWKS, issuer, audience, expiry.
12
+ * 2. Does the delegation it carries actually authorize *this* action? — the
13
+ * grant chain in the assertion, verified and checked against a demand.
14
+ *
15
+ * The verify path holds no secret. It fetches only the public JWKS, so a relying
16
+ * party can never mint an assertion, only check one — the property the whole
17
+ * asymmetric design exists to provide.
18
+ */
19
+ /** The identity + delegation an assertion carries, once verified. */
20
+ export interface FlashyIdAssertion {
21
+ /** The subject the assertion is about (the acting principal). */
22
+ sub: string;
23
+ /** The delegation chain, root-first, if the assertion carries one. */
24
+ del?: GrantChain;
25
+ /** Raw verified claims, for anything the typed surface doesn't name. */
26
+ claims: Record<string, unknown>;
27
+ }
28
+ export interface VerifyOptions {
29
+ /** Flashy ID issuer, e.g. https://id.flashyid.com — must match the token `iss`. */
30
+ issuer: string;
31
+ /** This relying party's client id — must match the token `aud`. */
32
+ audience: string;
33
+ /** Injectable for tests; defaults to the issuer's /.well-known/jwks.json. */
34
+ getKey?: JWTVerifyGetKey | KeyLike | Uint8Array;
35
+ }
36
+ /**
37
+ * Verify an assertion's signature and standard claims. Returns the identity and
38
+ * any delegation it carries, or null if the token is missing, malformed,
39
+ * expired, wrong-issuer, wrong-audience, or fails signature verification. Never
40
+ * throws — a bad token is a null, which a relying party turns into a 401.
41
+ *
42
+ * The `del` claim is shape-validated before it is typed as a chain: a `del`
43
+ * that is present but not a well-formed GrantChain is left off the returned
44
+ * assertion (`del: undefined`) rather than cast and trusted. The raw claim
45
+ * stays visible in `claims`, so `authorize` can distinguish "no delegation"
46
+ * from "malformed delegation" and refuse the latter explicitly.
47
+ */
48
+ export declare function verifyAssertion(token: string | undefined | null, opts: VerifyOptions): Promise<FlashyIdAssertion | null>;
49
+ /**
50
+ * The full relying-party check: verify the assertion, then verify the delegation
51
+ * it carries authorizes a specific action. One call, one boolean-ish answer,
52
+ * with a specific refusal when it fails.
53
+ *
54
+ * Returns the effective grant on success. Returns null when the assertion itself
55
+ * doesn't verify (a 401 for the relying party). Returns a refusal when the
56
+ * assertion is genuine but its delegation is malformed, unsound, not held by
57
+ * the assertion's subject, or doesn't permit the demand (a 403 — and the
58
+ * refusal code says which).
59
+ *
60
+ * Two checks beyond the chain's own soundness:
61
+ * - The chain's leaf holder must be the assertion's `sub` — an assertion for
62
+ * A carrying a chain delegated to B is refused (`broken_chain`), since the
63
+ * acting principal would not be the one the authority rests with.
64
+ * - The human-approval bar is enforced by `permits`: a demand whose `impact`
65
+ * is at or above the chain's effective `approval_at_or_above` is refused
66
+ * with `approval_required`, never silently allowed. A relying party that
67
+ * can route to a human for a co-signature should use the enforcement
68
+ * gate's `evaluateGrant`, which turns that same refusal into ESCALATE.
69
+ */
70
+ export declare function authorize(token: string | undefined | null, demand: Demand, opts: VerifyOptions & {
71
+ nowSec: number;
72
+ revokedJtis?: ReadonlySet<string>;
73
+ /**
74
+ * The roots this relying party accepts authority from — the `iss` of each
75
+ * chain's root link, typically the `accountableTo` of every AAO charter it
76
+ * federates with. When set, a sound chain that roots elsewhere is refused
77
+ * with `untrusted_root`. Omit to accept any root (single-issuer use); a mesh
78
+ * relying party that admits identities from other orgs should always set it,
79
+ * or "verified" means only "belongs to someone", not "someone we trust".
80
+ */
81
+ trustedRoots?: Iterable<string>;
82
+ }): Promise<{
83
+ assertion: FlashyIdAssertion;
84
+ result: GrantResult;
85
+ } | null>;
@@ -0,0 +1,134 @@
1
+ import { jwtVerify, createRemoteJWKSet } from 'jose';
2
+ import { verifyChain, permits, rootsWithin } from '../grants/grants.js';
3
+ import { IMPACT_ORDER } from '../grants/types.js';
4
+ function isStringArray(v) {
5
+ return Array.isArray(v) && v.every((x) => typeof x === 'string');
6
+ }
7
+ function isLimit(v) {
8
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
9
+ return false;
10
+ const lim = v;
11
+ if (lim.approval_at_or_above !== undefined && !IMPACT_ORDER.includes(lim.approval_at_or_above)) {
12
+ return false;
13
+ }
14
+ if (lim.spend_max !== undefined && typeof lim.spend_max !== 'number')
15
+ return false;
16
+ return true;
17
+ }
18
+ function isGrantLink(v) {
19
+ if (typeof v !== 'object' || v === null)
20
+ return false;
21
+ const l = v;
22
+ return (typeof l.iss === 'string' &&
23
+ typeof l.sub === 'string' &&
24
+ isStringArray(l.scp) &&
25
+ isStringArray(l.res) &&
26
+ isLimit(l.lim) &&
27
+ typeof l.iat === 'number' &&
28
+ typeof l.exp === 'number' &&
29
+ typeof l.jti === 'string');
30
+ }
31
+ /**
32
+ * A `del` claim is attacker-adjacent wire data: it arrives inside a signed
33
+ * token, but nothing about the signature guarantees the claim has the shape
34
+ * the grant kernel assumes. Validate it before it is ever typed as a chain.
35
+ */
36
+ function isGrantChain(v) {
37
+ return Array.isArray(v) && v.every(isGrantLink);
38
+ }
39
+ const remoteKeySets = new Map();
40
+ function remoteKeyFor(issuer) {
41
+ const existing = remoteKeySets.get(issuer);
42
+ if (existing)
43
+ return existing;
44
+ const set = createRemoteJWKSet(new URL(`${issuer.replace(/\/+$/, '')}/.well-known/jwks.json`));
45
+ remoteKeySets.set(issuer, set);
46
+ return set;
47
+ }
48
+ /**
49
+ * Verify an assertion's signature and standard claims. Returns the identity and
50
+ * any delegation it carries, or null if the token is missing, malformed,
51
+ * expired, wrong-issuer, wrong-audience, or fails signature verification. Never
52
+ * throws — a bad token is a null, which a relying party turns into a 401.
53
+ *
54
+ * The `del` claim is shape-validated before it is typed as a chain: a `del`
55
+ * that is present but not a well-formed GrantChain is left off the returned
56
+ * assertion (`del: undefined`) rather than cast and trusted. The raw claim
57
+ * stays visible in `claims`, so `authorize` can distinguish "no delegation"
58
+ * from "malformed delegation" and refuse the latter explicitly.
59
+ */
60
+ export async function verifyAssertion(token, opts) {
61
+ if (!token)
62
+ return null;
63
+ const key = opts.getKey ?? remoteKeyFor(opts.issuer);
64
+ try {
65
+ const { payload } = await jwtVerify(token, key, {
66
+ issuer: opts.issuer,
67
+ audience: opts.audience,
68
+ });
69
+ if (typeof payload.sub !== 'string' || !payload.sub)
70
+ return null;
71
+ const del = isGrantChain(payload.del) ? payload.del : undefined;
72
+ return { sub: payload.sub, del, claims: payload };
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
78
+ /**
79
+ * The full relying-party check: verify the assertion, then verify the delegation
80
+ * it carries authorizes a specific action. One call, one boolean-ish answer,
81
+ * with a specific refusal when it fails.
82
+ *
83
+ * Returns the effective grant on success. Returns null when the assertion itself
84
+ * doesn't verify (a 401 for the relying party). Returns a refusal when the
85
+ * assertion is genuine but its delegation is malformed, unsound, not held by
86
+ * the assertion's subject, or doesn't permit the demand (a 403 — and the
87
+ * refusal code says which).
88
+ *
89
+ * Two checks beyond the chain's own soundness:
90
+ * - The chain's leaf holder must be the assertion's `sub` — an assertion for
91
+ * A carrying a chain delegated to B is refused (`broken_chain`), since the
92
+ * acting principal would not be the one the authority rests with.
93
+ * - The human-approval bar is enforced by `permits`: a demand whose `impact`
94
+ * is at or above the chain's effective `approval_at_or_above` is refused
95
+ * with `approval_required`, never silently allowed. A relying party that
96
+ * can route to a human for a co-signature should use the enforcement
97
+ * gate's `evaluateGrant`, which turns that same refusal into ESCALATE.
98
+ */
99
+ export async function authorize(token, demand, opts) {
100
+ const assertion = await verifyAssertion(token, opts);
101
+ if (!assertion)
102
+ return null;
103
+ if (!assertion.del) {
104
+ // verifyAssertion drops a `del` that fails shape validation; the raw claim
105
+ // tells malformed apart from absent, and each refuses with its own reason.
106
+ if (assertion.claims.del !== undefined) {
107
+ return { assertion, result: { ok: false, code: 'broken_chain', detail: 'delegation is not a well-formed grant chain' } };
108
+ }
109
+ return { assertion, result: { ok: false, code: 'empty_chain', detail: 'assertion carries no delegation' } };
110
+ }
111
+ const verified = verifyChain(assertion.del, opts.nowSec, opts.revokedJtis ?? new Set());
112
+ if (!verified.ok)
113
+ return { assertion, result: verified };
114
+ if (verified.holder !== assertion.sub) {
115
+ return {
116
+ assertion,
117
+ result: {
118
+ ok: false,
119
+ code: 'broken_chain',
120
+ detail: `chain leaf holder ${verified.holder} is not the assertion subject ${assertion.sub}`,
121
+ },
122
+ };
123
+ }
124
+ // The mesh binding: a sound, subject-held chain still has to root where this
125
+ // party agreed. Checked before permits so an untrusted root cannot be masked
126
+ // by also lacking the demanded scope.
127
+ if (opts.trustedRoots !== undefined) {
128
+ const rooted = rootsWithin(verified, opts.trustedRoots);
129
+ if (rooted !== true)
130
+ return { assertion, result: rooted };
131
+ }
132
+ const p = permits(verified, demand);
133
+ return { assertion, result: p === true ? verified : p };
134
+ }
@@ -0,0 +1,56 @@
1
+ # The enforcement gate
2
+
3
+ A governance layer that only *records* has a liability ceiling — regulated
4
+ buyers need a decision that can *gate*. The enforcement gate turns the delegated
5
+ -authority grant kernel into exactly that, without inventing a new policy engine:
6
+ the kernel already answers "does a signed, unrevoked, in-mandate grant permit
7
+ this action?" — the gate maps that answer onto the three outcomes a caller can
8
+ act on.
9
+
10
+ This is the FlashyOS response to the institutional (AURORA) brief's #1-CRITICAL
11
+ ask: expose `authorize()` as a synchronous gate on `decide()`.
12
+
13
+ ## The three answers
14
+
15
+ | Action | When |
16
+ |---|---|
17
+ | `ALLOW` | the grant permits the action, below the human-approval bar — proceed |
18
+ | `ESCALATE` | permitted, but the action's impact is **at or above** the chain's `approval_at_or_above` — a named human must co-sign |
19
+ | `DENY` | the chain is unsound (`expired`, `revoked`, `chain_widened`, `broken_chain`) or the action is `out_of_mandate` (scope / resource / spend exceeded) |
20
+
21
+ `DENY` carries the kernel's `RefusalCode`, so the "why" is auditable. `ESCALATE`
22
+ carries the impact bar that triggered it.
23
+
24
+ ## API
25
+
26
+ ```ts
27
+ import { evaluateGrant, enforce, recordOnly, grantAdapter } from '@flashyid/sdk';
28
+
29
+ // Pure decision — no clock, no I/O. Same answer for issuer, RP, and auditor.
30
+ const result = evaluateGrant(chain, { scope: 'seal', impact: 'CRITICAL' }, { nowSec });
31
+ // → { action: 'ESCALATE', escalateAtOrAbove: 'CRITICAL' }
32
+ ```
33
+
34
+ - `evaluateGrant(chain, demand, { nowSec, revokedJtis })` — the pure core.
35
+ - `EnforcementAdapter` — `evaluate(decision) => Promise<EnforcementResult>`; the
36
+ seam an enterprise registers to gate decisions.
37
+ - `grantAdapter()` — an adapter backed by `evaluateGrant` (the real gate).
38
+ - `recordOnly` — the default adapter: always `ALLOW`. An org with no adapter, or
39
+ an unreachable one, must never have its agents halted.
40
+ - `enforce(decision, adapter, { timeoutMs = 5000, onUnavailable })` — the
41
+ operational contract: await the adapter within a timeout; on error or timeout,
42
+ fall back to `ALLOW` (recorded only) and raise `onUnavailable` — the CRITICAL
43
+ alert an operator wires to monitoring.
44
+
45
+ ## Design posture
46
+
47
+ The gate **preserves "never block"** as the default. Gating is opt-in: only an
48
+ org that registers an adapter is gated, and even then an unreachable adapter
49
+ falls back to record-only rather than halting the agent's critical path. This is
50
+ the honest-governance posture the brief called sound — extended, not replaced,
51
+ with a real gate for those who want one. A natural commercial tier
52
+ ("Governance Pro") sits exactly here.
53
+
54
+ Tests: `src/enforce/gate.test.ts` — ALLOW / ESCALATE / DENY across scope, spend,
55
+ expiry, and revocation; record-only default; adapter throw + timeout fallback
56
+ with the alert firing.