@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,246 @@
1
+ "use strict";
2
+ /**
3
+ * Team B commands — the **cross-tenant invitation state machine** (§10bis / AC 9).
4
+ *
5
+ * The CONSENT path: the ONLY way a NON-root grants another tenant access.
6
+ *
7
+ * createInvitation → `pending` (confers NOTHING). Blast-radius ("gives tenant X
8
+ * access to ALL your <object type>s until revoked") + confirm required for a
9
+ * whole-object-type grant. Audited.
10
+ * transitionInvitation → enforces {@link INVITATION_TRANSITIONS}:
11
+ * - `pending → accepted|denied|expired|revoked`
12
+ * - `accepted → revoked|expired`
13
+ * - terminals (`denied`/`expired`/`revoked`) dead-end.
14
+ * An illegal transition → `invalid_transition`.
15
+ * ACCEPT activates the grant WITHIN THE CEILING (scope + actions + expiry). We
16
+ * REUSE the L8 ceiling SEMANTICS (an accepted, unexpired, unrevoked invitation
17
+ * confers exactly its declared scope+actions until it expires) — we do not
18
+ * re-derive them. An already-expired invitation cannot be accepted into an
19
+ * active grant.
20
+ * DENY / EXPIRE / REVOKE confer NOTHING. EITHER SIDE (owning or grantee tenant)
21
+ * revokes with IMMEDIATE effect. Every transition is audited.
22
+ *
23
+ * ⛔ An invitation is ONLY a live grant while `accepted` + unexpired + unrevoked —
24
+ * `pending`/`denied`/`expired`/`revoked` confer no access (the query side reads
25
+ * {@link CrossTenantInvitationStore.listActiveGrants}, which returns only accepted
26
+ * ones; the accept transition is what makes it appear there).
27
+ *
28
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.isLegalTransition = isLegalTransition;
32
+ exports.canPartyTransition = canPartyTransition;
33
+ exports.makeCreateInvitation = makeCreateInvitation;
34
+ exports.makeTransitionInvitation = makeTransitionInvitation;
35
+ const reason_codes_js_1 = require("../../authorization/reason-codes.js");
36
+ const types_js_1 = require("../types.js");
37
+ const grants_js_1 = require("./grants.js");
38
+ const pipeline_js_1 = require("./pipeline.js");
39
+ /**
40
+ * Is `to` a legal transition FROM `from` per {@link INVITATION_TRANSITIONS}? A
41
+ * transition to the SAME state, or one not listed, is illegal. Fail-closed on any
42
+ * malformed state (an unknown `from` has no outgoing transitions).
43
+ */
44
+ function isLegalTransition(from, to) {
45
+ const allowed = types_js_1.INVITATION_TRANSITIONS[from];
46
+ if (allowed === undefined) {
47
+ return false;
48
+ }
49
+ return (0, reason_codes_js_1.strictTrue)(allowed.some((s) => s === to));
50
+ }
51
+ /**
52
+ * Which tenants may revoke / transition an invitation. EITHER side — the owning
53
+ * tenant OR the grantee tenant — may revoke with immediate effect (§3.7).
54
+ *
55
+ * The OWNER side is verified strictly by tenant id (`actingTenantId ===
56
+ * owningTenantId`). The GRANTEE side is verified ONLY when a `granteeTenantId` is
57
+ * RESOLVED from the invitation's email (the record stores no grantee tenant id) —
58
+ * absent a resolved grantee tenant, the grantee side is NOT authorized (a
59
+ * stranger and an unverifiable grantee both fail closed). Exported so the query
60
+ * side (and tests) can reuse the exact rule.
61
+ */
62
+ function canPartyTransition(invitation, actingTenantId, resolvedGranteeTenantId) {
63
+ if (actingTenantId === invitation.owningTenantId) {
64
+ return true;
65
+ }
66
+ if (resolvedGranteeTenantId !== undefined &&
67
+ resolvedGranteeTenantId.length > 0 &&
68
+ resolvedGranteeTenantId === actingTenantId) {
69
+ return true;
70
+ }
71
+ return false;
72
+ }
73
+ function makeCreateInvitation(deps) {
74
+ const clock = deps.now ?? Date.now;
75
+ return async function createInvitation(mutation, command) {
76
+ return (0, pipeline_js_1.runAdminCommand)({
77
+ mutation,
78
+ // Whole-object-type cross-tenant grant is destructive/high-blast → confirm
79
+ // required (the safeguard classifies invitation_create as destructive).
80
+ hasConfirmToken: (0, grants_js_1.extractHasConfirm)(mutation),
81
+ validate: () => {
82
+ if (typeof command.owningTenantId !== 'string' ||
83
+ command.owningTenantId.length === 0 ||
84
+ typeof command.granteeTenantEmail !== 'string' ||
85
+ command.granteeTenantEmail.length === 0) {
86
+ return { ok: false, reason: 'not_found' };
87
+ }
88
+ // The owner may only offer access to THEIR OWN tenant's objects — the
89
+ // owning tenant must be the acting admin's target tenant (an admin can't
90
+ // offer another tenant's data). Root passes the delegated gate but
91
+ // still names a coherent owning tenant here.
92
+ if (command.owningTenantId !== mutation.targetTenantId &&
93
+ !(0, reason_codes_js_1.strictTrue)(mutation.admin.isRoot)) {
94
+ return {
95
+ ok: false,
96
+ reason: 'unilateral_cross_tenant',
97
+ };
98
+ }
99
+ if (!Array.isArray(command.objectTypeKeys) ||
100
+ command.objectTypeKeys.length === 0 ||
101
+ command.objectTypeKeys.some((k) => typeof k !== 'string' || k.length === 0)) {
102
+ return { ok: false, reason: 'invalid_policy' };
103
+ }
104
+ if (!Array.isArray(command.actions) ||
105
+ command.actions.length === 0 ||
106
+ command.actions.some((a) => typeof a !== 'string' || a.length === 0)) {
107
+ return { ok: false, reason: 'invalid_policy' };
108
+ }
109
+ if (typeof command.expiresAtMs !== 'number' ||
110
+ !Number.isFinite(command.expiresAtMs) ||
111
+ command.expiresAtMs <= clock()) {
112
+ // The ceiling MUST carry a real FUTURE expiry (a grant that is already
113
+ // expired confers nothing — reject at create).
114
+ return { ok: false, reason: 'invalid_policy' };
115
+ }
116
+ if (typeof command.scope !== 'string' || command.scope.length === 0) {
117
+ return { ok: false, reason: 'invalid_policy' };
118
+ }
119
+ return null;
120
+ },
121
+ mutate: async () => deps.invitationStore.create({
122
+ owningTenantId: command.owningTenantId,
123
+ granteeTenantEmail: command.granteeTenantEmail,
124
+ objectTypeKeys: command.objectTypeKeys,
125
+ scope: command.scope,
126
+ actions: command.actions,
127
+ expiresAtMs: command.expiresAtMs,
128
+ }),
129
+ emitAudit: async (value, blastRadius) => {
130
+ await deps.audit.record({
131
+ type: 'admin_action',
132
+ occurredAtMs: clock(),
133
+ actorId: mutation.admin.id,
134
+ tenantId: mutation.targetTenantId,
135
+ attributes: (0, pipeline_js_1.buildAuditAttributes)(mutation, blastRadius, {
136
+ action: 'invitation_create',
137
+ invitationState: value.state, // 'pending' — confers nothing yet
138
+ granteeTenantEmail: value.granteeTenantEmail,
139
+ objectTypeKeys: value.objectTypeKeys,
140
+ offeredActions: value.actions,
141
+ }),
142
+ });
143
+ },
144
+ }, deps.decide);
145
+ };
146
+ }
147
+ function makeTransitionInvitation(deps) {
148
+ const clock = deps.now ?? Date.now;
149
+ return async function transitionInvitation(mutation, command) {
150
+ // Fetch once up-front so validate + mutate + audit share the record. A missing
151
+ // invitation is `not_found`; the state machine + party check run in validate.
152
+ let invitation = null;
153
+ return (0, pipeline_js_1.runAdminCommand)({
154
+ mutation,
155
+ hasConfirmToken: true, // transitions are not classified destructive per se
156
+ validate: async () => {
157
+ if (typeof command.invitationId !== 'string' ||
158
+ command.invitationId.length === 0) {
159
+ return { ok: false, reason: 'not_found' };
160
+ }
161
+ invitation = await deps.invitationStore.get(command.invitationId);
162
+ if (invitation === null) {
163
+ return { ok: false, reason: 'not_found' };
164
+ }
165
+ // ⛔ The state machine — an illegal transition is rejected.
166
+ if (!isLegalTransition(invitation.state, command.newState)) {
167
+ return {
168
+ ok: false,
169
+ reason: 'invalid_transition',
170
+ };
171
+ }
172
+ // EITHER-SIDE authorization: the acting tenant must be the owner or the
173
+ // resolved grantee. The grantee is addressed by EMAIL (no grantee tenant
174
+ // id on the record), so the grantee side is authorized only when an
175
+ // injected resolver maps the email to the acting tenant. Absent the
176
+ // resolver, only the owner is authorized (fail-closed). A root may
177
+ // act on either side.
178
+ const resolvedGrantee = deps.resolveGranteeTenant?.(invitation.granteeTenantEmail);
179
+ if (!(0, reason_codes_js_1.strictTrue)(mutation.admin.isRoot) &&
180
+ !canPartyTransition(invitation, mutation.admin.tenantId, resolvedGrantee)) {
181
+ return {
182
+ ok: false,
183
+ reason: 'unilateral_cross_tenant',
184
+ };
185
+ }
186
+ // ⛔ DEFECT 1 (round 2) — ACCEPT IS GRANTEE-ONLY (mutual consent, §10bis
187
+ // / AC 9). An invitation IS the consent mechanism: acceptance is the
188
+ // GRANTEE's act of consenting to RECEIVE the offered cross-tenant access.
189
+ // The either-side party check above lets the OWNER act on their own
190
+ // invitation (create/deny/revoke/expire) — but an owner ACCEPTING their
191
+ // own offer is a UNILATERAL cross-tenant grant with ZERO grantee consent
192
+ // (the same escalation class as RULING 1). So `accepted` is reachable
193
+ // ONLY by the resolved GRANTEE tenant, or a root (strict
194
+ // `=== true`). If `resolveGranteeTenant` is ABSENT the grantee tenant is
195
+ // unverifiable, so accept FAILS CLOSED — only a root may accept
196
+ // (owner-only acceptance would BE the bug). `deny`/`revoke`/`expired`
197
+ // remain allowed for EITHER side (§3.7 either-side revoke).
198
+ if (command.newState === 'accepted') {
199
+ const granteeCanAccept = resolvedGrantee !== undefined &&
200
+ resolvedGrantee.length > 0 &&
201
+ resolvedGrantee === mutation.admin.tenantId;
202
+ if (!(0, reason_codes_js_1.strictTrue)(mutation.admin.isRoot) &&
203
+ !granteeCanAccept) {
204
+ return {
205
+ ok: false,
206
+ reason: 'unilateral_cross_tenant',
207
+ };
208
+ }
209
+ }
210
+ // ACCEPT activates the grant WITHIN THE CEILING — an already-expired
211
+ // invitation cannot be accepted into an active grant (reuse the ceiling's
212
+ // expiry semantics; a stale accept confers nothing).
213
+ if (command.newState === 'accepted' &&
214
+ invitation.expiresAtMs <= clock()) {
215
+ return {
216
+ ok: false,
217
+ reason: 'invalid_transition',
218
+ };
219
+ }
220
+ return null;
221
+ },
222
+ mutate: async () => {
223
+ await deps.invitationStore.updateState(command.invitationId, command.newState);
224
+ },
225
+ emitAudit: async (_value, blastRadius) => {
226
+ const inv = invitation;
227
+ await deps.audit.record({
228
+ type: 'admin_action',
229
+ occurredAtMs: clock(),
230
+ actorId: mutation.admin.id,
231
+ tenantId: mutation.targetTenantId,
232
+ attributes: (0, pipeline_js_1.buildAuditAttributes)(mutation, blastRadius, {
233
+ action: 'invitation_transition',
234
+ invitationState: command.newState,
235
+ ...(inv !== null
236
+ ? {
237
+ fromState: inv.state,
238
+ granteeTenantEmail: inv.granteeTenantEmail,
239
+ }
240
+ : {}),
241
+ }),
242
+ });
243
+ },
244
+ }, deps.decide);
245
+ };
246
+ }
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ /**
3
+ * Team B command — **curatePermission** (rename / group a permission, AC 1).
4
+ *
5
+ * Overlays an admin-authored label/group on the registry-seeded catalog via the
6
+ * {@link CatalogStore} (the base catalog is the ModuleRegistry; curation is the
7
+ * overlay). Low-blast, non-destructive — it does NOT change access, only display —
8
+ * so it does not require a confirm token. Still routes the full §11.3 pipeline
9
+ * (delegated-admin gate → validate → mutate → audit) so every curation is
10
+ * attributable (invariant #6).
11
+ *
12
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.makeCuratePermission = makeCuratePermission;
16
+ const pipeline_js_1 = require("./pipeline.js");
17
+ /**
18
+ * Curate (rename/group) a permission. `label`/`group` are the human-readable
19
+ * overlay values; at least one must be present. Fails `invalid_policy` when both
20
+ * are absent/blank (nothing to curate) — reusing the closed deny taxonomy rather
21
+ * than inventing a reason.
22
+ */
23
+ function makeCuratePermission(deps) {
24
+ const clock = deps.now ?? Date.now;
25
+ return async function curatePermission(mutation, permissionKey, label, group) {
26
+ return (0, pipeline_js_1.runAdminCommand)({
27
+ mutation,
28
+ hasConfirmToken: true, // non-destructive — no confirm required
29
+ validate: () => {
30
+ const hasLabel = typeof label === 'string' && label.trim().length > 0;
31
+ const hasGroup = typeof group === 'string' && group.trim().length > 0;
32
+ if (!hasLabel && !hasGroup) {
33
+ // Nothing to curate — reject structurally (fail-closed).
34
+ return { ok: false, reason: 'invalid_policy' };
35
+ }
36
+ if (typeof permissionKey !== 'string' || permissionKey.length === 0) {
37
+ return { ok: false, reason: 'not_found' };
38
+ }
39
+ return null;
40
+ },
41
+ mutate: async () => {
42
+ await deps.catalogStore.setCuration({
43
+ permissionKey,
44
+ ...(typeof label === 'string' && label.trim().length > 0
45
+ ? { label }
46
+ : {}),
47
+ ...(typeof group === 'string' && group.trim().length > 0
48
+ ? { group }
49
+ : {}),
50
+ });
51
+ },
52
+ emitAudit: async (_value, blastRadius) => {
53
+ const permissionLabel = await deps.labels.resolve('permission', permissionKey, mutation.targetTenantId);
54
+ await deps.audit.record({
55
+ type: 'admin_action',
56
+ occurredAtMs: clock(),
57
+ actorId: mutation.admin.id,
58
+ tenantId: mutation.targetTenantId,
59
+ attributes: (0, pipeline_js_1.buildAuditAttributes)(mutation, blastRadius, {
60
+ action: 'curate_permission',
61
+ permissionLabel,
62
+ ...(label !== undefined ? { newLabel: label } : {}),
63
+ ...(group !== undefined ? { newGroup: group } : {}),
64
+ }),
65
+ });
66
+ },
67
+ }, deps.decide);
68
+ };
69
+ }
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ /**
3
+ * The Team-B command pipeline runner (§11.3 order) — the REAL-safeguard twin of
4
+ * the prelude's `runCommandPipeline`.
5
+ *
6
+ * ⛔ WHY THIS EXISTS. The frozen `admin-service.ts#runCommandPipeline` hardwires
7
+ * the FAIL-CLOSED STUB safeguards from `safeguards.ts` (which always deny /
8
+ * high-blast / confirm-required). Team B may NOT edit those frozen files. So each
9
+ * command routes through THIS runner, which executes the identical §11.3 ORDER but
10
+ * against Team B's REAL safeguards in `../safeguards-impl.ts`. The integration
11
+ * owner wires the command service to these runners; the frozen stub file stays
12
+ * byte-unchanged.
13
+ *
14
+ * FROZEN ORDER (identical to the prelude's):
15
+ * (1) DELEGATED-ADMIN CHECK — {@link checkDelegatedAdminImpl} (reuses decide()).
16
+ * (2) VALIDATE — the command's own structural check.
17
+ * (3) CONFIRM + BLAST-RADIUS — if {@link requiresConfirmImpl}, require the
18
+ * confirm token (else `confirm_required`) and compute the blast-radius.
19
+ * (4) MUTATE — apply via the store.
20
+ * (5) AUDIT — emit the `admin_action` event, with the blast-radius threaded into
21
+ * the event attributes for destructive commands (the reviewer note).
22
+ *
23
+ * Any step that denies short-circuits fail-closed BEFORE the mutation.
24
+ *
25
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
26
+ */
27
+ Object.defineProperty(exports, "__esModule", { value: true });
28
+ exports.runAdminCommand = runAdminCommand;
29
+ exports.withPayload = withPayload;
30
+ exports.buildAuditAttributes = buildAuditAttributes;
31
+ const safeguards_impl_js_1 = require("../safeguards-impl.js");
32
+ /**
33
+ * Run a mutating admin command through the frozen §11.3 pipeline against Team B's
34
+ * REAL safeguards. Every deny short-circuits fail-closed BEFORE the mutation.
35
+ *
36
+ * ⛔ `decide` is threaded into {@link checkDelegatedAdminImpl} — the ONE decision
37
+ * path (ADR-0001). The computed blast-radius is threaded into `emitAudit` (step 5)
38
+ * so it is recorded, not discarded.
39
+ */
40
+ async function runAdminCommand(step, decide, blastDeps = {}) {
41
+ // (1) DELEGATED-ADMIN CHECK — fail-closed, reuses decide() (ADR-0001 / §3.2).
42
+ const delegated = await (0, safeguards_impl_js_1.checkDelegatedAdminImpl)(step.mutation.admin, step.mutation, decide);
43
+ if (delegated.ok !== true) {
44
+ return {
45
+ ok: false,
46
+ reason: delegated.reason ?? 'delegated_admin_exceeds_authority',
47
+ };
48
+ }
49
+ // (2) VALIDATE — structural (guided policy / tier≠public / legal transition).
50
+ const invalid = await step.validate();
51
+ if (invalid !== null) {
52
+ return invalid;
53
+ }
54
+ // (3) CONFIRM + BLAST-RADIUS — destructive/high-blast requires a confirm token.
55
+ let blastRadius = null;
56
+ if ((0, safeguards_impl_js_1.requiresConfirmImpl)(step.mutation) === true) {
57
+ if (step.hasConfirmToken !== true) {
58
+ return { ok: false, reason: 'confirm_required' };
59
+ }
60
+ // Computed for the audit record; threaded into emitAudit below (not discarded).
61
+ blastRadius = await (0, safeguards_impl_js_1.computeBlastRadiusImpl)(step.mutation, blastDeps);
62
+ }
63
+ // (4) MUTATE — only reached after 1–3 pass (fail-closed order).
64
+ const value = await step.mutate();
65
+ // (5) AUDIT — every applied mutation is recorded, with the blast-radius threaded
66
+ // into the emitted event's attributes for destructive commands (invariant #6).
67
+ await step.emitAudit(value, blastRadius);
68
+ return { ok: true, value };
69
+ }
70
+ /**
71
+ * Return a copy of `mutation` whose `payload` is enriched with the command's own
72
+ * data, so the §11.3 safeguards (which read ONLY `mutation.payload`) can classify
73
+ * the delegated-admin scope / blast-radius / confirm-required. Each command calls
74
+ * this before {@link runAdminCommand} so the safeguard sees the grant/tier/policy/
75
+ * invitation details even when the service passed them as a separate argument.
76
+ *
77
+ * Existing payload keys (e.g. a caller-supplied `confirm` token) are PRESERVED —
78
+ * the command payload is merged UNDER them so a confirm token is never clobbered.
79
+ */
80
+ function withPayload(mutation, payload) {
81
+ const existing = mutation.payload !== null &&
82
+ typeof mutation.payload === 'object' &&
83
+ !Array.isArray(mutation.payload)
84
+ ? mutation.payload
85
+ : {};
86
+ return { ...mutation, payload: { ...payload, ...existing } };
87
+ }
88
+ /**
89
+ * Build the shared `attributes` bag for an `admin_action` audit event, folding in
90
+ * the mutation kind + (when present) the computed blast-radius. The single place
91
+ * the blast-radius→audit threading happens, so every command records it uniformly.
92
+ */
93
+ function buildAuditAttributes(mutation, blastRadius, extra) {
94
+ const base = {
95
+ commandKind: mutation.kind,
96
+ targetTenantId: mutation.targetTenantId,
97
+ ...extra,
98
+ };
99
+ if (blastRadius !== null) {
100
+ base.blastRadius = {
101
+ affectedPrincipalCount: blastRadius.affectedPrincipalCount,
102
+ severity: blastRadius.severity,
103
+ description: blastRadius.description,
104
+ ...(blastRadius.affectedRecordEstimate !== undefined
105
+ ? { affectedRecordEstimate: blastRadius.affectedRecordEstimate }
106
+ : {}),
107
+ };
108
+ }
109
+ return base;
110
+ }
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ /**
3
+ * Team B command — **authorPolicy** (the GUIDED-BUILDER validation, AC 5 / §3.4).
4
+ *
5
+ * A record-access policy is authored as a structured {@link GuidedPolicy}
6
+ * (typeKey + action + effect + field→operator→value conditions). There is NO
7
+ * raw-expression path — the type literally cannot represent one — but this module
8
+ * VALIDATES the structure defensively:
9
+ * - `typeKey` is a registered object type;
10
+ * - `action` is a non-empty stable key;
11
+ * - each condition's `field` is a KNOWN field of that object type (from the
12
+ * registry descriptor);
13
+ * - the condition's `operator` is VALID FOR THAT FIELD'S TYPE;
14
+ * - the condition's `value` is WELL-FORMED for the operator.
15
+ * Anything else → `invalid_policy`.
16
+ *
17
+ * On success the pipeline persists via {@link PolicyStore.savePolicy} + audits.
18
+ * A policy author is additive (it defines access rules); no confirm token needed.
19
+ *
20
+ * ADR-0003: framework-agnostic — no framework / HTTP / DB / node imports.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.isValidCondition = isValidCondition;
24
+ exports.validateGuidedPolicy = validateGuidedPolicy;
25
+ exports.makeAuthorPolicy = makeAuthorPolicy;
26
+ const pipeline_js_1 = require("./pipeline.js");
27
+ /** The complete closed set of guided operators (single source — mirrors the type). */
28
+ const ALL_OPERATORS = new Set([
29
+ 'eq',
30
+ 'ne',
31
+ 'in',
32
+ 'not_in',
33
+ 'gt',
34
+ 'lt',
35
+ 'gte',
36
+ 'lte',
37
+ 'contains',
38
+ 'not_contains',
39
+ 'is_null',
40
+ 'is_not_null',
41
+ 'is_owner',
42
+ 'is_not_owner',
43
+ ]);
44
+ /** Operators that take NO operand (a `value` is ignored / must be absent-ish). */
45
+ const NULLARY_OPERATORS = new Set([
46
+ 'is_null',
47
+ 'is_not_null',
48
+ 'is_owner',
49
+ 'is_not_owner',
50
+ ]);
51
+ /** Operators whose operand MUST be an array (set membership). */
52
+ const ARRAY_OPERATORS = new Set(['in', 'not_in']);
53
+ /** Operators that are ownership predicates — only valid on a REFERENCE field. */
54
+ const OWNERSHIP_OPERATORS = new Set([
55
+ 'is_owner',
56
+ 'is_not_owner',
57
+ ]);
58
+ /**
59
+ * Ordered/relational operators (`gt`/`lt`/`gte`/`lte`) — valid on scalar
60
+ * (non-reference) fields, never on a reference field (you don't order a reference).
61
+ */
62
+ const RELATIONAL_OPERATORS = new Set([
63
+ 'gt',
64
+ 'lt',
65
+ 'gte',
66
+ 'lte',
67
+ ]);
68
+ /** Text operators (`contains`/`not_contains`) — valid on scalar fields only. */
69
+ const TEXT_OPERATORS = new Set([
70
+ 'contains',
71
+ 'not_contains',
72
+ ]);
73
+ /**
74
+ * Is `operator` valid for a field, given whether the field is a REFERENCE field
75
+ * (carries `referencesTypeKey`)? This is the field-type↔operator compatibility
76
+ * rule (§3.4). Conservative + closed:
77
+ * - ownership predicates (`is_owner`/`is_not_owner`) → REFERENCE fields only;
78
+ * - relational (`gt`/`lt`/`gte`/`lte`) + text (`contains`/`not_contains`) →
79
+ * scalar (non-reference) fields only;
80
+ * - equality/membership/null (`eq`/`ne`/`in`/`not_in`/`is_null`/`is_not_null`) →
81
+ * valid on any field.
82
+ */
83
+ function operatorValidForField(operator, field) {
84
+ const isReference = typeof field.referencesTypeKey === 'string' &&
85
+ field.referencesTypeKey.length > 0;
86
+ if (OWNERSHIP_OPERATORS.has(operator)) {
87
+ return isReference;
88
+ }
89
+ if (RELATIONAL_OPERATORS.has(operator) || TEXT_OPERATORS.has(operator)) {
90
+ return !isReference;
91
+ }
92
+ // eq / ne / in / not_in / is_null / is_not_null — universally applicable.
93
+ return true;
94
+ }
95
+ /**
96
+ * Is the `value` well-formed for `operator`?
97
+ * - nullary operators (`is_null`/ownership) → value must be absent/undefined/null;
98
+ * - array operators (`in`/`not_in`) → value must be a non-empty array of primitives;
99
+ * - everything else → value must be a defined primitive (string/number/boolean).
100
+ */
101
+ function valueWellFormed(operator, value) {
102
+ if (NULLARY_OPERATORS.has(operator)) {
103
+ return value === undefined || value === null;
104
+ }
105
+ if (ARRAY_OPERATORS.has(operator)) {
106
+ return (Array.isArray(value) &&
107
+ value.length > 0 &&
108
+ value.every((v) => isPrimitive(v)));
109
+ }
110
+ return isPrimitive(value);
111
+ }
112
+ function isPrimitive(v) {
113
+ return (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean');
114
+ }
115
+ /**
116
+ * SHAPE validation of a single condition, WITHOUT the registry (used by the grant
117
+ * command for its inline conditions). Checks: `field` is a non-empty string, the
118
+ * `operator` is a member of the closed set, and the `value` is well-formed for the
119
+ * operator. Does NOT verify the field exists on an object type (that needs the
120
+ * registry + the owning type — done in {@link validateGuidedPolicy}).
121
+ */
122
+ function isValidCondition(condition) {
123
+ if (condition === null || typeof condition !== 'object') {
124
+ return false;
125
+ }
126
+ const c = condition;
127
+ if (typeof c.field !== 'string' || c.field.length === 0) {
128
+ return false;
129
+ }
130
+ if (typeof c.operator !== 'string' ||
131
+ !ALL_OPERATORS.has(c.operator)) {
132
+ return false;
133
+ }
134
+ return valueWellFormed(c.operator, c.value);
135
+ }
136
+ /**
137
+ * Fully validate a {@link GuidedPolicy} against the registry (AC 5). Returns `null`
138
+ * on success or an `invalid_policy` deny on ANY structural failure. Pure (reads the
139
+ * registry, no I/O). Exported so tests + the grant path can reuse it.
140
+ */
141
+ function validateGuidedPolicy(registry, policy) {
142
+ const invalid = { ok: false, reason: 'invalid_policy' };
143
+ // Defensive shape checks (the type guards most of this, but a hostile caller
144
+ // may cast `as GuidedPolicy` over junk — validate defensively, §3.4).
145
+ if (policy === null || typeof policy !== 'object') {
146
+ return invalid;
147
+ }
148
+ if (typeof policy.typeKey !== 'string' || policy.typeKey.length === 0) {
149
+ return invalid;
150
+ }
151
+ if (typeof policy.action !== 'string' || policy.action.length === 0) {
152
+ return invalid;
153
+ }
154
+ if (policy.effect !== 'allow' && policy.effect !== 'deny') {
155
+ return invalid;
156
+ }
157
+ if (!Array.isArray(policy.conditions)) {
158
+ return invalid;
159
+ }
160
+ // The object type must be REGISTERED (an unknown type has no known fields).
161
+ const objectType = registry.resolveObjectType(policy.typeKey);
162
+ if (objectType === undefined) {
163
+ return invalid;
164
+ }
165
+ const fieldsByKey = new Map();
166
+ for (const f of objectType.fields) {
167
+ fieldsByKey.set(f.key, f);
168
+ }
169
+ for (const condition of policy.conditions) {
170
+ // Basic shape (field string, operator in the closed set, value primitive-ish).
171
+ if (!isValidCondition(condition)) {
172
+ return invalid;
173
+ }
174
+ const c = condition;
175
+ // The field must be a KNOWN field of THIS object type.
176
+ const field = fieldsByKey.get(c.field);
177
+ if (field === undefined) {
178
+ return invalid;
179
+ }
180
+ // The operator must be valid FOR THAT FIELD'S TYPE.
181
+ if (!operatorValidForField(c.operator, field)) {
182
+ return invalid;
183
+ }
184
+ // The value must be well-formed for the operator (re-checked with field ctx).
185
+ if (!valueWellFormed(c.operator, c.value)) {
186
+ return invalid;
187
+ }
188
+ }
189
+ return null;
190
+ }
191
+ function makeAuthorPolicy(deps) {
192
+ const clock = deps.now ?? Date.now;
193
+ return async function authorPolicy(inMutation, policy) {
194
+ // Enrich so the delegated-admin safeguard reads the policy's object type +
195
+ // action (the admin must hold that action on that type to author a policy).
196
+ const mutation = (0, pipeline_js_1.withPayload)(inMutation, {
197
+ typeKey: policy.typeKey,
198
+ action: policy.action,
199
+ });
200
+ return (0, pipeline_js_1.runAdminCommand)({
201
+ mutation,
202
+ hasConfirmToken: true, // authoring a policy is additive
203
+ validate: () => validateGuidedPolicy(deps.registry, policy),
204
+ mutate: async () => deps.policyStore.savePolicy(mutation.targetTenantId, policy),
205
+ emitAudit: async (value, blastRadius) => {
206
+ await deps.audit.record({
207
+ type: 'admin_action',
208
+ occurredAtMs: clock(),
209
+ actorId: mutation.admin.id,
210
+ tenantId: mutation.targetTenantId,
211
+ attributes: (0, pipeline_js_1.buildAuditAttributes)(mutation, blastRadius, {
212
+ action: 'author_policy',
213
+ objectType: policy.typeKey,
214
+ policyAction: policy.action,
215
+ effect: policy.effect,
216
+ conditionCount: policy.conditions.length,
217
+ policyId: value.policyId,
218
+ }),
219
+ });
220
+ },
221
+ }, deps.decide);
222
+ };
223
+ }