@astram/core 0.1.0 → 1.0.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 +23 -4
  41. package/dist/authorization/index.d.ts.map +1 -1
  42. package/dist/authorization/index.js +29 -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 +124 -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,88 @@
1
+ "use strict";
2
+ /**
3
+ * Admin QUERY engine — the **audit viewer read-model** (Team A, AC 6, §13).
4
+ *
5
+ * Reads a page of audit events over {@link import('../ports.js').AuditReader}
6
+ * (newest-first, tenant-scoped, paginated) and maps each {@link AuditEvent} to an
7
+ * {@link AuditViewEvent} whose actor is resolved to a human LABEL.
8
+ *
9
+ * ⛔ NO RAW IDENTIFIERS (ADR-0012 / §13.4) — the crossing-to-UI invariant. The
10
+ * viewer renders `actorLabel`, NEVER `event.actorId`. `actorLabel` is resolved via
11
+ * the {@link import('../ports.js').LabelResolver} chokepoint; a DELETED actor
12
+ * resolves to the resolver's fallback ("Deleted user"/"(unknown)"), never the raw
13
+ * id. (The frozen {@link AuditViewEvent} embeds the raw `event` for completeness;
14
+ * the SDK projection — Team C — MUST send only `actorLabel` + non-id event fields
15
+ * to the browser, NOT `event.actorId`. Documented in the team DONE.md.)
16
+ *
17
+ * ⛔ DATA-ABSENCE vs TRANSIENT: `read` → `[]` means "nothing matched" (a NORMAL
18
+ * empty page → `nextCursor: null`). A reader that THROWS (unavailable) propagates
19
+ * — a fail-closed read (ADR-0016).
20
+ *
21
+ * ⛔ PAGINATION: the reader returns a STABLE newest-first order. `nextCursor` is
22
+ * the ordering key of the LAST event on a FULL page (there may be more); `null`
23
+ * when the page is short (last page) or no limit was set. The cursor is opaque
24
+ * ordering data (a timestamp key), not a user-facing id.
25
+ *
26
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.toViewEvent = toViewEvent;
30
+ exports.deriveNextCursor = deriveNextCursor;
31
+ exports.auditView = auditView;
32
+ /**
33
+ * Map one {@link AuditEvent} to an {@link AuditViewEvent} — resolving the actor to
34
+ * a human label via the chokepoint (deleted → fallback, never the id). The
35
+ * resolver may THROW (unavailable) → propagate, fail-closed.
36
+ */
37
+ async function toViewEvent(event, labels) {
38
+ const actorLabel = await labels.resolve('principal', event.actorId, event.tenantId);
39
+ return {
40
+ event,
41
+ actorLabel: actorLabel.length > 0 ? actorLabel : '(unknown actor)',
42
+ };
43
+ }
44
+ /**
45
+ * Derive the opaque next-page cursor. Newest-first events paginate by the LAST
46
+ * (oldest-on-page) event's ordering key. Returns `null` when the page is not full
47
+ * (no more data) or no `limit` was requested (single unbounded read). PURE.
48
+ */
49
+ function deriveNextCursor(events, limit) {
50
+ if (limit === undefined || events.length < limit || events.length === 0) {
51
+ return null;
52
+ }
53
+ const last = events[events.length - 1];
54
+ if (last === undefined) {
55
+ return null;
56
+ }
57
+ // The stable ordering key is the (UTC) occurrence time; opaque to the caller.
58
+ return String(last.occurredAtMs);
59
+ }
60
+ /**
61
+ * The audit viewer read-model (§13 / AC 6): read a page of events for the query's
62
+ * tenant, resolve every actor to a label, echo the query (cursor continuity), and
63
+ * compute the next-page cursor.
64
+ *
65
+ * ⛔ Reads ONLY the fields the port's {@link AuditReadQuery} defines; the returned
66
+ * events carry a resolved `actorLabel` so no raw actor id crosses to the UI.
67
+ */
68
+ async function auditView(deps, query) {
69
+ const { auditReader, labels } = deps;
70
+ const readQuery = {
71
+ tenantId: query.tenantId,
72
+ ...(query.type !== undefined ? { type: query.type } : {}),
73
+ ...(query.actorId !== undefined ? { actorId: query.actorId } : {}),
74
+ ...(query.limit !== undefined ? { limit: query.limit } : {}),
75
+ ...(query.before !== undefined ? { before: query.before } : {}),
76
+ };
77
+ // [] = nothing matched (NORMAL empty page); a throw = unavailable → propagates.
78
+ const events = await auditReader.read(readQuery);
79
+ const viewEvents = [];
80
+ for (const event of events) {
81
+ viewEvents.push(await toViewEvent(event, labels));
82
+ }
83
+ return {
84
+ query,
85
+ events: viewEvents,
86
+ nextCursor: deriveNextCursor(events, query.limit),
87
+ };
88
+ }
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ /**
3
+ * Admin QUERY engine — the **catalog read-model** (Team A, AC 1 / AC 6, §2 / §5.4).
4
+ *
5
+ * The human-readable permission catalog: the registry (`listActions()`) is the
6
+ * BASE; the {@link import('../ports.js').CatalogStore} curation overlay layers
7
+ * custom labels/groups on top; every entry is classified for the completeness
8
+ * view (§5.4):
9
+ * - `classified` — a live registry action (optionally curated).
10
+ * - `unclassified` — a live registry action the admin has NOT yet curated
11
+ * (newly-discovered → "needs attention," never silently open, AC 1).
12
+ * - `orphaned` — a curation that references a permission key NO live action
13
+ * derives (the operation was removed — drift to clean up, §5.4).
14
+ *
15
+ * ⛔ NO RAW IDENTIFIERS (ADR-0012). A display label is, in order of preference:
16
+ * 1. the curation's custom label (admin-authored human text), else
17
+ * 2. the {@link import('../ports.js').LabelResolver} label for the permission, else
18
+ * 3. a humanized form derived from the registry business keys.
19
+ * A raw route/path/uuid is NEVER emitted as display text. `permissionKey` is the
20
+ * stable identity carried for command inputs/correlation, not for display.
21
+ *
22
+ * ⛔ DATA-ABSENCE vs TRANSIENT: `catalogStore.getCuration` / `listGroups` return
23
+ * `null`/`[]` for a NORMAL miss (→ registry-derived label / no groups). A store
24
+ * that THROWS (genuinely unavailable) propagates — a fail-closed read (ADR-0016);
25
+ * we never swallow "down" into "no curation".
26
+ *
27
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.humanizeKey = humanizeKey;
31
+ exports.getCatalog = getCatalog;
32
+ exports.buildEntry = buildEntry;
33
+ exports.classifyKnownKeys = classifyKnownKeys;
34
+ /**
35
+ * Humanize a stable business key (e.g. `create`, `work_order`, `assign_reviewer`)
36
+ * into human-readable display text (`Create`, `Work Order`, `Assign Reviewer`).
37
+ * PURE. Splits on `_`/`-`/`:` and camelCase boundaries, then Title-Cases. Used
38
+ * ONLY as the last-resort label when neither a curation nor a resolver label is
39
+ * available — it is human text derived from the key, NEVER a raw route/uuid.
40
+ */
41
+ function humanizeKey(key) {
42
+ const words = key
43
+ // split camelCase / PascalCase boundaries
44
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
45
+ // treat separators as spaces
46
+ .split(/[\s_:-]+/u)
47
+ .filter((w) => w.length > 0);
48
+ if (words.length === 0) {
49
+ return key;
50
+ }
51
+ return words
52
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
53
+ .join(' ');
54
+ }
55
+ /**
56
+ * Resolve a permission's human display label. Preference order (no raw ids):
57
+ * curation label → {@link LabelResolver} → humanized registry action key. The
58
+ * resolver may THROW when the directory is unavailable — that propagates
59
+ * (fail-closed). A resolver that returns a value (including its own deleted/
60
+ * unknown FALLBACK) is used as-is; the resolver never returns a raw id.
61
+ */
62
+ async function resolvePermissionLabel(permissionKey, action, curation, labels, tenantId) {
63
+ if (curation?.label !== undefined && curation.label.length > 0) {
64
+ return curation.label;
65
+ }
66
+ // Ask the label chokepoint (ADR-0012). It ALWAYS returns a human label
67
+ // (a fallback for deleted/unknown), never the raw id; it THROWS only when the
68
+ // directory is genuinely unavailable (→ propagate, fail-closed).
69
+ const resolved = await labels.resolve('permission', permissionKey, tenantId);
70
+ if (resolved.length > 0 && resolved !== permissionKey) {
71
+ return resolved;
72
+ }
73
+ // Last resort: humanize the registry business keys (never the raw permissionKey
74
+ // string). An orphaned curation (no live action) has no keys to humanize → we
75
+ // fall back to the curation's own group text or a neutral placeholder.
76
+ if (action !== undefined) {
77
+ return `${humanizeKey(action.action.actionKey)} ${humanizeKey(action.action.typeKey)}`;
78
+ }
79
+ return '(unknown permission)';
80
+ }
81
+ /**
82
+ * Build the single {@link ActionEntry} for a registered action — its stable key
83
+ * (for command inputs), a humanized label, and its resolved tier. Since a
84
+ * permission key derives from `module:type:action`, each permission spans exactly
85
+ * one action; the entry's label is the humanized action verb.
86
+ */
87
+ function toActionEntry(action) {
88
+ return {
89
+ actionKey: action.action.actionKey,
90
+ label: humanizeKey(action.action.actionKey),
91
+ tier: action.tier,
92
+ };
93
+ }
94
+ /**
95
+ * The FULL catalog (AC 1 / §2): every live registry permission (classified or
96
+ * unclassified) PLUS any orphaned curations (drift), each label-resolved and
97
+ * classified. Ordered deterministically by permission key so the viewer paginates
98
+ * stably.
99
+ *
100
+ * ⛔ Reuses the registry as the base + the curation overlay; resolves every
101
+ * user-facing label via {@link LabelResolver}; emits NO raw route/uuid.
102
+ */
103
+ async function getCatalog(deps, tenantId) {
104
+ const { registry, catalogStore, labels } = deps;
105
+ const actions = registry.listActions();
106
+ const entries = [];
107
+ // Live registry permissions — classified when curated, else unclassified
108
+ // ("needs attention," never silently open). ORPHAN drift (a curation/grant for
109
+ // a permission key the registry no longer derives) is reported via
110
+ // {@link classifyKnownKeys} — the read-side ports (CatalogStore/GrantStore)
111
+ // expose no "enumerate every curation" API, so an orphan is classified when a
112
+ // caller presents a specific dead key (e.g. from a grant enumeration). The full
113
+ // catalog here is the live registry surface + its curation overlay.
114
+ for (const action of actions) {
115
+ const curation = await catalogStore.getCuration(action.permissionKey);
116
+ entries.push(await buildEntry(action.permissionKey, action, curation, labels, tenantId));
117
+ }
118
+ // Deterministic ordering by the stable permission key.
119
+ entries.sort((x, y) => (x.permissionKey < y.permissionKey ? -1 : x.permissionKey > y.permissionKey ? 1 : 0));
120
+ return entries;
121
+ }
122
+ /**
123
+ * Build one {@link CatalogEntry} for a permission key. `action` is the live
124
+ * registry action (or `undefined` for an orphaned key). Classification:
125
+ * - live action + curation present → `classified`
126
+ * - live action + NO curation → `unclassified` (needs attention)
127
+ * - NO live action (curation only) → `orphaned` (drift)
128
+ */
129
+ async function buildEntry(permissionKey, action, curation, labels, tenantId) {
130
+ const classification = action === undefined
131
+ ? 'orphaned'
132
+ : curation !== null
133
+ ? 'classified'
134
+ : 'unclassified';
135
+ const label = await resolvePermissionLabel(permissionKey, action, curation, labels, tenantId);
136
+ const tier = action?.tier ?? 'gated';
137
+ const actionEntries = action !== undefined ? [toActionEntry(action)] : [];
138
+ const group = curation?.group;
139
+ const base = {
140
+ permissionKey,
141
+ label,
142
+ tier,
143
+ actions: actionEntries,
144
+ classification,
145
+ };
146
+ return group !== undefined && group.length > 0
147
+ ? { ...base, group }
148
+ : base;
149
+ }
150
+ /**
151
+ * Classify an explicit set of permission keys (e.g. the keys a set of grants
152
+ * references) against the live registry + curation overlay — the ORPHAN-detection
153
+ * path (§5.4). A key with NO live action is `orphaned` (drift); a live key with a
154
+ * curation is `classified`; a live uncurated key is `unclassified`. Returns one
155
+ * label-resolved {@link CatalogEntry} per key, deterministically ordered. Used by
156
+ * {@link import('./index.js')}'s `listUnclassified` to surface grant-referenced
157
+ * orphans the registry-only pass can't see.
158
+ */
159
+ async function classifyKnownKeys(deps, keys, tenantId) {
160
+ const { registry, catalogStore, labels } = deps;
161
+ const seen = new Set();
162
+ const entries = [];
163
+ for (const key of keys) {
164
+ if (seen.has(key)) {
165
+ continue;
166
+ }
167
+ seen.add(key);
168
+ const action = registry.resolveByPermissionKey(key);
169
+ const curation = await catalogStore.getCuration(key);
170
+ entries.push(await buildEntry(key, action, curation, labels, tenantId));
171
+ }
172
+ entries.sort((x, y) => (x.permissionKey < y.permissionKey ? -1 : x.permissionKey > y.permissionKey ? 1 : 0));
173
+ return entries;
174
+ }
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ /**
3
+ * Admin QUERY engine — **effective-access explain** (Team A, AC 3 / AC 6, §2).
4
+ *
5
+ * "What can principal P do, and why." Enumerates P's effective grants (via
6
+ * {@link import('../ports.js').GrantStore.listGrants}) into human-readable
7
+ * {@link EffectiveGrant}s: a resolved permission label + the granted action subset
8
+ * + a PROSE conditions summary (never a raw expression). The principal is resolved
9
+ * to a label (never their raw id).
10
+ *
11
+ * ⛔ TRUTHFULNESS (AC 3 / ADR-0001): the explanation enumerates the grant FACTS —
12
+ * it does not fabricate a verdict. `decide()` remains the ONE decision path
13
+ * (simulate delegates to it); explain and simulate must never diverge. Explain
14
+ * reports what is granted; it does not re-derive access.
15
+ *
16
+ * ⛔ NO RAW IDENTIFIERS (ADR-0012): `principalLabel` + every grant `label` pass
17
+ * through {@link import('../ports.js').LabelResolver}; a deleted entity resolves to
18
+ * the resolver's fallback ("Deleted user"/"(unknown)"), NEVER the raw id. The
19
+ * conditions summary is guided-structure prose — no ids, no raw expression.
20
+ *
21
+ * ⛔ NO-LEAK (§7.5 / §13): explain reports the principal's OWN grants; it does not
22
+ * enumerate resources P cannot see. A grant names a permission + an action subset,
23
+ * not the existence of specific records.
24
+ *
25
+ * ⛔ DATA-ABSENCE vs TRANSIENT: `listGrants` → `[]` means "no grants" (a NORMAL
26
+ * empty explanation). A store that THROWS (unavailable) propagates — fail-closed.
27
+ *
28
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.summarizeCondition = summarizeCondition;
32
+ exports.summarizeConditions = summarizeConditions;
33
+ exports.explain = explain;
34
+ /**
35
+ * Human phrasings for each guided operator (prose, never a raw expression). A
36
+ * TOTAL record over the closed {@link PolicyOperator} union — adding a new
37
+ * operator to the union is a compile error here until it gets a phrasing.
38
+ */
39
+ const OPERATOR_PHRASE = {
40
+ eq: 'equals',
41
+ ne: 'is not',
42
+ in: 'is one of',
43
+ not_in: 'is not one of',
44
+ gt: 'is greater than',
45
+ lt: 'is less than',
46
+ gte: 'is at least',
47
+ lte: 'is at most',
48
+ contains: 'contains',
49
+ not_contains: 'does not contain',
50
+ is_null: 'is empty',
51
+ is_not_null: 'is set',
52
+ is_owner: 'they own',
53
+ is_not_owner: 'they do not own',
54
+ };
55
+ /** Operators that take NO operand — their prose omits the value. */
56
+ const OPERAND_LESS = new Set([
57
+ 'is_null',
58
+ 'is_not_null',
59
+ 'is_owner',
60
+ 'is_not_owner',
61
+ ]);
62
+ /**
63
+ * Summarize a single guided condition into human prose. PURE. Never emits a raw
64
+ * expression or an id — it names the field + a phrasing + (for operand operators)
65
+ * a rendered value. `is_owner` → "records they own"; `status in [...]` →
66
+ * "status is one of open, closed".
67
+ */
68
+ function summarizeCondition(condition) {
69
+ const { field, operator, value } = condition;
70
+ const phrase = OPERATOR_PHRASE[operator] ?? String(operator);
71
+ if (operator === 'is_owner') {
72
+ return `records ${field} they own`;
73
+ }
74
+ if (operator === 'is_not_owner') {
75
+ return `records ${field} they do not own`;
76
+ }
77
+ if (OPERAND_LESS.has(operator)) {
78
+ return `${field} ${phrase}`;
79
+ }
80
+ return `${field} ${phrase} ${renderValue(value)}`;
81
+ }
82
+ /** Render a condition value as prose (arrays comma-joined; no ids leaked). */
83
+ function renderValue(value) {
84
+ if (Array.isArray(value)) {
85
+ return value.map((v) => String(v)).join(', ');
86
+ }
87
+ if (value === null || value === undefined) {
88
+ return '(none)';
89
+ }
90
+ return String(value);
91
+ }
92
+ /**
93
+ * Compose the prose conditions summary for a grant's conditions. Returns
94
+ * `undefined` when the grant is unconditional (so the type's optional field is
95
+ * omitted). Multiple conditions are AND-composed ("only where …, and …").
96
+ */
97
+ function summarizeConditions(conditions) {
98
+ if (conditions === undefined || conditions.length === 0) {
99
+ return undefined;
100
+ }
101
+ const parts = conditions.map(summarizeCondition);
102
+ return `Only where ${parts.join(', and ')}`;
103
+ }
104
+ /**
105
+ * Resolve one {@link Grant} into a human-readable {@link EffectiveGrant}: the
106
+ * permission label (via the label chokepoint), the granted action subset, and the
107
+ * prose conditions summary. The resolver may THROW (unavailable) → propagate.
108
+ */
109
+ async function toEffectiveGrant(grant, labels, tenantId) {
110
+ const label = await resolvePermissionLabel(grant.permissionKey, labels, tenantId);
111
+ const summary = summarizeConditions(grant.conditions);
112
+ const base = {
113
+ label,
114
+ actions: [...grant.actions],
115
+ };
116
+ return summary !== undefined ? { ...base, conditionsSummary: summary } : base;
117
+ }
118
+ /**
119
+ * Resolve a permission key to its human label via the chokepoint. Always returns
120
+ * a label (the resolver's fallback for deleted/unknown), NEVER the raw key; throws
121
+ * only on a transient directory failure (→ propagate, fail-closed).
122
+ */
123
+ async function resolvePermissionLabel(permissionKey, labels, tenantId) {
124
+ const resolved = await labels.resolve('permission', permissionKey, tenantId);
125
+ return resolved.length > 0 ? resolved : '(unknown permission)';
126
+ }
127
+ /**
128
+ * Effective-access explain for a principal (AC 3): enumerate P's grants in
129
+ * `tenantId` into human terms + the "why," with the principal resolved to a label.
130
+ *
131
+ * ⛔ Truthful by construction — reports the grant facts; the verdict path is
132
+ * `decide()` (simulate), never re-derived here.
133
+ */
134
+ async function explain(deps, principalId, tenantId) {
135
+ const { grantStore, labels } = deps;
136
+ // Resolve the principal to a human label (deleted → resolver fallback, never id).
137
+ const principalLabel = await labels.resolve('principal', principalId, tenantId);
138
+ // Enumerate the principal's grants ([] = no effective grants, a NORMAL result;
139
+ // a throw = unavailable → propagates fail-closed).
140
+ const grants = await grantStore.listGrants(principalId, tenantId);
141
+ const resolved = [];
142
+ for (const grant of grants) {
143
+ resolved.push(await toEffectiveGrant(grant, labels, tenantId));
144
+ }
145
+ return {
146
+ principalLabel: principalLabel.length > 0 ? principalLabel : '(unknown principal)',
147
+ grants: resolved,
148
+ };
149
+ }
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ /**
3
+ * Admin QUERY engine — barrel (Team A, Layer 10).
4
+ *
5
+ * Re-exports the standalone query functions that back the frozen
6
+ * {@link import('../admin-service.js').AdminQueryService} interface. Each is a pure
7
+ * function of `(deps, …args)` — the integration owner composes them into
8
+ * `createAdminQueryService(deps)` (the prelude froze that factory; this team owns
9
+ * the bodies as standalone functions per the prelude instruction). Every function
10
+ * is read-only, label-resolved (no raw ids, ADR-0012), and — for `simulate` —
11
+ * routes through the ONE `decide()` (ADR-0001).
12
+ *
13
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.deriveNextCursor = exports.toViewEvent = exports.auditView = exports.wrapDecision = exports.simulate = exports.summarizeConditions = exports.summarizeCondition = exports.explain = exports.humanizeKey = exports.classifyKnownKeys = exports.buildEntry = exports.getCatalog = void 0;
17
+ exports.listUnclassified = listUnclassified;
18
+ exports.composeAdminQueryService = composeAdminQueryService;
19
+ const catalog_js_1 = require("./catalog.js");
20
+ const explain_js_1 = require("./explain.js");
21
+ const simulate_js_1 = require("./simulate.js");
22
+ const audit_view_js_1 = require("./audit-view.js");
23
+ var catalog_js_2 = require("./catalog.js");
24
+ Object.defineProperty(exports, "getCatalog", { enumerable: true, get: function () { return catalog_js_2.getCatalog; } });
25
+ Object.defineProperty(exports, "buildEntry", { enumerable: true, get: function () { return catalog_js_2.buildEntry; } });
26
+ Object.defineProperty(exports, "classifyKnownKeys", { enumerable: true, get: function () { return catalog_js_2.classifyKnownKeys; } });
27
+ Object.defineProperty(exports, "humanizeKey", { enumerable: true, get: function () { return catalog_js_2.humanizeKey; } });
28
+ var explain_js_2 = require("./explain.js");
29
+ Object.defineProperty(exports, "explain", { enumerable: true, get: function () { return explain_js_2.explain; } });
30
+ Object.defineProperty(exports, "summarizeCondition", { enumerable: true, get: function () { return explain_js_2.summarizeCondition; } });
31
+ Object.defineProperty(exports, "summarizeConditions", { enumerable: true, get: function () { return explain_js_2.summarizeConditions; } });
32
+ var simulate_js_2 = require("./simulate.js");
33
+ Object.defineProperty(exports, "simulate", { enumerable: true, get: function () { return simulate_js_2.simulate; } });
34
+ Object.defineProperty(exports, "wrapDecision", { enumerable: true, get: function () { return simulate_js_2.wrapDecision; } });
35
+ var audit_view_js_2 = require("./audit-view.js");
36
+ Object.defineProperty(exports, "auditView", { enumerable: true, get: function () { return audit_view_js_2.auditView; } });
37
+ Object.defineProperty(exports, "toViewEvent", { enumerable: true, get: function () { return audit_view_js_2.toViewEvent; } });
38
+ Object.defineProperty(exports, "deriveNextCursor", { enumerable: true, get: function () { return audit_view_js_2.deriveNextCursor; } });
39
+ /**
40
+ * The catalog's "needs attention" subset (AC 1 / §5.4): the UNCLASSIFIED (live
41
+ * registry actions the admin has not curated) and ORPHANED (curation/grant drift)
42
+ * entries. A newly-discovered permission surfaces HERE, never silently open.
43
+ *
44
+ * ⛔ Ports scope: the read-side ports enumerate the registry (base) + per-key
45
+ * curation, so this reliably surfaces every UNCLASSIFIED live permission. ORPHAN
46
+ * drift (a curation/grant for a permission key the registry no longer derives)
47
+ * requires an enumeration API the frozen `CatalogStore`/`GrantStore` ports do NOT
48
+ * expose (no "list every curation" / tenant-wide grant sweep); such keys are
49
+ * classified on demand via `classifyKnownKeys(deps, keys, tenantId)` when a caller
50
+ * (e.g. the command side, over the keys it holds) presents them. This function
51
+ * returns the registry-derived unclassified subset — the portion the read ports
52
+ * can compute completely.
53
+ */
54
+ async function listUnclassified(deps, tenantId) {
55
+ const catalog = await (0, catalog_js_1.getCatalog)(deps, tenantId);
56
+ return catalog.filter((e) => e.classification === 'unclassified' || e.classification === 'orphaned');
57
+ }
58
+ /**
59
+ * Assemble a concrete {@link AdminQueryService} from the standalone query
60
+ * functions. The prelude's `createAdminQueryService` returns a fail-closed
61
+ * skeleton it OWNS (frozen — Team A does not edit `admin-service.ts`); the
62
+ * integration owner wires THIS composition into that factory (or inlines these
63
+ * functions). Provided here so the wiring is a one-liner and the query bodies have
64
+ * a single composition point.
65
+ */
66
+ function composeAdminQueryService(deps) {
67
+ return {
68
+ getCatalog: (tenantId) => (0, catalog_js_1.getCatalog)(deps, tenantId),
69
+ listUnclassified: (tenantId) => listUnclassified(deps, tenantId),
70
+ explain: (principalId, tenantId) => (0, explain_js_1.explain)(deps, principalId, tenantId),
71
+ simulate: (request) => (0, simulate_js_1.simulate)(deps, request),
72
+ auditView: (query) => (0, audit_view_js_1.auditView)(deps, query),
73
+ };
74
+ }
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ /**
3
+ * Admin QUERY engine — **simulate** (Team A, AC 2 — the one-decision-path AC).
4
+ *
5
+ * "Would principal P be allowed action A on resource R — and if not, which gate?"
6
+ *
7
+ * ⛔ THE ONE DECISION PATH (ADR-0001 / AC 2). `simulate` calls the injected
8
+ * {@link import('../../authorization/index.js').DecisionAuthority.decide} — the
9
+ * SINGLE real authority — and WRAPS the returned {@link Decision} into a
10
+ * {@link SimulateResult}. It NEVER re-implements, second-guesses, or overrides the
11
+ * verdict. The `effect`/`reason` mirror the decision verbatim; `decidingGate` +
12
+ * `explanation` are a human RENDERING of `decision.reason` for troubleshooting.
13
+ *
14
+ * ⛔ TRANSIENT: `decide()` THROWS `AuthorizationUnavailableError` when a downstream
15
+ * port is genuinely unavailable (ADR-0016). We DO NOT catch it — it propagates so
16
+ * the caller/SDK fails closed + retryable. Only a returned `Decision` is wrapped.
17
+ *
18
+ * ⛔ NO-LEAK (§7.5): the explanation is built from the frozen reason CODE, never
19
+ * from `decision.detail` (admin-only, may name a resource) and never from any raw
20
+ * id. It reveals only which gate settled the verdict, not resource existence.
21
+ *
22
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
23
+ */
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.wrapDecision = wrapDecision;
26
+ exports.simulate = simulate;
27
+ /**
28
+ * Human rendering of each frozen {@link DecisionReasonCode}: the gate that settled
29
+ * the verdict + a non-leaking prose explanation. A TOTAL record over the closed
30
+ * reason union — a new reason code is a compile error here until it is mapped, so
31
+ * the admin explanation can never silently fall back to a raw code.
32
+ */
33
+ const REASON_RENDERING = {
34
+ allowed: {
35
+ gate: 'Allowed',
36
+ explanation: 'Allowed: the principal satisfies every gate for this action.',
37
+ },
38
+ not_authenticated: {
39
+ gate: 'Authentication gate',
40
+ explanation: 'Denied at the authentication gate: this action requires an authenticated request.',
41
+ },
42
+ tenant_mismatch: {
43
+ gate: 'Tenant gate',
44
+ explanation: 'Denied at the tenant gate: the resource belongs to a different tenant and no cross-tenant grant applies.',
45
+ },
46
+ missing_object_type_grant: {
47
+ gate: 'Feature / object-type gate',
48
+ explanation: 'Denied at the object-type gate: the principal holds no grant covering this action on this object type.',
49
+ },
50
+ no_record_permit: {
51
+ gate: 'Record permit tier',
52
+ explanation: 'Denied at the record gate: no policy, share, or grant permits the principal on this specific record.',
53
+ },
54
+ explicit_deny_policy: {
55
+ gate: 'Record permit tier (explicit deny)',
56
+ explanation: 'Denied at the record gate: an explicit deny policy matches this record and overrides any allow.',
57
+ },
58
+ resource_not_registered: {
59
+ gate: 'Resource registration',
60
+ explanation: 'Denied: the resource type is not registered with the module registry, so it is deny-by-default.',
61
+ },
62
+ root_data_plane_denied: {
63
+ gate: 'Feature / object-type gate (root cap)',
64
+ explanation: 'Denied by the root cap: the root is control-plane only and cannot act on a data-plane object type, regardless of grants.',
65
+ },
66
+ deny_by_default: {
67
+ gate: 'Deny-by-default terminal',
68
+ explanation: 'Denied by default: no gate affirmatively allowed this action (the fail-closed terminal).',
69
+ },
70
+ };
71
+ /**
72
+ * Wrap a verbatim {@link Decision} from `decide()` into a {@link SimulateResult}
73
+ * — mirroring effect/reason and adding the human deciding-gate + explanation
74
+ * derived from the reason code (no raw ids, no leak). PURE. Exported so the tester
75
+ * can assert the wrapping in isolation from the (spied) decision call.
76
+ */
77
+ function wrapDecision(decision) {
78
+ const rendering = REASON_RENDERING[decision.reason];
79
+ return {
80
+ decision,
81
+ effect: decision.effect,
82
+ reason: decision.reason,
83
+ decidingGate: rendering.gate,
84
+ explanation: rendering.explanation,
85
+ };
86
+ }
87
+ /**
88
+ * Simulate a decision (AC 2). Forwards the EXACT request inputs to the ONE
89
+ * {@link import('../../authorization/index.js').DecisionAuthority.decide} and
90
+ * wraps its {@link Decision}. NEVER a second decision path.
91
+ *
92
+ * A thrown `AuthorizationUnavailableError` (transient) propagates unchanged
93
+ * (fail-closed + retryable); only a returned decision is wrapped.
94
+ */
95
+ async function simulate(deps, request) {
96
+ const decision = await deps.decide.decide(request.principal, request.action, request.resource, request.context);
97
+ return wrapDecision(decision);
98
+ }