@astram/guard 0.37.0 → 0.40.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 (69) hide show
  1. package/dist/agent/agent-provenance.d.ts +24 -0
  2. package/dist/agent/agent-provenance.d.ts.map +1 -1
  3. package/dist/agent/agent-provenance.js +33 -1
  4. package/dist/auth/auth.controller.d.ts.map +1 -1
  5. package/dist/auth/auth.controller.js +5 -1
  6. package/dist/auth/auth.module.d.ts.map +1 -1
  7. package/dist/auth/auth.module.js +40 -2
  8. package/dist/auth/dto.d.ts +2 -0
  9. package/dist/auth/dto.d.ts.map +1 -1
  10. package/dist/auth/tokens.d.ts +14 -0
  11. package/dist/auth/tokens.d.ts.map +1 -1
  12. package/dist/auth/tokens.js +16 -2
  13. package/dist/authentication/service-account-principal.d.ts +29 -0
  14. package/dist/authentication/service-account-principal.d.ts.map +1 -0
  15. package/dist/authentication/service-account-principal.js +55 -0
  16. package/dist/authz/mariadb-policy-store.d.ts +38 -3
  17. package/dist/authz/mariadb-policy-store.d.ts.map +1 -1
  18. package/dist/authz/mariadb-policy-store.js +61 -4
  19. package/dist/completeness/catalog-reconciler.d.ts +10 -1
  20. package/dist/completeness/catalog-reconciler.d.ts.map +1 -1
  21. package/dist/completeness/catalog-reconciler.js +23 -4
  22. package/dist/completeness/ports/catalog-store.d.ts +19 -2
  23. package/dist/completeness/ports/catalog-store.d.ts.map +1 -1
  24. package/dist/enforcement/facts-version.d.ts +22 -0
  25. package/dist/enforcement/facts-version.d.ts.map +1 -0
  26. package/dist/enforcement/facts-version.js +34 -0
  27. package/dist/enforcement/global-enforcement.guard.d.ts +9 -26
  28. package/dist/enforcement/global-enforcement.guard.d.ts.map +1 -1
  29. package/dist/enforcement/global-enforcement.guard.js +48 -177
  30. package/dist/enforcement/session-facts-reload.d.ts +66 -0
  31. package/dist/enforcement/session-facts-reload.d.ts.map +1 -0
  32. package/dist/enforcement/session-facts-reload.js +168 -0
  33. package/dist/identity/auth-facts.controller.d.ts.map +1 -1
  34. package/dist/identity/auth-facts.controller.js +5 -1
  35. package/dist/identity/identity-actions.d.ts +9 -1
  36. package/dist/identity/identity-actions.d.ts.map +1 -1
  37. package/dist/identity/identity-actions.js +12 -1
  38. package/dist/identity/module-registry.bridge.d.ts +16 -0
  39. package/dist/identity/module-registry.bridge.d.ts.map +1 -1
  40. package/dist/identity/module-registry.bridge.js +45 -0
  41. package/dist/identity/permission-facts.adapter.d.ts +41 -1
  42. package/dist/identity/permission-facts.adapter.d.ts.map +1 -1
  43. package/dist/identity/permission-facts.adapter.js +98 -1
  44. package/dist/index.d.ts +6 -5
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +12 -6
  47. package/dist/internal.d.ts +23 -0
  48. package/dist/internal.d.ts.map +1 -1
  49. package/dist/internal.js +36 -1
  50. package/dist/module/shield-tokens.d.ts +87 -11
  51. package/dist/module/shield-tokens.d.ts.map +1 -1
  52. package/dist/module/shield-tokens.js +8 -1
  53. package/dist/notifications/notification.service.d.ts +3 -0
  54. package/dist/notifications/notification.service.d.ts.map +1 -1
  55. package/dist/notifications/notification.service.js +9 -0
  56. package/dist/request-auth/request-principal.d.ts +5 -0
  57. package/dist/request-auth/request-principal.d.ts.map +1 -1
  58. package/dist/request-auth/request-principal.js +7 -1
  59. package/dist/request-auth/session-token-binder.d.ts +79 -6
  60. package/dist/request-auth/session-token-binder.d.ts.map +1 -1
  61. package/dist/request-auth/session-token-binder.js +264 -173
  62. package/dist/session/call-principals.d.ts +54 -0
  63. package/dist/session/call-principals.d.ts.map +1 -0
  64. package/dist/session/call-principals.js +38 -0
  65. package/dist/session/session-principal.d.ts +86 -0
  66. package/dist/session/session-principal.d.ts.map +1 -0
  67. package/dist/session/session-principal.js +139 -0
  68. package/migrations/1710000000143-AddPermissionGroup.cjs +41 -0
  69. package/package.json +5 -5
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decideOnSessionFacts = decideOnSessionFacts;
4
+ const session_token_binder_js_1 = require("../request-auth/session-token-binder.js");
5
+ const request_principal_js_1 = require("../request-auth/request-principal.js");
6
+ const session_facts_als_js_1 = require("../request-auth/session-facts-als.js");
7
+ const facts_version_js_1 = require("./facts-version.js");
8
+ /** A subtree re-derive that was due but could not be done (resolver error / empty / junk). */
9
+ const SUBTREE_REDERIVE_FAILED = Symbol('subtree-rederive-failed');
10
+ /** Steps 1–4 above. Throws only what `decide()` throws. */
11
+ async function decideOnSessionFacts(deps, input) {
12
+ const { principal, claims, accessToken, classification } = input;
13
+ // ── ADR-0011 SESSION-FACTS HOT PATH ──────────────────────────────────────────
14
+ // Enter the session-facts ALS scope with THIS session's cached grants around the decide() call.
15
+ // The app-owned `SessionFactsReader` (an ALS-backed reader wired into the decision authority)
16
+ // reads the SAME `SHIELD_SESSION_FACTS_ALS` store inside decide(), so gate 5 gets these facts and
17
+ // can serve the coarse decision from cache (no DB reload) when the cached version is still fresh.
18
+ //
19
+ // CROSS-PRINCIPAL ISOLATION: `als.run(store, cb)` binds `store` to this async context and
20
+ // everything decide() awaits, and ONLY that context. The store is built HERE from THESE claims.
21
+ //
22
+ // FAIL-CLOSED: no projector wired / absent / malformed binding → `claims.cachedFacts` is
23
+ // undefined → the store carries `cachedFacts: null` → gate 5 DB-reloads. The cache is only ever
24
+ // consulted; it never fabricates a permit.
25
+ //
26
+ // RELOAD SIGNAL (security hardening Phase 1C): when gate 5 reloads THIS principal's grants, the
27
+ // framework-built authority reports the reloaded (authoritative) version here.
28
+ //
29
+ // TIME BOUND (ADR-0035): cached facts at or past their `validUntilMs` (the next start or end of
30
+ // a role posting's window — a change no version bump marks) are treated as ABSENT, so gate 5
31
+ // reloads them (and the roles with them, below).
32
+ let reloaded;
33
+ const usableFacts = (0, facts_version_js_1.usableCachedFacts)(claims.cachedFacts, input.nowMs);
34
+ const factsStore = {
35
+ cachedFacts: usableFacts,
36
+ permissionsVersion: usableFacts?.permissionsVersion ?? 0,
37
+ onReload: (principalId, tenantId, grants) => {
38
+ if (principalId === principal.id && tenantId === principal.tenantId) {
39
+ reloaded = grants;
40
+ }
41
+ },
42
+ };
43
+ const decision = await session_facts_als_js_1.SHIELD_SESSION_FACTS_ALS.run(factsStore, () => deps.decisionAuthority.decide(principal, { key: classification.action }, { level: 'object_type', typeKey: classification.typeKey, tenantId: principal.tenantId }, { isAuthenticated: true }));
44
+ // The type-level decision above is on the principal's OWN tenant, which every subtree contains,
45
+ // so it does not depend on the subtree. Hence: decide first, then hand on the re-derived
46
+ // principal.
47
+ //
48
+ // LIVE ROLES (ADR-0035, GAPS #4): the reload also carries the principal's in-effect roles (when
49
+ // the app port reports them). The caller gets them now (role-keyed record rules, list scope,
50
+ // shares, the engine's record checks all read `principal.roleIds`), and the binding is rewritten
51
+ // with the reloaded facts + roles together, so the next requests are served from the cache
52
+ // (GAPS #6) with the same live roles.
53
+ // MANDATORY 2FA (auth capabilities R2.5, AC-9): re-evaluate when the permission version moved
54
+ // past the session's requirement stamp — gate 5 just told us the version (its reload, or the
55
+ // fresh cached facts it served). Unchanged version ⇒ no DB query. A failed evaluation caches
56
+ // nothing, so the next request (or refresh) reloads and retries.
57
+ let enforced = claims;
58
+ let mfaFailed = false;
59
+ const mfa = deps.mfaRequirement;
60
+ if (mfa !== undefined && mfa !== null) {
61
+ try {
62
+ enforced = await mfa.refresh(accessToken ?? '', claims, {
63
+ version: reloaded?.permissionsVersion ?? usableFacts?.permissionsVersion,
64
+ grants: reloaded ?? usableFacts ?? undefined,
65
+ });
66
+ }
67
+ catch {
68
+ mfaFailed = true;
69
+ }
70
+ }
71
+ let handed = principal;
72
+ let subtreeStale = false;
73
+ if (reloaded !== undefined && !mfaFailed) {
74
+ const liveRoles = (0, session_token_binder_js_1.liveRoleIds)(reloaded);
75
+ const current = liveRoles !== undefined ? { ...claims, roleIds: liveRoles } : claims;
76
+ const rederived = await rederiveSubtreeOnVersionMove(deps, accessToken, current, reloaded.permissionsVersion);
77
+ subtreeStale = rederived === SUBTREE_REDERIVE_FAILED;
78
+ // A subtree re-derive that was due but FAILED (resolver error / empty) keeps the facts
79
+ // uncached, so the next request reloads and retries it (the Phase 1C retry guarantee).
80
+ if (rederived !== SUBTREE_REDERIVE_FAILED) {
81
+ await rebindReloadedGrants(deps, accessToken, claims, reloaded, liveRoles);
82
+ }
83
+ if (rederived !== null && rederived !== SUBTREE_REDERIVE_FAILED) {
84
+ handed = rederived;
85
+ }
86
+ else if (liveRoles !== undefined) {
87
+ const withRoles = (0, request_principal_js_1.principalFromClaims)(current);
88
+ if (withRoles !== null)
89
+ handed = withRoles;
90
+ }
91
+ }
92
+ // G-036 M1 (SPEC §5 run-loop): the version the principal above was derived under, from what
93
+ // gate 5 already reported (no new read). Absent when gate 5 reported none or the subtree
94
+ // re-derive failed (the principal's subtree then belongs to no single version). For a ROOT
95
+ // principal gate 5 loads and checks no grants, so cached facts it never compared with the
96
+ // tenant's version say nothing (SPEC v8): absent.
97
+ const factsVersion = (0, facts_version_js_1.derivedFactsVersion)(principal, reloaded, usableFacts, subtreeStale);
98
+ return { decision, principal: handed, enforced, mfaFailed, factsVersion };
99
+ }
100
+ /**
101
+ * Write gate 5's reloaded grants and the live roles onto the session binding (ADR-0035). Session
102
+ * bindings only: a service-account key has no binding (its roles and scope are read live per
103
+ * request by the key store). Best-effort and conditional (same session, same tenant, fresher
104
+ * facts, `XX`): a miss or a Redis error only means the next request reloads again.
105
+ */
106
+ async function rebindReloadedGrants(deps, accessToken, claims, grants, liveRoles) {
107
+ if (claims.sessionId === '' || claims.kind === 'service_account')
108
+ return;
109
+ try {
110
+ await deps.tokenBinder.refreshGrants(accessToken, claims.sessionId, claims.tenantId, grants, liveRoles);
111
+ }
112
+ catch {
113
+ // Best-effort: the decision and the handed principal already use the reloaded grants.
114
+ }
115
+ }
116
+ /**
117
+ * Re-derive the session's scope subtree after gate 5 reloaded facts at `reloadedVersion`
118
+ * (security hardening Phase 1C). Identity bumps a tenant's permission version when a company is
119
+ * created, moved or deleted under it, so a reload at a version newer than the bound subtree's
120
+ * stamp means the subtree may be stale: resolve it again with the SAME resolver login uses,
121
+ * rebind it (token + session entries) and return the principal to hand on.
122
+ *
123
+ * Off the hot path: runs only for a session binding that carries a subtree, with a resolver
124
+ * wired, and a reload NEWER than its stamp (or no stamp yet — once, then stamped). That is the
125
+ * only DB read added (one closure query), and only on a version change.
126
+ *
127
+ * FAIL-CLOSED, NON-WIDENING: a resolver error, a non-array or an EMPTY result →
128
+ * {@link SUBTREE_REDERIVE_FAILED}: the bound subtree stays (never replaced by a guess, never
129
+ * widened), the stamp is not advanced, the reloaded facts are not cached (ADR-0035), and the next
130
+ * request reloads and retries. `null` = no re-derive was due. A failed Redis rebind still returns
131
+ * the fresh principal (the DB answer is authoritative); the next reload retries the rebind.
132
+ */
133
+ async function rederiveSubtreeOnVersionMove(deps, accessToken, claims, reloadedVersion) {
134
+ const resolver = deps.scopeSubtreeResolver;
135
+ if (resolver === undefined || resolver === null)
136
+ return null;
137
+ // Session bindings only: a service-account key has no binding (its scope is read live per
138
+ // request by the key store) and no session id.
139
+ if (claims.sessionId === '' || claims.kind === 'service_account')
140
+ return null;
141
+ // Only a binding that carries a subtree: an absent one is the self-node fallback (no resolver
142
+ // or a failed login-time resolve) and stays that way until the next login/refresh.
143
+ if (claims.scopeSubtreeNodeIds === undefined || claims.scopeSubtreeNodeIds.length === 0) {
144
+ return null;
145
+ }
146
+ const stamp = claims.scopeSubtreeVersion;
147
+ if (stamp !== undefined && reloadedVersion <= stamp)
148
+ return null;
149
+ let subtree;
150
+ try {
151
+ const resolved = await resolver.resolveSubtree(claims.tenantId);
152
+ if (!Array.isArray(resolved) || resolved.length === 0)
153
+ return SUBTREE_REDERIVE_FAILED;
154
+ if (resolved.some((n) => typeof n !== 'string' || n.length === 0)) {
155
+ return SUBTREE_REDERIVE_FAILED;
156
+ }
157
+ subtree = [...resolved];
158
+ }
159
+ catch {
160
+ return SUBTREE_REDERIVE_FAILED;
161
+ }
162
+ await deps.tokenBinder.rederiveScopeSubtree(accessToken, claims.sessionId, claims.tenantId, subtree, reloadedVersion);
163
+ return (0, request_principal_js_1.principalFromClaims)({
164
+ ...claims,
165
+ scopeSubtreeNodeIds: subtree,
166
+ scopeSubtreeVersion: reloadedVersion,
167
+ });
168
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"auth-facts.controller.d.ts","sourceRoot":"","sources":["../../src/identity/auth-facts.controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAaH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAGlF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAiB,KAAK,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AACjG,OAAO,EAGL,KAAK,kBAAkB,EACvB,KAAK,6BAA6B,EACnC,MAAM,+BAA+B,CAAC;AAEvC,+FAA+F;AAC/F,MAAM,WAAW,4BAA6B,SAAQ,kBAAkB;IACtE,QAAQ,CAAC,KAAK,EAAE,SAAS,EAAE,CAAC;IAC5B,iFAAiF;IACjF,QAAQ,CAAC,UAAU,EAAE,wBAAwB,CAAC;CAC/C;AAED,qBACa,mBAAmB;IAI5B,OAAO,CAAC,QAAQ,CAAC,WAAW;IAG5B,OAAO,CAAC,QAAQ,CAAC,KAAK;IAItB,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;gBAPf,WAAW,EAAE,kBAAkB,GAAG,SAAS,EAG3C,KAAK,EAAE,6BAA6B,GAAG,SAAS,EAIhD,cAAc,CAAC,GAAE,qBAAqB,GAAG,IAAI,aAAA;IAGhE;;;;;OAKG;IAGG,YAAY,CACU,aAAa,CAAC,EAAE,MAAM,GAC/C,OAAO,CAAC,kBAAkB,GAAG,4BAA4B,CAAC;IA8B7D;;;;;OAKG;IAGG,qBAAqB,CACC,aAAa,CAAC,EAAE,MAAM,GAC/C,OAAO,CAAC;QAAE,OAAO,E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BAAsB;CAerC"}
@@ -64,7 +64,11 @@ let AuthFactsController = class AuthFactsController {
64
64
  throw new common_1.HttpException({ error: 'authorization_unavailable' }, common_1.HttpStatus.SERVICE_UNAVAILABLE);
65
65
  }
66
66
  try {
67
- return await this.facts.projectFor(principal.id, principal.tenantId, principal.isRoot);
67
+ // Department scope fact: the session's kind, from the bound session only, never the
68
+ // request (the node set is the active company, `principal.tenantId`).
69
+ return await this.facts.projectFor(principal.id, principal.tenantId, principal.isRoot, {
70
+ kind: principal.kind,
71
+ });
68
72
  }
69
73
  catch (err) {
70
74
  if (err instanceof permission_facts_adapter_js_1.AuthorizationUnavailableError) {
@@ -39,8 +39,16 @@ export type ServiceAccountAction = (typeof SERVICE_ACCOUNT_ACTIONS)[number];
39
39
  * assistant routes and every agent call, `propose` is reserved for proposals (M3), and
40
40
  * `restricted_data` lets a user's run send `restricted` data to an approved model provider.
41
41
  */
42
- export declare const AGENT_ACTIONS: readonly ["chat", "propose", "restricted_data", "client_data_approve"];
42
+ export declare const AGENT_ACTIONS: readonly ["chat", "propose", "restricted_data", "client_data_approve", "unattended", "unattended_admin"];
43
43
  export type AgentAction = (typeof AGENT_ACTIONS)[number];
44
+ /**
45
+ * `agent_audit`'s action vocabulary (agent-activity-audit SPEC v1 §5, §10): `read` only, the key
46
+ * `identity:agent_audit:read` that gates the tenant admin's read of the assistant's task and
47
+ * action records (`GET /agent/audit/…`). A separate authority-only type on purpose: the key is
48
+ * NOT covered by `identity:agent:*` (supervisor decision (a)).
49
+ */
50
+ export declare const AGENT_AUDIT_ACTIONS: readonly ["read"];
51
+ export type AgentAuditAction = (typeof AGENT_AUDIT_ACTIONS)[number];
44
52
  /**
45
53
  * The per-tenant agent modes stored in `agent_tenant_setting.ats_mode` (agent-read-capabilities
46
54
  * SPEC §5 H, §11 D-3; model-provider-client-data SPEC v7 §4 B). `off` is the default when no row
@@ -1 +1 @@
1
- {"version":3,"file":"identity-actions.d.ts","sourceRoot":"","sources":["../../src/identity/identity-act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M,mBAAmB,mBAAoB,CAAC;AACrD,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEpE;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,uCAAwC,CAAC;AACxE,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAElE;;;GAGG;AACH,eAAO,MAAM,4BAA4B,+BAAgC,CAAC;AAC1E,MAAM,MAAM,wBAAwB,GAAG,CAAC,OAAO,4BAA4B,CAAC,CAAC,MAAM,CAAC,CAAC;AAErF;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAEnF;AAED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAE1E;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,iBAAiB,GAAG,SAAS,MAAM,EAAE,CAEnE;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAE9D"}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AGENT_BOOTSTRAP_TENANT_MODES = exports.AGENT_TENANT_MODES = exports.AGENT_ACTIONS = exports.SERVICE_ACCOUNT_ACTIONS = exports.RECORD_SHARE_ACTIONS = exports.CROSS_TENANT_GRANT_ACTIONS = exports.IDENTITY_ACTIONS = exports.MODULE_KEY = void 0;
3
+ exports.AGENT_BOOTSTRAP_TENANT_MODES = exports.AGENT_TENANT_MODES = exports.AGENT_AUDIT_ACTIONS = exports.AGENT_ACTIONS = exports.SERVICE_ACCOUNT_ACTIONS = exports.RECORD_SHARE_ACTIONS = exports.CROSS_TENANT_GRANT_ACTIONS = exports.IDENTITY_ACTIONS = exports.MODULE_KEY = void 0;
4
4
  exports.agentTenantModeKey = agentTenantModeKey;
5
5
  exports.agentClientDataTombstoneKey = agentClientDataTombstoneKey;
6
6
  exports.agentClientDataAckKey = agentClientDataAckKey;
@@ -50,7 +50,18 @@ exports.AGENT_ACTIONS = [
50
50
  // model-provider-client-data SPEC v7 §5 E: approve (or confirm, revoke) sending this company's
51
51
  // real data to an external AI provider. Assigned to no role by default.
52
52
  'client_data_approve',
53
+ // background-agent-tasks SPEC v4 §3, §10: start and run an unattended (service-account) task, and
54
+ // the per-company switch `PUT /identity/agent/unattended`. Both assigned to no role by default.
55
+ 'unattended',
56
+ 'unattended_admin',
53
57
  ];
58
+ /**
59
+ * `agent_audit`'s action vocabulary (agent-activity-audit SPEC v1 §5, §10): `read` only, the key
60
+ * `identity:agent_audit:read` that gates the tenant admin's read of the assistant's task and
61
+ * action records (`GET /agent/audit/…`). A separate authority-only type on purpose: the key is
62
+ * NOT covered by `identity:agent:*` (supervisor decision (a)).
63
+ */
64
+ exports.AGENT_AUDIT_ACTIONS = ['read'];
54
65
  /**
55
66
  * The per-tenant agent modes stored in `agent_tenant_setting.ats_mode` (agent-read-capabilities
56
67
  * SPEC §5 H, §11 D-3; model-provider-client-data SPEC v7 §4 B). `off` is the default when no row
@@ -9,4 +9,20 @@ export declare function buildIdentityModuleRegistry(inputs: readonly ObjectTypeI
9
9
  * `RegistrationError` on invalid text, like the registry build.
10
10
  */
11
11
  export declare function permissionTextByKey(inputs: readonly ObjectTypeInput[]): ReadonlyMap<string, PermissionText>;
12
+ /** First effective order given to a group that declares none (permission groups SPEC §10). */
13
+ export declare const UNORDERED_PERMISSION_GROUP_BASE = 1000;
14
+ /**
15
+ * Permission groups (SPEC §5 guard): the display-only group of every action of the given types,
16
+ * keyed by the SAME permission keys as {@link permissionTextByKey}; types without a group are
17
+ * absent. Types sharing a group key must declare the same (trimmed) label and the same `order`
18
+ * (or none), else engine `RegistrationError` names both types and the key. Effective order: the
19
+ * declared one, else `UNORDERED_PERMISSION_GROUP_BASE + i`, `i` the group's first-appearance
20
+ * index among the groups without a declared order, in `inputs` order. Never read by grants,
21
+ * wildcards, bundles or decide().
22
+ */
23
+ export declare function permissionGroupByKey(inputs: readonly ObjectTypeInput[]): ReadonlyMap<string, {
24
+ readonly key: string;
25
+ readonly label: string;
26
+ readonly order: number;
27
+ }>;
12
28
  //# sourceMappingURL=module-registry.bridge.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"module-registry.bridge.d.ts","sourceRoot":"","sources":["../../src/identity/module-registry.bridge.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EACV,cAAc,EAIf,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAc,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AASlF,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,GAAG,cAAc,CAgC9F;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,SAAS,eAAe,EAAE,GACjC,WAAW,CAAC,MAAM,EAAE,cAAc,CAAC,CAQrC"}
1
+ {"version":3,"file":"module-registry.bridge.d.ts","sourceRoot":"","sources":["../../src/identity/module-registry.bridge.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EACV,cAAc,EAIf,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAc,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAelF,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,SAAS,eAAe,EAAE,GAAG,cAAc,CAgC9F;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,SAAS,eAAe,EAAE,GACjC,WAAW,CAAC,MAAM,EAAE,cAAc,CAAC,CAQrC;AAED,8FAA8F;AAC9F,eAAO,MAAM,+BAA+B,OAAO,CAAC;AAEpD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,SAAS,eAAe,EAAE,GACjC,WAAW,CAAC,MAAM,EAAE;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CA6B/F"}
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UNORDERED_PERMISSION_GROUP_BASE = void 0;
3
4
  exports.buildIdentityModuleRegistry = buildIdentityModuleRegistry;
4
5
  exports.permissionTextByKey = permissionTextByKey;
6
+ exports.permissionGroupByKey = permissionGroupByKey;
5
7
  /**
6
8
  * Bridge: engine ObjectTypes → a populated core ModuleRegistry. Ported from astram3 (framework
7
9
  * now owns identity). Engine ObjectTypes describe physical tables; core's gates + the
@@ -66,3 +68,46 @@ function permissionTextByKey(inputs) {
66
68
  }
67
69
  return out;
68
70
  }
71
+ /** First effective order given to a group that declares none (permission groups SPEC §10). */
72
+ exports.UNORDERED_PERMISSION_GROUP_BASE = 1000;
73
+ /**
74
+ * Permission groups (SPEC §5 guard): the display-only group of every action of the given types,
75
+ * keyed by the SAME permission keys as {@link permissionTextByKey}; types without a group are
76
+ * absent. Types sharing a group key must declare the same (trimmed) label and the same `order`
77
+ * (or none), else engine `RegistrationError` names both types and the key. Effective order: the
78
+ * declared one, else `UNORDERED_PERMISSION_GROUP_BASE + i`, `i` the group's first-appearance
79
+ * index among the groups without a declared order, in `inputs` order. Never read by grants,
80
+ * wildcards, bundles or decide().
81
+ */
82
+ function permissionGroupByKey(inputs) {
83
+ const regs = inputs.map(toObjectType);
84
+ const seen = new Map();
85
+ const unordered = [];
86
+ for (const reg of regs) {
87
+ const g = (0, engine_1.permissionGroupOf)(reg);
88
+ if (g === null)
89
+ continue;
90
+ const first = seen.get(g.key);
91
+ if (first === undefined) {
92
+ seen.set(g.key, { typeKey: reg.typeKey, label: g.label, order: g.order });
93
+ if (g.order === null)
94
+ unordered.push(g.key);
95
+ }
96
+ else if (first.label !== g.label || first.order !== g.order) {
97
+ throw new engine_1.RegistrationError(`registrations '${first.typeKey}' and '${reg.typeKey}' declare group '${g.key}' with a ` +
98
+ 'different label or order; every type in a group must declare the same label and order.');
99
+ }
100
+ }
101
+ const out = new Map();
102
+ for (const reg of regs) {
103
+ const g = (0, engine_1.permissionGroupOf)(reg);
104
+ if (g === null)
105
+ continue;
106
+ const order = g.order ?? exports.UNORDERED_PERMISSION_GROUP_BASE + unordered.indexOf(g.key);
107
+ const group = { key: g.key, label: g.label, order };
108
+ for (const action of (0, identity_actions_js_1.actionsOf)(reg)) {
109
+ out.set((0, core_1.derivePermissionKey)(identity_actions_js_1.MODULE_KEY, reg.typeKey, action), group);
110
+ }
111
+ }
112
+ return out;
113
+ }
@@ -15,11 +15,26 @@ export interface AuthFactDto {
15
15
  readonly resource?: string;
16
16
  readonly reasonCode?: string;
17
17
  }
18
+ /** The closed list of read limits a session can be told about (department-scope-fact §10). */
19
+ export type ScopeLimitKind = 'department';
20
+ /** Per readable type key, the kinds of limit on the session's reads of it (UX only, §11). */
21
+ export type ScopeLimits = Readonly<Record<string, readonly ScopeLimitKind[]>>;
18
22
  export interface AuthFactProjection {
19
23
  readonly principalId: string;
20
24
  readonly facts: readonly AuthFactDto[];
21
25
  readonly projectedAt: number;
22
26
  readonly permissionsVersion?: number;
27
+ /**
28
+ * Department scope fact (department-scope-fact SPEC §3): the readable types whose reads an
29
+ * effective department deny policy narrows for this session. UX only — no decision, gate, list
30
+ * or ceiling reads it. Omitted when empty, for root and service accounts, and on a read error.
31
+ */
32
+ readonly scopeLimits?: ScopeLimits;
33
+ }
34
+ /** Session context for {@link MariaDbPermissionFactsAdapter.projectFor}'s scope fact. */
35
+ export interface ProjectForOptions {
36
+ /** The principal kind; the scope fact is computed for `'user'` only (absent ⇒ none). */
37
+ readonly kind?: string;
23
38
  }
24
39
  /**
25
40
  * The freshness token `GET /identity/auth-facts` (`permissionsVersion`) and
@@ -57,12 +72,31 @@ export declare class MariaDbPermissionFactsAdapter {
57
72
  constructor(pool: Pool, listActions: () => readonly string[], controlPlaneKeys: readonly string[], now?: () => number,
58
73
  /** Framework database names; absent ⇒ resolved from `SHIELD_DB_NAMESPACE` here, once. */
59
74
  schemas?: FrameworkSchemaNames);
60
- projectFor(principalId: string, tenantId: string, isRoot: boolean): Promise<AuthFactProjection>;
75
+ projectFor(principalId: string, tenantId: string, isRoot: boolean, opts?: ProjectForOptions): Promise<AuthFactProjection>;
61
76
  /** The raw per-tenant permission version (not the {@link authFactsVersion} token). */
62
77
  currentVersionFor(_principalId: string, tenantId: string): Promise<number>;
63
78
  private readRoleIdsForTenant;
64
79
  private readGrantKeys;
65
80
  private readVersion;
81
+ /**
82
+ * Department scope fact (department-scope-fact SPEC §5): the readable types whose reads an
83
+ * effective department deny policy narrows for this caller. ONE parameterized SELECT over
84
+ * `<authz>.record_permission_rule` — deny rows, action `read` or `*`, the readable types, the
85
+ * active company or a global (NULL-tenant) rule — reading only the grouping, subject, type and
86
+ * operator columns (never the value, the field or a row id). Rows group by `rpr_policy_uuid`
87
+ * per type (NULL ⇒ a singleton), exactly as the list scope groups them
88
+ * (`MariaDbListScopeAdapter`); a type is limited when some group's every row
89
+ * `subjectMatches` the caller's roles and some row uses `not_in_my_departments`.
90
+ *
91
+ * Node set: the ACTIVE COMPANY plus NULL-tenant rules only, never the session subtree. That
92
+ * set is contained in both the list scope's subtree set and the global-type set, so a
93
+ * "limited" is never wrong; a parent caller limited only by a child company's policy gets no
94
+ * hint (the safe direction).
95
+ *
96
+ * Fail closed means ABSENT: any error returns `undefined`, never a throw and never a guess.
97
+ * UX only — nothing decides from it.
98
+ */
99
+ readScopeLimits(_principalId: string, tenantId: string, roleIds: readonly string[], readableTypes: readonly string[]): Promise<ScopeLimits | undefined>;
66
100
  /**
67
101
  * Expand wildcard grant keys against the registry's declared actions:
68
102
  * 'identity' / 'identity:*' → every 'identity:' action
@@ -72,6 +106,12 @@ export declare class MariaDbPermissionFactsAdapter {
72
106
  */
73
107
  private expandGrantKeys;
74
108
  }
109
+ /**
110
+ * The type keys the caller can read: every `<module>:<type>:read` key among the expanded grant
111
+ * keys (department-scope-fact §5). Only these may appear in `scopeLimits` (§11, "only types the
112
+ * session can read").
113
+ */
114
+ export declare function readableTypeKeys(expandedKeys: readonly string[]): string[];
75
115
  export declare const isExplicitOnlyPermissionKey: (key: string) => boolean;
76
116
  /**
77
117
  * Expand wildcard grant keys against the registry's declared actions:
@@ -1 +1 @@
1
- {"version":3,"file":"permission-facts.adapter.d.ts","sourceRoot":"","sources":["../../src/identity/permission-facts.adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,qCAAqC,CAAC;AAE7C,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AACD,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,KAAK,EAAE,SAAS,WAAW,EAAE,CAAC;IACvC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CACtC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,gBAAgB,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CAE/E;AAED,yFAAyF;AACzF,qB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exports.AuthorizationUnavailableError = void 0;
13
13
  exports.authFactsVersion = authFactsVersion;
14
+ exports.readableTypeKeys = readableTypeKeys;
14
15
  exports.expandPermissionGrantKeys = expandPermissionGrantKeys;
15
16
  const framework_schema_names_js_1 = require("../config/framework-schema-names.js");
17
+ const rule_subject_js_1 = require("../authz/rule-subject.js");
18
+ /** The department operator that, in a deny group, narrows the caller's reads (§10). */
19
+ const DEPARTMENT_DENY_OPERATOR = 'not_in_my_departments';
16
20
  /**
17
21
  * The freshness token `GET /identity/auth-facts` (`permissionsVersion`) and
18
22
  * `GET /identity/permissions-version` (`version`) carry: the per-tenant
@@ -63,18 +67,30 @@ class MariaDbPermissionFactsAdapter {
63
67
  this.app = s.app;
64
68
  this.authz = s.authz;
65
69
  }
66
- async projectFor(principalId, tenantId, isRoot) {
70
+ async projectFor(principalId, tenantId, isRoot, opts = {}) {
67
71
  try {
68
72
  const roleIds = await this.readRoleIdsForTenant(principalId, tenantId);
69
73
  const granted = roleIds.length > 0 ? await this.readGrantKeys(roleIds) : [];
70
74
  const expanded = this.expandGrantKeys(granted);
71
75
  const keys = isRoot ? [...new Set([...expanded, ...this.controlPlaneKeys])] : expanded;
72
76
  const permissionsVersion = authFactsVersion(await this.readVersion(tenantId), isRoot);
77
+ // Department scope fact (SPEC §6): non-root user principals with a readable type only.
78
+ // Best-effort: `readScopeLimits` never throws, and an absent or empty result adds nothing.
79
+ let scopeLimits;
80
+ if (!isRoot && opts.kind === 'user') {
81
+ const readable = readableTypeKeys(expanded);
82
+ if (readable.length > 0) {
83
+ scopeLimits = await this.readScopeLimits(principalId, tenantId, roleIds, readable);
84
+ }
85
+ }
73
86
  return {
74
87
  principalId,
75
88
  facts: keys.map((action) => ({ action, allowed: true })),
76
89
  projectedAt: this.now(),
77
90
  permissionsVersion,
91
+ ...(scopeLimits !== undefined && Object.keys(scopeLimits).length > 0
92
+ ? { scopeLimits }
93
+ : {}),
78
94
  };
79
95
  }
80
96
  catch (err) {
@@ -114,6 +130,72 @@ class MariaDbPermissionFactsAdapter {
114
130
  const rows = (await this.pool.query(`SELECT apv_version FROM \`${this.authz}\`.\`authz_permission_version\` WHERE apv_tenant_uuid = ? LIMIT 1`, [tenantId]));
115
131
  return rows[0] !== undefined ? Number(rows[0].apv_version) : 0;
116
132
  }
133
+ /**
134
+ * Department scope fact (department-scope-fact SPEC §5): the readable types whose reads an
135
+ * effective department deny policy narrows for this caller. ONE parameterized SELECT over
136
+ * `<authz>.record_permission_rule` — deny rows, action `read` or `*`, the readable types, the
137
+ * active company or a global (NULL-tenant) rule — reading only the grouping, subject, type and
138
+ * operator columns (never the value, the field or a row id). Rows group by `rpr_policy_uuid`
139
+ * per type (NULL ⇒ a singleton), exactly as the list scope groups them
140
+ * (`MariaDbListScopeAdapter`); a type is limited when some group's every row
141
+ * `subjectMatches` the caller's roles and some row uses `not_in_my_departments`.
142
+ *
143
+ * Node set: the ACTIVE COMPANY plus NULL-tenant rules only, never the session subtree. That
144
+ * set is contained in both the list scope's subtree set and the global-type set, so a
145
+ * "limited" is never wrong; a parent caller limited only by a child company's policy gets no
146
+ * hint (the safe direction).
147
+ *
148
+ * Fail closed means ABSENT: any error returns `undefined`, never a throw and never a guess.
149
+ * UX only — nothing decides from it.
150
+ */
151
+ async readScopeLimits(_principalId, tenantId, roleIds, readableTypes) {
152
+ try {
153
+ const types = [...new Set(readableTypes)];
154
+ if (types.length === 0)
155
+ return {};
156
+ const rows = (await this.pool.query(`SELECT rpr_policy_uuid, rpr_type_key, rpr_subject_kind, rpr_subject_value,
157
+ rpr_subject_role_uuids, rpr_operator
158
+ FROM \`${this.authz}\`.\`record_permission_rule\`
159
+ WHERE rpr_effect = 'deny'
160
+ AND rpr_action IN ('read', '*')
161
+ AND rpr_type_key IN (${types.map(() => '?').join(', ')})
162
+ AND (rpr_tenant_uuid = ? OR rpr_tenant_uuid IS NULL)`, [...types, tenantId]));
163
+ if (!Array.isArray(rows))
164
+ return undefined;
165
+ // Group per type by rpr_policy_uuid; every NULL-policy row is its own singleton group.
166
+ const groups = new Map();
167
+ let nullGroupSeq = 0;
168
+ for (const row of rows) {
169
+ const key = row.rpr_policy_uuid != null
170
+ ? `p:${row.rpr_type_key}:${row.rpr_policy_uuid}`
171
+ : `n:${nullGroupSeq++}`;
172
+ const bucket = groups.get(key);
173
+ if (bucket)
174
+ bucket.push(row);
175
+ else
176
+ groups.set(key, [row]);
177
+ }
178
+ const limited = new Set();
179
+ for (const groupRows of groups.values()) {
180
+ const head = groupRows[0];
181
+ if (head === undefined || !types.includes(head.rpr_type_key))
182
+ continue;
183
+ if (!groupRows.every((row) => (0, rule_subject_js_1.subjectMatches)(row, roleIds)))
184
+ continue;
185
+ if (groupRows.some((row) => row.rpr_operator === DEPARTMENT_DENY_OPERATOR)) {
186
+ limited.add(head.rpr_type_key);
187
+ }
188
+ }
189
+ const out = {};
190
+ for (const type of types)
191
+ if (limited.has(type))
192
+ out[type] = ['department'];
193
+ return out;
194
+ }
195
+ catch {
196
+ return undefined;
197
+ }
198
+ }
117
199
  /**
118
200
  * Expand wildcard grant keys against the registry's declared actions:
119
201
  * 'identity' / 'identity:*' → every 'identity:' action
@@ -126,6 +208,21 @@ class MariaDbPermissionFactsAdapter {
126
208
  }
127
209
  }
128
210
  exports.MariaDbPermissionFactsAdapter = MariaDbPermissionFactsAdapter;
211
+ /**
212
+ * The type keys the caller can read: every `<module>:<type>:read` key among the expanded grant
213
+ * keys (department-scope-fact §5). Only these may appear in `scopeLimits` (§11, "only types the
214
+ * session can read").
215
+ */
216
+ function readableTypeKeys(expandedKeys) {
217
+ const out = new Set();
218
+ for (const key of expandedKeys) {
219
+ const parts = key.split(':');
220
+ if (parts.length === 3 && parts[2] === 'read' && parts[1] !== undefined && parts[1] !== '') {
221
+ out.add(parts[1]);
222
+ }
223
+ }
224
+ return [...out];
225
+ }
129
226
  /**
130
227
  * Keys no wildcard ever reaches (they need an exact grant): the `identity:schema_change:*` keys
131
228
  * (they change the database structure), the keys of an admin-defined table type
package/dist/index.d.ts CHANGED
@@ -15,9 +15,9 @@
15
15
  * `@nestjs/core`, `reflect-metadata`, `rxjs` so the host owns one copy of each.
16
16
  */
17
17
  export { guardMigrationsDir } from './migrations-dir.js';
18
- export { buildIdentityModuleRegistry, permissionTextByKey, } from './identity/module-registry.bridge.js';
18
+ export { buildIdentityModuleRegistry, permissionTextByKey, permissionGroupByKey, UNORDERED_PERMISSION_GROUP_BASE, } from './identity/module-registry.bridge.js';
19
19
  export type { PermissionText } from '@astram/engine';
20
- export { MODULE_KEY, IDENTITY_ACTIONS, CROSS_TENANT_GRANT_ACTIONS, RECORD_SHARE_ACTIONS, SERVICE_ACCOUNT_ACTIONS, AGENT_ACTIONS, AGENT_TENANT_MODES, AGENT_BOOTSTRAP_TENANT_MODES, agentTenantModeKey, agentClientDataTombstoneKey, agentClientDataAckKey, actionsFor, actionsOf, type AgentAction, type AgentTenantMode, type AgentBootstrapTenantMode, } from './identity/identity-actions.js';
20
+ export { MODULE_KEY, IDENTITY_ACTIONS, CROSS_TENANT_GRANT_ACTIONS, RECORD_SHARE_ACTIONS, SERVICE_ACCOUNT_ACTIONS, AGENT_ACTIONS, AGENT_AUDIT_ACTIONS, AGENT_TENANT_MODES, AGENT_BOOTSTRAP_TENANT_MODES, agentTenantModeKey, agentClientDataTombstoneKey, agentClientDataAckKey, actionsFor, actionsOf, type AgentAction, type AgentAuditAction, type AgentTenantMode, type AgentBootstrapTenantMode, } from './identity/identity-actions.js';
21
21
  export { ShieldModule, SHIELD_DECISION_AUTHORITY, SHIELD_RECORD_AUTHORIZATION, type ShieldModuleOptions, type ShieldModuleAsyncOptions, type RecordAuthorizationInputs, } from './module/shield.module.js';
22
22
  export { Public, Classified, CLASSIFICATION_METADATA, DEFAULT_CLASSIFIED_ACTION, normalizeClassification, } from './enforcement/classification.decorator.js';
23
23
  export type { Classification } from './enforcement/classification.decorator.js';
@@ -25,7 +25,7 @@ export { UuidPipe, uuidField, optionalUuidField, uuidArrayField } from './enforc
25
25
  export { OperationInventoryScanner } from './completeness/operation-inventory-scanner.js';
26
26
  export { CatalogReconciler, CatalogGatabilityError } from './completeness/catalog-reconciler.js';
27
27
  export type { ReconcileOptions } from './completeness/catalog-reconciler.js';
28
- export type { CatalogStore, CatalogPermissionRow, CatalogTextUpdate, ReconcileReport, } from './completeness/ports/catalog-store.js';
28
+ export type { CatalogStore, CatalogPermissionRow, CatalogPermissionGroup, CatalogTextUpdate, ReconcileReport, } from './completeness/ports/catalog-store.js';
29
29
  export { SHIELD_SESSION_TOKEN_BINDER, SHIELD_SERVICE_AUTHENTICATOR, } from './request-auth/tokens.js';
30
30
  export { SessionTokenBinder } from './request-auth/session-token-binder.js';
31
31
  export type { BoundPrincipalClaims, SessionTokenBinderOptions, } from './request-auth/session-token-binder.js';
@@ -53,11 +53,12 @@ export { ObjectStoreBootCheck } from './storage/object-store-boot-check.js';
53
53
  export { FileIntake, FILE_INTAKE_REQUEST_KEY, FILE_INTAKE_DEFAULT_MAX_BYTES, type FileIntakeOptions, type FileIntakeResult, } from './storage/file-intake.interceptor.js';
54
54
  export type { ShieldStorageOption, AppFileProfile } from './storage/storage.providers.js';
55
55
  export { APP_CONTENT_TYPE_DENY_LIST, MAX_APP_FILE_PROFILES, isDeniedAppContentType, } from './storage/storage.providers.js';
56
- export { SHIELD_OBJECT_STORE, SHIELD_FILE_INGEST, SHIELD_AGENT_FILE_READER, type AgentFileReader, type OpenedFileLike, type DescribedFileLike, SHIELD_PROPOSAL_PORT, SHIELD_PROPOSAL_READER, SHIELD_AGENT_TASK_CALLS, SHIELD_AGENT_CLIENT_DATA_PROFILES, SHIELD_AGENT_CLIENT_DATA_DISCLOSURE, type AgentClientDataProfiles, type AgentClientDataProfile, type AgentClientDataMaskingPolicy, type AgentClientDataDisclosurePort, type ProposalPort, type ProposalReader, type ProposalReaderQuery, type ProposalReaderState, type ProposalDraftLike, type ProposalProvenanceLike, type SubmittedProposalLike, type ProposalSummaryLike, type ProposalSummaryPage, type AgentTaskCalls, SHIELD_FILE_SHARE, FILE_SHARE_ERROR_CODES, FileShareError, type FileShareErrorCode, type FileShareParent, type FileSharePort, type FileShareResult, } from './module/shield-tokens.js';
56
+ export { SHIELD_OBJECT_STORE, SHIELD_FILE_INGEST, SHIELD_AGENT_FILE_READER, type AgentFileReader, type OpenedFileLike, type DescribedFileLike, SHIELD_PROPOSAL_PORT, SHIELD_PROPOSAL_READER, SHIELD_AGENT_TASK_CALLS, SHIELD_AGENT_CLIENT_DATA_PROFILES, SHIELD_AGENT_CLIENT_DATA_DISCLOSURE, type AgentClientDataProfiles, type AgentClientDataProfile, type AgentClientDataMaskingPolicy, type AgentClientDataDisclosurePort, type ProposalPort, type ProposalReader, type ProposalReaderQuery, type ProposalReaderState, type ProposalDraftLike, type ProposalProvenanceLike, type SubmittedProposalLike, type ProposalSummaryLike, type ProposalSummaryPage, type AgentTaskCalls, SHIELD_AGENT_AUDIT_LINKS, type AgentAuditLinks, type AgentAuditProposalLink, SHIELD_FILE_SHARE, FILE_SHARE_ERROR_CODES, FileShareError, type FileShareErrorCode, type FileShareParent, type FileSharePort, type FileShareResult, } from './module/shield-tokens.js';
57
57
  export { loadObjectStorageConfig, DEFAULT_OBJECT_STORAGE_MAX_BYTES, type ObjectStorageConfig, type LoadObjectStorageConfigOptions, } from './config/app-config.js';
58
58
  export { MariaDbSessionRecordStore, SHIELD_SESSION_RECORD_STORE, RedisHotSessionStore, SHIELD_HOT_SESSION_STORE, RedisRecentRotationStore, type RedisRecentRotationStoreOptions, CryptoTokenGenerator, Sha256RefreshTokenHasher, SystemClock, cryptoTokenGeneratorProvider, refreshHasherProvider, systemClockProvider, SHIELD_TOKEN_GENERATOR, SHIELD_REFRESH_HASHER, SHIELD_CLOCK, HotRevokingSessionRecordStore, type SessionHotRevoker, type LineageSessionLookup, SHIELD_SESSION_LIFETIMES, ROTATE_GRACE_MS, accessBindingTtlMs, } from './session/index.js';
59
59
  export { MariaDbRecordPermissionRuleAdapter, SHIELD_RECORD_RULE_PORT, type RuleQueryable, } from './authz/mariadb-record-rule-adapter.js';
60
- export { MariaDbPolicyStore, SHIELD_POLICY_STORE, type RuleQueryable as PolicyStoreQueryable, } from './authz/mariadb-policy-store.js';
60
+ export { MariaDbPolicyStore, SHIELD_POLICY_STORE, type RuleQueryable as PolicyStoreQueryable, type PolicyStoreConnection, type PolicyWriteOptions, } from './authz/mariadb-policy-store.js';
61
+ export type { AuthFactProjection, AuthFactDto, ScopeLimitKind, ScopeLimits, } from './identity/permission-facts.adapter.js';
61
62
  export { MariaDbListScopeAdapter, SHIELD_LIST_SCOPE_PORT, type ListScopeQueryable, } from './authz/mariadb-list-scope-adapter.js';
62
63
  export { translateListScope, UnknownScopeFieldError, UnloadedDepartmentSetError, type TranslatedListScope, type ListScopePrincipal, } from './authz/list-scope-sql.js';
63
64
  export { readViewerDepartmentCodes, DEPARTMENT_CODE_PATTERN, type DepartmentQueryable, } from './authz/viewer-departments.js';