@astram/core 0.1.0 → 1.1.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.
Files changed (142) hide show
  1. package/dist/admin/admin-service.d.ts +1 -1
  2. package/dist/admin/command/grants.js +3 -3
  3. package/dist/admin/command/grants.js.map +1 -1
  4. package/dist/admin/command/invitations.d.ts +2 -2
  5. package/dist/admin/command/invitations.js +8 -8
  6. package/dist/admin/command/invitations.js.map +1 -1
  7. package/dist/admin/command/service-accounts.d.ts +1 -1
  8. package/dist/admin/command/service-accounts.js +1 -1
  9. package/dist/admin/query/simulate.d.ts.map +1 -1
  10. package/dist/admin/query/simulate.js +4 -0
  11. package/dist/admin/query/simulate.js.map +1 -1
  12. package/dist/admin/safeguards-impl.d.ts +2 -2
  13. package/dist/admin/safeguards-impl.js +9 -9
  14. package/dist/admin/safeguards-impl.js.map +1 -1
  15. package/dist/admin/safeguards.d.ts +4 -4
  16. package/dist/admin/safeguards.js +4 -4
  17. package/dist/admin/types.d.ts +1 -1
  18. package/dist/admin/types.d.ts.map +1 -1
  19. package/dist/authentication/authenticator.d.ts +2 -2
  20. package/dist/authentication/authenticator.js +2 -2
  21. package/dist/authentication/authenticator.js.map +1 -1
  22. package/dist/authentication/credential-resolver.d.ts +1 -1
  23. package/dist/authorization/cross-tenant/grant-evaluator.d.ts +2 -2
  24. package/dist/authorization/cross-tenant/grant-evaluator.js +2 -2
  25. package/dist/authorization/decision-authority.d.ts +2 -2
  26. package/dist/authorization/decision-authority.d.ts.map +1 -1
  27. package/dist/authorization/decision-authority.js +11 -3
  28. package/dist/authorization/decision-authority.js.map +1 -1
  29. package/dist/authorization/errors.d.ts +37 -0
  30. package/dist/authorization/errors.d.ts.map +1 -1
  31. package/dist/authorization/errors.js +43 -0
  32. package/dist/authorization/errors.js.map +1 -1
  33. package/dist/authorization/gates/object-type.d.ts +2 -2
  34. package/dist/authorization/gates/object-type.d.ts.map +1 -1
  35. package/dist/authorization/gates/object-type.js +20 -7
  36. package/dist/authorization/gates/object-type.js.map +1 -1
  37. package/dist/authorization/gates/tenant.d.ts +3 -3
  38. package/dist/authorization/gates/tenant.js +7 -7
  39. package/dist/authorization/gates/tenant.js.map +1 -1
  40. package/dist/authorization/index.d.ts +33 -4
  41. package/dist/authorization/index.d.ts.map +1 -1
  42. package/dist/authorization/index.js +39 -4
  43. package/dist/authorization/index.js.map +1 -1
  44. package/dist/authorization/ports.d.ts +3 -3
  45. package/dist/authorization/reason-codes.d.ts +7 -1
  46. package/dist/authorization/reason-codes.d.ts.map +1 -1
  47. package/dist/authorization/reason-codes.js +9 -1
  48. package/dist/authorization/reason-codes.js.map +1 -1
  49. package/dist/authorization/record/owner-baseline.d.ts +43 -0
  50. package/dist/authorization/record/owner-baseline.d.ts.map +1 -0
  51. package/dist/authorization/record/owner-baseline.js +72 -0
  52. package/dist/authorization/record/owner-baseline.js.map +1 -0
  53. package/dist/authorization/record/permit-tier.d.ts.map +1 -1
  54. package/dist/authorization/record/permit-tier.js +16 -5
  55. package/dist/authorization/record/permit-tier.js.map +1 -1
  56. package/dist/identity/broker.d.ts +8 -8
  57. package/dist/identity/broker.d.ts.map +1 -1
  58. package/dist/identity/broker.js +8 -8
  59. package/dist/identity/broker.js.map +1 -1
  60. package/dist/identity/claim-mapper.d.ts +8 -8
  61. package/dist/identity/claim-mapper.d.ts.map +1 -1
  62. package/dist/identity/claim-mapper.js +4 -4
  63. package/dist/identity/index.d.ts +2 -2
  64. package/dist/identity/index.d.ts.map +1 -1
  65. package/dist/identity/internal-adapter.d.ts +12 -12
  66. package/dist/identity/internal-adapter.d.ts.map +1 -1
  67. package/dist/identity/internal-adapter.js +9 -9
  68. package/dist/identity/internal-adapter.js.map +1 -1
  69. package/dist/metadata/index.d.ts +43 -0
  70. package/dist/metadata/index.d.ts.map +1 -1
  71. package/dist/metadata/index.js +6 -0
  72. package/dist/metadata/index.js.map +1 -1
  73. package/dist/metadata/registry.d.ts.map +1 -1
  74. package/dist/metadata/registry.js +2 -1
  75. package/dist/metadata/registry.js.map +1 -1
  76. package/dist-cjs/admin/admin-service.js +159 -0
  77. package/dist-cjs/admin/command/grants.js +200 -0
  78. package/dist-cjs/admin/command/index.js +38 -0
  79. package/dist-cjs/admin/command/invitations.js +246 -0
  80. package/dist-cjs/admin/command/permissions.js +69 -0
  81. package/dist-cjs/admin/command/pipeline.js +110 -0
  82. package/dist-cjs/admin/command/policies.js +223 -0
  83. package/dist-cjs/admin/command/service-accounts.js +278 -0
  84. package/dist-cjs/admin/command/service.js +130 -0
  85. package/dist-cjs/admin/command/tiers.js +81 -0
  86. package/dist-cjs/admin/index.js +78 -0
  87. package/dist-cjs/admin/ports.js +41 -0
  88. package/dist-cjs/admin/query/audit-view.js +88 -0
  89. package/dist-cjs/admin/query/catalog.js +174 -0
  90. package/dist-cjs/admin/query/explain.js +149 -0
  91. package/dist-cjs/admin/query/index.js +74 -0
  92. package/dist-cjs/admin/query/simulate.js +98 -0
  93. package/dist-cjs/admin/safeguards-impl.js +322 -0
  94. package/dist-cjs/admin/safeguards.js +95 -0
  95. package/dist-cjs/admin/types.js +40 -0
  96. package/dist-cjs/audit/audit-recorder.js +269 -0
  97. package/dist-cjs/audit/canonicalize.js +176 -0
  98. package/dist-cjs/audit/errors.js +44 -0
  99. package/dist-cjs/audit/index.js +39 -0
  100. package/dist-cjs/audit/ports.js +27 -0
  101. package/dist-cjs/audit/sensitive.js +162 -0
  102. package/dist-cjs/audit/walk.js +123 -0
  103. package/dist-cjs/authentication/authenticator.js +210 -0
  104. package/dist-cjs/authentication/credential-resolver.js +21 -0
  105. package/dist-cjs/authentication/index.js +42 -0
  106. package/dist-cjs/authentication/password-hasher.js +21 -0
  107. package/dist-cjs/authentication/totp.js +155 -0
  108. package/dist-cjs/authorization/cross-tenant/grant-evaluator.js +167 -0
  109. package/dist-cjs/authorization/decision-authority.js +213 -0
  110. package/dist-cjs/authorization/default-gates.js +53 -0
  111. package/dist-cjs/authorization/delegation/operation-identity.js +226 -0
  112. package/dist-cjs/authorization/errors.js +110 -0
  113. package/dist-cjs/authorization/gates/object-type.js +192 -0
  114. package/dist-cjs/authorization/gates/tenant.js +89 -0
  115. package/dist-cjs/authorization/gates/wiring.js +59 -0
  116. package/dist-cjs/authorization/index.js +134 -0
  117. package/dist-cjs/authorization/ports.js +36 -0
  118. package/dist-cjs/authorization/reason-codes.js +117 -0
  119. package/dist-cjs/authorization/record/owner-baseline.js +74 -0
  120. package/dist-cjs/authorization/record/permit-tier.js +92 -0
  121. package/dist-cjs/authorization/record/rule-evaluator.js +128 -0
  122. package/dist-cjs/authorization/record/shares.js +110 -0
  123. package/dist-cjs/identity/broker.js +139 -0
  124. package/dist-cjs/identity/claim-mapper.js +51 -0
  125. package/dist-cjs/identity/index.js +39 -0
  126. package/dist-cjs/identity/internal-adapter.js +91 -0
  127. package/dist-cjs/index.js +63 -0
  128. package/dist-cjs/metadata/completeness.js +108 -0
  129. package/dist-cjs/metadata/dependencies.js +110 -0
  130. package/dist-cjs/metadata/index.js +76 -0
  131. package/dist-cjs/metadata/registry.js +207 -0
  132. package/dist-cjs/package.json +3 -0
  133. package/dist-cjs/risk/evaluator.js +63 -0
  134. package/dist-cjs/risk/index.js +35 -0
  135. package/dist-cjs/risk/risk-engine.js +290 -0
  136. package/dist-cjs/risk/signals.js +106 -0
  137. package/dist-cjs/risk/thresholds.js +63 -0
  138. package/dist-cjs/session/index.js +35 -0
  139. package/dist-cjs/session/lifetimes.js +70 -0
  140. package/dist-cjs/session/ports.js +23 -0
  141. package/dist-cjs/session/session-authority.js +398 -0
  142. package/package.json +13 -10
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ /**
3
+ * Per-record SHARE + cross-tenant-grant half of gate 6 (§7.3.4 / §9.2, ADR-0006 +
4
+ * ADR-0009) — TEAM C's slice of the record permit tier.
5
+ *
6
+ * ⛔ THIS IS NOT THE FINAL GATE 6. Gate 6 is a UNION of two widening permit sources
7
+ * under a deny-wins policy:
8
+ *
9
+ * gate6 = (policy allows) OR (share/cross-tenant grant permits) [union]
10
+ * — but an EXPLICIT policy deny OVERRIDES everything [deny-wins]
11
+ *
12
+ * TEAM B owns the POLICY half (`record/rule-evaluator.ts`: rule allow + explicitDeny).
13
+ * TEAM C (this file) owns the SHARE + CROSS-TENANT-GRANT half. The INTEGRATION owner
14
+ * composes the two into the single `recordPermit` `RecordPermitFn` the pipeline calls
15
+ * at gate 6, applying deny-wins (explicit policy deny beats any share widening). The
16
+ * `createRecordShareGate` exported here is a SHARE-ONLY view for INDEPENDENT testing —
17
+ * it is NOT the final gate 6 and MUST NOT be injected as such (in the composed gate a
18
+ * policy rule could still permit even when no share exists).
19
+ *
20
+ * ── WHAT A SHARE PERMITS (`evaluateRecordShare`), record-level resources only:
21
+ * (1) **Same-tenant share** — {@link RecordSharePort.hasShare} is `true` (STRICT
22
+ * `=== true`) for this principal/roles on this record+action (ADR-0006).
23
+ * (2) **Cross-tenant grant** — when the principal's tenant differs from the
24
+ * resource's owning tenant, a cross-tenant grant covering this record+action is
25
+ * ITSELF the share for the cross-tenant case (§7.3.4). Evaluated via the shared
26
+ * {@link isCrossTenantGrantApplicable} helper (the SAME ceiling+scope logic
27
+ * gates 3 and 5 use — single-sourced, no duplication).
28
+ * The two are UNIONED: permitted if (1) OR (2).
29
+ *
30
+ * ── STRICT `=== true` on the port boolean (the Layer-5/6 fail-open bug class): the
31
+ * share verdict is routed through `strictTrue` — a truthy non-boolean is NOT a
32
+ * permit.
33
+ *
34
+ * ── TRANSIENT-vs-DENY (ADR-0016): neither path catches. A `false`/`null` from a port
35
+ * is a normal data-absence (no permit). An {@link AuthorizationUnavailableError}
36
+ * (or any other error) PROPAGATES so `decide()` can classify it — a transient is
37
+ * NEVER swallowed into a "no permit". A share/grant is never fabricated on error.
38
+ *
39
+ * ── PURE + zero-dep (ADR-0003): no framework / DB / node imports; the only I/O is
40
+ * through the injected ports reached via `ctx.deps`.
41
+ */
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.evaluateRecordShare = evaluateRecordShare;
44
+ exports.createRecordShareGate = createRecordShareGate;
45
+ const decision_authority_js_1 = require("../decision-authority.js");
46
+ const reason_codes_js_1 = require("../reason-codes.js");
47
+ const grant_evaluator_js_1 = require("../cross-tenant/grant-evaluator.js");
48
+ /**
49
+ * Does a same-tenant share OR an in-scope cross-tenant grant permit `ctx.action` on
50
+ * `ctx.resource` for `ctx.principal`? The pure boolean the composed gate 6 unions with
51
+ * TEAM B's policy result.
52
+ *
53
+ * Only meaningful for `resource.level === 'record'` (shares + record-scoped grants are
54
+ * record-level). For a non-record resource there is no per-record share to evaluate →
55
+ * returns `false` (no share permit; the coarse gate 5 already governs feature/
56
+ * object-type level, and the caller/integration never invokes this off the record path).
57
+ *
58
+ * @returns `true` iff (same-tenant share) OR (applicable cross-tenant grant). Any
59
+ * transient/other error from a consulted port PROPAGATES (never swallowed).
60
+ */
61
+ async function evaluateRecordShare(ctx, options = {}) {
62
+ const { principal, action, resource, deps } = ctx;
63
+ // Shares/ACL + record-scoped grants are RECORD-level. Off the record path there is
64
+ // no per-record share source to widen with — no share permit.
65
+ if (resource.level !== 'record') {
66
+ return false;
67
+ }
68
+ // A record-level resource without a record id cannot be matched to a share/grant —
69
+ // fail closed (no permit).
70
+ if (resource.recordId === undefined || resource.recordId.length === 0) {
71
+ return false;
72
+ }
73
+ // (1) Same-tenant share (ADR-0006). STRICT `=== true` — a truthy non-boolean from a
74
+ // misbehaving adapter is NOT a permit. A transient throw propagates (not caught).
75
+ const shareVerdict = await deps.recordShare.hasShare(principal.id, principal.roleIds, resource.typeKey, resource.recordId, action.key);
76
+ if ((0, reason_codes_js_1.strictTrue)(shareVerdict)) {
77
+ return true;
78
+ }
79
+ // (2) Cross-tenant grant as the share (§7.3.4) — ONLY when the principal is reaching
80
+ // ACROSS a tenant boundary. Same-tenant callers never consult the cross-tenant path
81
+ // (a same-tenant record is governed by the same-tenant share + policy alone).
82
+ if (resource.tenantId !== undefined && principal.tenantId !== resource.tenantId) {
83
+ const verdict = await (0, grant_evaluator_js_1.isCrossTenantGrantApplicable)(deps.crossTenantGrant, { principal, action, resource }, options);
84
+ if (verdict.applicable) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
90
+ /**
91
+ * Build the SHARE-ONLY gate 6 view — a {@link RecordPermitFn} that decides purely on
92
+ * the share/cross-tenant-grant half, for INDEPENDENT testing of TEAM C's slice.
93
+ *
94
+ * ⛔ NOT the final gate 6. It renders:
95
+ * - a share/grant permits ⇒ `gateAllow()` (via {@link evaluateRecordShare});
96
+ * - none permits ⇒ `gateDeny(denyNoRecordPermit())`.
97
+ * It has NO knowledge of policy rules — in the COMPOSED gate 6 a policy rule could
98
+ * still permit (union) even when this returns deny, and an explicit policy deny would
99
+ * override even a share permit (deny-wins). The integration owner composes this with
100
+ * TEAM B's rule evaluator; do NOT inject this as `DecisionAuthorityDeps.gates.recordPermit`.
101
+ */
102
+ function createRecordShareGate(options = {}) {
103
+ return async (ctx) => {
104
+ const permitted = await evaluateRecordShare(ctx, options);
105
+ // A share/grant is a WIDENING permit; absence of one is a normal `no_record_permit`
106
+ // Deny INPUT (not an error). This share-only view never returns `explicit_deny_policy`
107
+ // (that is TEAM B's policy signal) and never `continue` (the record tier is terminal).
108
+ return permitted ? (0, decision_authority_js_1.gateAllow)() : (0, decision_authority_js_1.gateDeny)((0, reason_codes_js_1.denyNoRecordPermit)());
109
+ };
110
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ /**
3
+ * The Identity **normalization core** — the body behind the frozen
4
+ * {@link IdentityBroker} seam (`./index.ts`). Turns an ALREADY-VERIFIED
5
+ * {@link ExternalIdentityAssertion} into ONE tenant-bound {@link Principal},
6
+ * uniformly for every principal kind (ADR-0007: no is-this-a-machine branch).
7
+ *
8
+ * SCOPE — shape the WHO, nothing more:
9
+ * - dispatch on `assertion.source` → the registered {@link IdentityClaimMapper};
10
+ * - map claims → candidate fields;
11
+ * - VALIDATE + tenant-bind → a safe Principal, or REJECT (fail-closed).
12
+ *
13
+ * OUT of scope (later steps, deliberately absent here): proving identity
14
+ * (no credential/MFA/WebAuthn verification — Authentication, step 5), session
15
+ * lifecycle (step 6), service-account credential lifecycle (Authentication). This
16
+ * core ASSUMES the assertion is authentic and only maps + tenant-binds + rejects
17
+ * malformed/unknown.
18
+ *
19
+ * Two security invariants, both fail-closed:
20
+ * 1. TENANT-BINDING — every Principal MUST be bound to exactly one non-empty
21
+ * tenant; a missing/empty tenant REJECTS (§2/§7.3, tenant is the boundary).
22
+ * 2. ROOT SAFETY — `isRoot` defaults `false` and is honored
23
+ * ONLY from a mapper's trusted `trustedRootSignal`; an attacker-supplied
24
+ * `superuser`/`isPlatformSuperuser` claim can never flip it (default-deny).
25
+ *
26
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.IdentityNormalizationError = void 0;
30
+ exports.createIdentityBroker = createIdentityBroker;
31
+ const claim_mapper_js_1 = require("./claim-mapper.js");
32
+ const internal_adapter_js_1 = require("./internal-adapter.js");
33
+ /** The set of valid principal kinds — the ONLY accepted `kind` values (§7.1). */
34
+ const VALID_PRINCIPAL_KINDS = new Set([
35
+ 'user',
36
+ 'role_group',
37
+ 'service_account',
38
+ ]);
39
+ /** Kind defaults to `user` when a mapper leaves it absent. */
40
+ const DEFAULT_PRINCIPAL_KIND = 'user';
41
+ /** Thrown when an assertion cannot be normalized into a safe Principal. */
42
+ class IdentityNormalizationError extends Error {
43
+ constructor(message) {
44
+ super(message);
45
+ this.name = 'IdentityNormalizationError';
46
+ }
47
+ }
48
+ exports.IdentityNormalizationError = IdentityNormalizationError;
49
+ /**
50
+ * The concrete normalization core. Stateless per call; holds only the mapper
51
+ * registry (its dispatch table). Instances come from {@link createIdentityBroker}.
52
+ */
53
+ class BrokerImpl {
54
+ registry;
55
+ constructor(registry) {
56
+ this.registry = registry;
57
+ }
58
+ async normalize(assertion) {
59
+ // --- Guard the input SHAPE before destructuring: a null/undefined/non-object
60
+ // assertion must fail closed with the SAME typed error as every other
61
+ // rejection (not a raw TypeError from destructuring), so a caller
62
+ // catching IdentityNormalizationError → 400/401 never leaks a 500. ---
63
+ if (assertion === null || typeof assertion !== 'object') {
64
+ throw new IdentityNormalizationError('normalize: assertion must be a non-null object (ExternalIdentityAssertion)');
65
+ }
66
+ // --- Dispatch: unknown/unregistered source → REJECT (never fabricate). ---
67
+ const { source } = assertion;
68
+ if (typeof source !== 'string' || source.length === 0) {
69
+ throw new IdentityNormalizationError('normalize: assertion.source must be a non-empty string');
70
+ }
71
+ const mapper = this.registry.resolve(source);
72
+ if (mapper === undefined) {
73
+ throw new IdentityNormalizationError(`normalize: no identity adapter registered for source "${source}" (unknown/unregistered source — fail-closed, no principal fabricated)`);
74
+ }
75
+ // --- Map claims → candidate fields (mapper does NOT validate/enforce). ---
76
+ const claims = assertion.claims ?? {};
77
+ const candidate = mapper.map(claims);
78
+ // --- Enforce invariants (fail-closed): a violation REJECTS; we never return
79
+ // a partial/unsafe Principal. ---
80
+ // id — non-empty, stable, opaque.
81
+ const id = candidate.id;
82
+ if (typeof id !== 'string' || id.length === 0) {
83
+ throw new IdentityNormalizationError(`normalize: assertion from "${source}" produced no stable principal id (fail-closed)`);
84
+ }
85
+ // tenantId — TENANT-BINDING: exactly one non-empty tenant, or REJECT.
86
+ const tenantId = candidate.tenantId;
87
+ if (typeof tenantId !== 'string' || tenantId.length === 0) {
88
+ throw new IdentityNormalizationError(`normalize: principal "${id}" from "${source}" is not tenant-bound (missing/empty tenantId — every principal MUST belong to exactly one tenant)`);
89
+ }
90
+ // kind — default to 'user'; an explicit-but-unrecognized kind REJECTS.
91
+ const kind = this.resolveKind(candidate.kind, id, source);
92
+ // roleIds — default to []; freeze a defensive copy so the Principal is immutable.
93
+ const roleIds = Object.freeze([...(candidate.roleIds ?? [])]);
94
+ // isRoot — ROOT SAFETY: default-deny. Honored ONLY from the
95
+ // mapper's TRUSTED signal (an allowlisted, first-party path). We NEVER read
96
+ // any raw claim here, so an attacker-controllable `superuser`/`isPlatformSuperuser`
97
+ // claim cannot influence this value.
98
+ const isRoot = candidate.trustedRootSignal === true;
99
+ return Object.freeze({
100
+ kind,
101
+ id,
102
+ tenantId,
103
+ roleIds,
104
+ isRoot,
105
+ });
106
+ }
107
+ /** Resolve + validate the principal kind (default `user`, reject unknown). */
108
+ resolveKind(candidateKind, id, source) {
109
+ if (candidateKind === undefined)
110
+ return DEFAULT_PRINCIPAL_KIND;
111
+ if (!VALID_PRINCIPAL_KINDS.has(candidateKind)) {
112
+ throw new IdentityNormalizationError(`normalize: principal "${id}" from "${source}" has invalid kind "${candidateKind}" (must be one of user | role_group | service_account)`);
113
+ }
114
+ return candidateKind;
115
+ }
116
+ }
117
+ /**
118
+ * Wire the mapper registry + adapters and return an object implementing the
119
+ * frozen {@link IdentityBroker}. This is the engine's public entry point.
120
+ *
121
+ * - No `mappers` given ⇒ registers ONE reference Internal adapter (canonical
122
+ * claim shape) with the given (default empty) root allowlist.
123
+ * - `mappers` given ⇒ registers exactly those (the seam future protocol adapters
124
+ * plug into). Duplicate sources fail-closed at registration.
125
+ */
126
+ function createIdentityBroker(options = {}) {
127
+ const registry = new claim_mapper_js_1.IdentityClaimMapperRegistry();
128
+ if (options.mappers === undefined) {
129
+ registry.register((0, internal_adapter_js_1.createInternalIdentityAdapter)(options.internalRootIds !== undefined
130
+ ? { rootIds: options.internalRootIds }
131
+ : {}));
132
+ }
133
+ else {
134
+ for (const mapper of options.mappers) {
135
+ registry.register(mapper);
136
+ }
137
+ }
138
+ return new BrokerImpl(registry);
139
+ }
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * The **IdP-adapter contract** for the Identity engine — the internal extension
4
+ * seam that turns a source's opaque, provider-native claims into a set of
5
+ * *candidate* principal fields the normalization core then validates + binds.
6
+ *
7
+ * This is the seam the 7 deferred protocol adapters (OIDC / SAML / LDAP-based
8
+ * external IdPs) will each implement — ONE `IdentityClaimMapper` per
9
+ * source. It is deliberately MINIMAL (ADR-0023 §7 Rule of Three): a `source`
10
+ * discriminator + a pure `map()` + a tiny registry. It grows an abstraction only
11
+ * when a third concrete need appears.
12
+ *
13
+ * SCOPE: claim → candidate fields ONLY. A mapper does NOT verify the assertion
14
+ * (authenticity is Authentication's job, step 5), does NOT enforce invariants
15
+ * (the core does — a mapper may legitimately produce an incomplete candidate, and
16
+ * the core fail-closes on it), and does NOT decide the root flag from
17
+ * attacker-controllable claims (see {@link CandidatePrincipalFields.trustedRootSignal}).
18
+ *
19
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports here.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.IdentityClaimMapperRegistry = void 0;
23
+ /**
24
+ * A tiny registry of {@link IdentityClaimMapper}s, keyed by `source`. The
25
+ * normalization core dispatches on `assertion.source` through this: a hit selects
26
+ * the mapper; a MISS is an unknown/unregistered source → the core rejects
27
+ * (fail-closed — never fabricate a principal). Fresh per broker.
28
+ */
29
+ class IdentityClaimMapperRegistry {
30
+ mappers = new Map();
31
+ /**
32
+ * Register a mapper for its `source`. Fail-closed: an empty source or a
33
+ * duplicate registration throws LOUD (a silently-shadowed mapper could route
34
+ * an assertion to the wrong IdP).
35
+ */
36
+ register(mapper) {
37
+ const { source } = mapper;
38
+ if (source.length === 0) {
39
+ throw new Error('IdentityClaimMapperRegistry.register: source must be non-empty');
40
+ }
41
+ if (this.mappers.has(source)) {
42
+ throw new Error(`IdentityClaimMapperRegistry.register: source "${source}" is already registered (duplicate mapper)`);
43
+ }
44
+ this.mappers.set(source, mapper);
45
+ }
46
+ /** Look up the mapper for a source, or `undefined` if none is registered. */
47
+ resolve(source) {
48
+ return this.mappers.get(source);
49
+ }
50
+ }
51
+ exports.IdentityClaimMapperRegistry = IdentityClaimMapperRegistry;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ /**
3
+ * Engine seam: **Identity** — resolves *who* the principal is.
4
+ *
5
+ * The Identity Broker normalizes any source IdP into ONE uniform Principal model
6
+ * regardless of origin (010_Architecture "the request's journey" §1). Users,
7
+ * roles/groups, and service accounts flow through the SAME downstream decision
8
+ * (§7 of 050 AUTHORIZATION_REQUIREMENTS).
9
+ *
10
+ * The FROZEN public types below (ADR-0023, semver-published) are the seam other
11
+ * layers build against — DO NOT change them. The engine that IMPLEMENTS this seam
12
+ * (the normalization core, the IdP-adapter contract, the reference Internal
13
+ * adapter, and the `createIdentityBroker` factory) lives in the sibling files
14
+ * re-exported at the bottom of this barrel.
15
+ * ADR-0003: framework-agnostic — nothing here may import a framework.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
29
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ // --- Engine implementation behind the frozen seam above (this layer) ---------
33
+ // The IdP-adapter contract (the extension seam future protocol adapters plug
34
+ // into) + its registry:
35
+ __exportStar(require("./claim-mapper.js"), exports);
36
+ // The reference Internal / generic-claims adapter (the "own IdP" path):
37
+ __exportStar(require("./internal-adapter.js"), exports);
38
+ // The normalization core + the `createIdentityBroker` factory + its error type:
39
+ __exportStar(require("./broker.js"), exports);
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ /**
3
+ * The reference {@link IdentityClaimMapper} — the **Internal / generic-claims
4
+ * provider** (Shield's own first-party IdP path).
5
+ *
6
+ * It expects a CANONICAL claim shape (`id`, `tenantId`, `kind`, `roleIds`, and a
7
+ * root signal) and maps it 1:1 to {@link CandidatePrincipalFields}. This is
8
+ * the "own IdP" path AND the shape the future protocol adapters target: an OIDC /
9
+ * SAML / LDAP adapter's job is to translate its provider-native claims INTO this
10
+ * canonical shape, then this same normalization guarantees apply.
11
+ *
12
+ * Uniform treatment (ADR-0007): a `service_account` assertion flows through the
13
+ * EXACT SAME `map()` as a `user` — there is no "is-this-a-machine" branch. Kind
14
+ * is carried through as data.
15
+ *
16
+ * ROOT SAFETY (security-critical). This adapter is the ONE trusted path that
17
+ * may propose the root flag, and it does so ONLY via an EXPLICIT,
18
+ * ALLOWLISTED mechanism: the Internal source is configured with the exact set of
19
+ * canonical ids that ARE roots (`rootIds`). The flag is set
20
+ * `true` iff the asserted `id` is in that allowlist — it is NEVER read from a
21
+ * caller-supplied `superuser` / `isPlatformSuperuser` claim. So even on this
22
+ * trusted source, an attacker who can influence claim VALUES cannot flip it
23
+ * (they'd have to be in the server-side allowlist, which they can't write). Every
24
+ * other (external) adapter leaves the signal `false`. Default-deny, everywhere.
25
+ *
26
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB imports.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.INTERNAL_IDENTITY_SOURCE = void 0;
30
+ exports.createInternalIdentityAdapter = createInternalIdentityAdapter;
31
+ /** The canonical `source` id for Shield's first-party Internal provider. */
32
+ exports.INTERNAL_IDENTITY_SOURCE = 'internal';
33
+ /** Read a claim as a trimmed non-empty string, or `undefined`. */
34
+ function asStr(value) {
35
+ if (typeof value !== 'string')
36
+ return undefined;
37
+ const trimmed = value.trim();
38
+ return trimmed.length === 0 ? undefined : trimmed;
39
+ }
40
+ /** Read a claim as an array of non-empty strings (roles); `[]` when absent. */
41
+ function asStrArray(value) {
42
+ if (!Array.isArray(value))
43
+ return [];
44
+ const out = [];
45
+ for (const item of value) {
46
+ const s = asStr(item);
47
+ if (s !== undefined)
48
+ out.push(s);
49
+ }
50
+ return out;
51
+ }
52
+ /**
53
+ * Build the reference Internal adapter. It maps the canonical claim shape 1:1
54
+ * and — via the trusted, allowlisted mechanism only — proposes the root
55
+ * signal. It performs NO verification (auth's job) and enforces NO invariants
56
+ * (the core does): a missing `id`/`tenantId` is returned absent so the core
57
+ * fail-closes uniformly.
58
+ */
59
+ function createInternalIdentityAdapter(config = {}) {
60
+ const source = config.source ?? exports.INTERNAL_IDENTITY_SOURCE;
61
+ // Snapshot the allowlist into a Set at construction — it is SERVER-SIDE trusted
62
+ // config, never influenced by an assertion's claims.
63
+ const rootIds = new Set(config.rootIds ?? []);
64
+ return {
65
+ source,
66
+ map(claims) {
67
+ const id = asStr(claims.id);
68
+ const tenantId = asStr(claims.tenantId);
69
+ // Kind carried as data (uniform treatment) — the core validates it against
70
+ // the allowed PrincipalKind set and rejects an unrecognized value.
71
+ const kind = asStr(claims.kind);
72
+ const roleIds = asStrArray(claims.roleIds);
73
+ // ROOT SAFETY: the flag comes SOLELY from the server-side allowlist
74
+ // keyed by the asserted (trusted) id — NEVER from claims.superuser /
75
+ // claims.isPlatformSuperuser. Those attacker-controllable claims are
76
+ // deliberately ignored here; the core also defaults the flag false.
77
+ const trustedRootSignal = id !== undefined && rootIds.has(id);
78
+ // Build with only the keys we actually have present — under
79
+ // `exactOptionalPropertyTypes` an optional field must be OMITTED (not set
80
+ // to `undefined`). A missing id/tenantId is returned absent so the core
81
+ // fail-closes uniformly.
82
+ const candidate = { roleIds, trustedRootSignal };
83
+ return {
84
+ ...candidate,
85
+ ...(id !== undefined ? { id } : {}),
86
+ ...(tenantId !== undefined ? { tenantId } : {}),
87
+ ...(kind !== undefined ? { kind } : {}),
88
+ };
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ /**
3
+ * `@astram/core` — the framework-agnostic security Core (ADR-0003).
4
+ *
5
+ * **This barrel is the FROZEN public contract (ADR-0023).** Everything exported
6
+ * here is what Layer-3 teams and downstream consumers build against; keep it
7
+ * deliberate and stable (semver). ZERO framework imports (no @nestjs/*, react,
8
+ * react-dom, vite, express) — enforced by the root ESLint ADR-0003 boundary.
9
+ *
10
+ * The public surface is:
11
+ *
12
+ * 1. **Six engine PORT interfaces** — one per layer, in the request's journey
13
+ * order. TYPES/INTERFACES ONLY; each is implemented by a later step (4-9):
14
+ * Identity (IdentityBroker) → Authentication (Authenticator) →
15
+ * Session (SessionAuthority) → Risk (RiskEngine) →
16
+ * Authorization (DecisionAuthority — the ONE decision entry) →
17
+ * Audit (AuditSink).
18
+ *
19
+ * 2. **The module-registers-metadata contract** — FieldDescriptor,
20
+ * ObjectTypeDescriptor, SupportingDependency (neverAutoGrant), ActionDescriptor
21
+ * (tier), ModuleMetadata; the `ModuleRegistry` interface (Team A implements)
22
+ * with its resolved lookups (RegisteredAction).
23
+ *
24
+ * 3. **Pure derivation RULES** (the only logic in this contract layer — no engine
25
+ * bodies): `derivePermissionKey` (the stable `feature:object:action` identity,
26
+ * ADR-0010) + the `PermissionKey` brand; `resolveTier` (ADR-0004 `gated`
27
+ * default) + `DEFAULT_ACCESS_TIER`; `resolveActionPermissionKey`.
28
+ *
29
+ * 4. **The boot-completeness-check contract** (ADR-0002/0010) — OperationInventory
30
+ * (caller-fed), CompletenessResult, and the `checkCompleteness` SIGNATURE
31
+ * (Team C implements the body).
32
+ *
33
+ * No engine logic lives here — decide()/normalize()/authenticate()/assess()/
34
+ * establish()/record() and checkCompleteness() are all seams/signatures only.
35
+ */
36
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
37
+ if (k2 === undefined) k2 = k;
38
+ var desc = Object.getOwnPropertyDescriptor(m, k);
39
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
40
+ desc = { enumerable: true, get: function() { return m[k]; } };
41
+ }
42
+ Object.defineProperty(o, k2, desc);
43
+ }) : (function(o, m, k, k2) {
44
+ if (k2 === undefined) k2 = k;
45
+ o[k2] = m[k];
46
+ }));
47
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
48
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
49
+ };
50
+ Object.defineProperty(exports, "__esModule", { value: true });
51
+ // Engine seams (one per layer) — PORTs, implemented by steps 4-9.
52
+ __exportStar(require("./identity/index.js"), exports);
53
+ __exportStar(require("./authentication/index.js"), exports);
54
+ __exportStar(require("./session/index.js"), exports);
55
+ __exportStar(require("./risk/index.js"), exports);
56
+ __exportStar(require("./authorization/index.js"), exports);
57
+ __exportStar(require("./audit/index.js"), exports);
58
+ // Module-registers-metadata contract + pure derivation rules + completeness check.
59
+ __exportStar(require("./metadata/index.js"), exports);
60
+ // Admin Console (Layer 10) — a NEW top-level module (append-only; no frozen
61
+ // prior-layer seam changed): admin ports + query/command types + §11.3 safeguard
62
+ // signatures + the query/command service factories + command-pipeline order.
63
+ __exportStar(require("./admin/index.js"), exports);
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ /**
3
+ * The **boot-completeness-check contract** (ADR-0002 fail-closed enforcement,
4
+ * ADR-0010 auto-discovered operations).
5
+ *
6
+ * At build/boot, every non-public operation the application exposes MUST resolve
7
+ * to a permission in the registry; any that doesn't is a HARD FAILURE and denied
8
+ * until wired (ADR-0002/0010). This module defines the TYPES + the pure function
9
+ * SIGNATURE that performs that reconciliation. It is **framework-agnostic**
10
+ * (ADR-0003): the operation inventory is **CALLER-FED** (confirmed decision #2) —
11
+ * `@astram/core` does NOT reflect NestJS routes; `@astram/guard` discovers the
12
+ * live operations and hands them in as an {@link OperationInventory}.
13
+ *
14
+ * The TYPES are the frozen contract; {@link checkCompleteness} is the PURE
15
+ * reconciliation implemented over them (Team C). No I/O, no framework imports —
16
+ * the inventory is handed in.
17
+ */
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.checkCompleteness = checkCompleteness;
20
+ /**
21
+ * Reconcile the caller-fed live operation inventory against the registry's
22
+ * declared permissions (ADR-0002/0010). PURE (no I/O) — the inventory is passed
23
+ * in; core never reflects routes itself (ADR-0003, confirmed decision #2).
24
+ *
25
+ * Reports: (a) non-public operations with no resolved permission/classification,
26
+ * (b) orphaned permissions (registered but no live op), (c) stranded ops (op with
27
+ * no association). `passed` gates boot per ADR-0002.
28
+ *
29
+ * Reconciliation rules (per the frozen contract, DONE §5):
30
+ *
31
+ * - **Public op** (`isPublic: true`) — exempt from the resolve requirement
32
+ * (ADR-0004). Skipped entirely; contributes to no failure list. A public op's
33
+ * `permissionKey`, if present, still counts as "claimed" so it does NOT strand a
34
+ * matching registered action as orphaned.
35
+ * - **Non-public op with NO `permissionKey`** — a STRANDED operation (declared no
36
+ * association at all). It is ALSO reported as unclassified (it resolves to no
37
+ * classification), with `declaredPermissionKey` absent to signal "declared none".
38
+ * - **Non-public op with a `permissionKey` that `resolveByPermissionKey` misses**
39
+ * — an UNCLASSIFIED operation (its key is registered nowhere), with the declared
40
+ * key echoed for triage. It is NOT stranded (it did declare an association).
41
+ * - **Orphaned permission** — a `registry.listActions()` entry whose `permissionKey`
42
+ * is claimed by NO live operation in the inventory (public or non-public).
43
+ * Reported for review (ADR-0010): a lingering grant opens no hole, so — per the
44
+ * {@link CompletenessResult} contract — orphaned permissions do NOT by themselves
45
+ * fail the boot.
46
+ *
47
+ * **Fail-closed semantics (ADR-0002):**
48
+ * `passed === (unclassifiedOperations.length === 0 && strandedOperations.length === 0)`.
49
+ * Any non-public op that resolves to nothing ⇒ `passed: false` ⇒ the caller
50
+ * (`@astram/guard`) hard-fails boot and denies until wired. Orphaned permissions
51
+ * are excluded from this gate (soft warning only).
52
+ *
53
+ * **Deterministic:** every returned list is sorted by a stable key (operationId /
54
+ * permissionKey) so identical inputs always yield byte-identical output.
55
+ */
56
+ function checkCompleteness(inventory, registry) {
57
+ const unclassifiedOperations = [];
58
+ const strandedOperations = [];
59
+ // The set of permission keys that some live operation claims to bind to —
60
+ // used to detect orphaned permissions (registered but claimed by no live op).
61
+ // A public op that declares a key still "claims" it, so it is included here.
62
+ const claimedPermissionKeys = new Set();
63
+ for (const op of inventory.operations) {
64
+ if (op.permissionKey !== undefined) {
65
+ claimedPermissionKeys.add(op.permissionKey);
66
+ }
67
+ // Public operations are an explicit, code-reviewed opt-out (ADR-0004) and are
68
+ // exempt from the "must resolve to a permission" rule.
69
+ if (op.isPublic) {
70
+ continue;
71
+ }
72
+ if (op.permissionKey === undefined) {
73
+ // Declared no association at all ⇒ stranded AND unclassified.
74
+ strandedOperations.push({ operationId: op.operationId });
75
+ unclassifiedOperations.push({ operationId: op.operationId });
76
+ continue;
77
+ }
78
+ // Declared a key — it must resolve to a registered action, else unclassified.
79
+ if (registry.resolveByPermissionKey(op.permissionKey) === undefined) {
80
+ unclassifiedOperations.push({
81
+ operationId: op.operationId,
82
+ declaredPermissionKey: op.permissionKey,
83
+ });
84
+ }
85
+ }
86
+ // Orphaned permissions: every registered action whose permission key no live
87
+ // operation claims. Reported for review (ADR-0010) — NOT a boot failure.
88
+ const orphanedPermissions = [];
89
+ for (const registered of registry.listActions()) {
90
+ if (!claimedPermissionKeys.has(registered.permissionKey)) {
91
+ orphanedPermissions.push({
92
+ permissionKey: registered.permissionKey,
93
+ moduleKey: registered.moduleKey,
94
+ });
95
+ }
96
+ }
97
+ // Deterministic ordering — stable, total sort keys.
98
+ unclassifiedOperations.sort((a, b) => (a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0));
99
+ strandedOperations.sort((a, b) => (a.operationId < b.operationId ? -1 : a.operationId > b.operationId ? 1 : 0));
100
+ orphanedPermissions.sort((a, b) => a.permissionKey < b.permissionKey ? -1 : a.permissionKey > b.permissionKey ? 1 : 0);
101
+ const passed = unclassifiedOperations.length === 0 && strandedOperations.length === 0;
102
+ return {
103
+ passed,
104
+ unclassifiedOperations,
105
+ orphanedPermissions,
106
+ strandedOperations,
107
+ };
108
+ }