@agentic-kit/db-tools 0.12.47 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
package/README.md CHANGED
@@ -27,11 +27,18 @@ npm install @agentic-kit/db-tools
27
27
 
28
28
  ## What's inside
29
29
 
30
- - **18 typed db tools** — `provision_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `delete_field`, `add_policies`, `add_records`, `manage_entity_types`, `create_api_key`, `run_codegen`, and the template suite (`list` / `create` / `apply` / `update` / `delete`). `constructiveDbTools` is the list, in registration order.
30
+ - **25 typed db tools** — `provision_database` / `replace_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `retype_field` / `delete_field`, `add_policies`, `add_records`, `list_entity_types` / `create_entity_type` / `delete_entity_type`, `create_api_key`, `run_codegen`, the template suite (`list` / `create` / `apply` / `update` / `delete`), the access tools (`explain_access`, `set_access`), and `describe_policy_type`. `constructiveDbTools` is the list, in registration order. Each states one effect (`read`, `write` or `destructive`) for every call; a change whose effect differs is its own tool (`retype_field` beside `update_field`, `replace_database` beside `provision_database`). Every failing call returns a `failure` (code, message, hint) beside the `details` it always had. A message or hint names no tool and no parameter: the calls that help travel as data (`failure.calls`, `result.calls`). Every object of a tool's own input refuses a key it does not have and names the nearest known one, instead of dropping it; Every change that names a table, a field, a template or an entity type finds it, or finds a new name's stored form free, before there is a plan to approve. A call that did only part of what was asked (a field without its unique constraint, some of the rows) returns the code `partial`, and its `details` hold the errors of the part that failed. Backend errors are read by their `extensions.code` and `extensions.class`, then the HTTP status (`extensions.http` first: the server answers HTTP 200 and puts the status there), then a masked internal error with its `errorId`; message text never decides, because the server masks the text it does not mean to show. `failureFromErrors(errors, action, meaning?)` is that mapping, exported for code that sends its own GraphQL (`postGraphQL`, which takes an `operationName`), and `FailureMeaning` names what a unique violation means for the call.
31
+
32
+ The public `extensions.context` of the error that decided goes into `failure.context`: a query over the backend's request limits (`QUERY_TOO_COSTLY`, `QUERY_TOO_DEEP`, `PAGE_SIZE_TOO_LARGE`, `REQUEST_TOO_LARGE`) is `query-too-large` with its numbers there, for example `{ cost, limit }`. An update or delete that answers with no row in its payload changed nothing: that is how row-level security answers for a row this account cannot see, so every tool that updates or deletes fails `no-rows-changed` there instead of reporting success. A create that answers without the new row fails `no-rows-changed` as well: the row may not exist, or a policy lets the account create it but not read it, and the hint names the call that shows whether it exists. `STEP_UP_REQUIRED` is `step-up-required`: the change needs a recent sign-in.
33
+
34
+ `constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`.
35
+
36
+ **Access.** The access of a table is its stored rules, grants and row security (`readTables`), and nothing here says who can or cannot reach a row. `explain_access` gives one plain sentence per stored rule (`explainPolicy`, from the words of the rule's Authz node), the grants, row security and the structural findings (`accessFindings`), each of which says what may happen. It and `describe_schema` return each stored rule through `asWritten`, in the one shape a caller writes (`{ $type, privileges, permissive, policy_role, data, with_check? }`), with every key the node's closed `parameter_schema` marks `readOnly` left out, nested nodes included, so a read carries no part the closed world refuses. A plan's rules use the same keys, with `words` in place of `data`. `set_access` replaces every rule of a table in one change with `owns: ['policies']`; the grants stay, and the Data nodes the rules need add their columns when the table lacks them. `add_policies` adds rules without replacing any. Both take rules only in the registry's blueprint shape (`{ $type, privileges, permissive, policy_role, policy_name, data }`, `AccessPolicyZod`), check each rule's shape against the registry's `BlueprintPolicy`, and check its data with `checkRule` (ajv over the node's closed `parameter_schema`, and the rule shapes these tools do not support) and its role before any plan. Every tool that sends rules, `provision_blueprint` included, sends them through `rulesToSend`: rules of one policy type, role, kind and data become one rule with all their privileges, and a rule the backend would skip (the same policy type and data as another) or refuse (a second policy row of one role, privilege and name) is refused before the plan. The plan holds the rules, grants and row security now and after, one sentence per rule, the findings the change adds and removes, the columns it adds (name, type, required, default) and the ones it reuses as they are. A reused column of another type than its Data node needs is blocked before the change (`conflict`, with `retype_field` and `delete_field`). When the person signed in to the app sees a row, a change that adds a required column with no value for the rows is blocked before anything is sent; otherwise the backend's refused NOT NULL comes back as a `conflict` with the `create_field` call that adds the column as optional first. After the change, the table is read back and compared with the plan by meaning (`policyDifference`); a difference is a `conflict`, and a read that fails is `unverified`. A refusal on the rows of an app table (`add_records`) suggests the read of its rules; a refusal on the control plane does not, because it is about the account's rights on the database.
37
+
31
38
  - **Host injection** — credentials, backend endpoints and data-plane tokens come from the host application, not from the package. Call `configureHost()` once at startup; the tools read it lazily per call.
32
39
  - **Project context** — `resolveProjectContext` / `resolveDataToken` resolve the database a tool acts on from the cwd's `.env` plus the host's session, and `deriveSubdomainEndpoint` derives its per-database endpoints. `probeDatabase` says whether that database is still there, and `readSchemaModel` reads its app tables.
33
40
  - **Provisioning model** — the pinned `node-type-registry` presets, the provision manifest, and overlay resolution (`resolveProvisionModules`).
34
- - **`constructiveGateDeps`** — the confirm gate's host capabilities (is the project runnable, is there a data token, what tables would a template copy) answered by these resolvers, so every adapter gates the same tools against the same project state instead of restating it.
41
+ - **`constructiveGateDeps`** — the confirm gate's host capabilities (the effect of a call, the tool's own first check, what tables would a template copy) answered by these tools, so every adapter gates the same tools against the same project state instead of restating it. Each tool runs its check (`toolPreconditions`: the project context on the plane it acts on, an owner, an app sign-in) before it changes anything, and the gate blocks a call whose check fails with that same failure.
35
42
  - **`toolSchema`** — a tool's zod parameters as plain JSON Schema, for adapters whose harness wants JSON Schema rather than zod.
36
43
 
37
44
  ## Usage
@@ -84,8 +91,15 @@ Failures carry a `code`: `signed-out`, `backend-unreachable`, `db-missing`, `db-
84
91
  Host hooks for this, all optional:
85
92
 
86
93
  - `persistBinding(binding)` saves the binding in the host's own store before `.env` is written. If it throws, `.env` is left alone, the ticket stays recorded, and the call fails `binding-not-saved`.
87
- - `toolReprovision: false` makes the tool's `reprovision: true` fail `reprovision-not-allowed`, for a host that replaces databases only after the user approves.
88
- - `reprovisionHint` replaces the "re-provision with `reprovision: true`" advice in failure messages.
94
+ - `toolReprovision: false` makes `replace_database` fail `reprovision-not-allowed`, for a host that replaces databases only after the user approves.
95
+ - `reprovisionHint` replaces the default advice to bind the directory to a new database in failure messages.
96
+ - `prewarmApp: false` stops the tools from preparing packages/app, for a host that prepares the app itself or not at all: `provision_database` clones and installs nothing while the backend provisions, and `run_codegen` creates, rewrites and installs nothing. It generates into the app that is there, and answers `app-missing`, with `appEndpoint` (the app data plane endpoint) in `failure.context` and `details`, when there is no app or a composed app has no installed packages.
97
+
98
+ ## Blueprints
99
+
100
+ `BlueprintZod`, `expandBlueprintDefaults`, `blueprintProblems` and the field type parsers live here. The tool's own parameters stay small: the definition is any blueprint, and `provision_blueprint` checks it inside the tool. `expandBlueprintDefaults` keeps every key it is given and fills in what the backend would otherwise need: for each new table DataId, its own nodes, the Data nodes its rules need (`dataNodesForPolicies`) and DataTimestamps, row security, the default grants (select, insert, update and delete for authenticated) when it gives none, each rule's role, privileges and kind, and each field's type and default in the backend's form (a type name becomes a FieldType, SQL text or a constant a FieldDefault); a field a node adds is dropped. Then each rule's data is checked with `checkRule`, a second rule of one type, role and privilege is refused, and the whole definition is checked with ajv against the registry's `blueprintDefinitionJsonSchema` (`blueprintProblems`); a schema, relation end or table the blueprint names must exist where it says. The backend's own blueprint codes (`VALIDATE_BLUEPRINT_*`) come back as `invalid-input` with the detail the backend sent. A code the backend raises while it builds a rule (`MEMBERSHIP_TYPE_MUST_BE_INT`, `BAD_RLS_EXPRESSION` and the others) is a sentence with the backend detail and a call for each policy type, and an internal error there never prints the backend's text.
101
+
102
+ The backend stores a new table or field name in its own form (`inflection.underscore`, then 63 characters: `r2_rows_a` becomes `r2_rowsa`). `storedName` is that rule, checked against the backend's own answers for 650 names. A plan says where a new name will be stored differently, a result names what the backend stored (read back by id after a blueprint), and a lookup by the name a table was made with names the stored one. `describe_policy_type` gives every Authz node in short, or one in full (its parameter schema, `use_when`, `avoid_when`, `risks` and the columns it needs).
89
103
 
90
104
  ## Blueprint builds
91
105
 
@@ -0,0 +1,93 @@
1
+ import { type AccessOperation, type TablePolicy } from './policies';
2
+ import { type AddedColumn, type ColumnDefault } from './provisioning';
3
+ import { type RelatedColumns } from './words';
4
+ /**
5
+ * What one rule of an Authz node checks: `member` (a member of the app or of a team), `named` (a person the row names),
6
+ * `shared` (a person given an explicit share), `anyone` (it checks the row only), `session` (the kind of session),
7
+ * `mixed` (it depends on nested parts), `none` (no one).
8
+ */
9
+ export interface AccessCheck {
10
+ person: 'member' | 'named' | 'shared' | 'anyone' | 'session' | 'mixed' | 'none';
11
+ /** For `member`: the app, a team the row names, or any team the row's owner shares with the person. */
12
+ scope?: 'app' | 'row' | 'peer';
13
+ /** The parameter that holds the row's owner column, when the row must name the person. */
14
+ owner?: string;
15
+ /** The parameter that holds the column of the team the row names. */
16
+ team?: string;
17
+ /** Meant as a limit on top of a grant, not as a grant. */
18
+ limit?: boolean;
19
+ /** Every row passes, with no check. */
20
+ always?: boolean;
21
+ }
22
+ export declare const ACCESS_CHECKS: Record<string, AccessCheck>;
23
+ /** One column of a table. */
24
+ export interface TableField {
25
+ name: string;
26
+ /** NOT NULL. */
27
+ required: boolean;
28
+ /** The default as the backend stores it (a FieldDefault), `null` for none, `'unknown'` when it cannot be read. */
29
+ default: ColumnDefault;
30
+ /** The type name, for example `uuid` or `text[]`, when known. */
31
+ type?: string;
32
+ }
33
+ export interface TableAccessInput {
34
+ policies: TablePolicy[];
35
+ /** When known. A grant to 'public' counts for every role. */
36
+ grants?: Array<{
37
+ roles: string[];
38
+ privileges: unknown[];
39
+ }>;
40
+ /** When known. */
41
+ rls_enabled?: boolean;
42
+ /** The table's columns, when known. */
43
+ fields?: TableField[];
44
+ /** The columns of other tables the rules name, by table id and by table name, when the reader read them. */
45
+ related?: RelatedColumns;
46
+ }
47
+ export interface AccessFinding {
48
+ /** Stable, kebab-case. */
49
+ id: string;
50
+ level: 'high' | 'medium' | 'low';
51
+ summary: string;
52
+ risk: string;
53
+ fix: string;
54
+ operations: AccessOperation[];
55
+ /** The columns the finding is about, when it is about columns. */
56
+ columns?: string[];
57
+ /** One sentence for each of those columns, when the finding differs by column. */
58
+ details?: string[];
59
+ }
60
+ /** A column the rules' Data nodes add that the table already has, but not as the node makes it. */
61
+ export interface ColumnGap {
62
+ column: string;
63
+ /** The Data node that adds the column. */
64
+ node: string;
65
+ /** The column as the node makes it. */
66
+ expected: AddedColumn;
67
+ /** The column the table has. */
68
+ actual: TableField;
69
+ /** What differs. A default or a type the table does not say (`'unknown'`, no `type`) does not differ. */
70
+ gaps: Array<'type' | 'required' | 'default'>;
71
+ }
72
+ /**
73
+ * The columns the rules' Data nodes add that the table has with another type, another NOT NULL, or another default. A
74
+ * generator keeps a column the table already has as it is, so the rule then reads a column it did not make.
75
+ */
76
+ export declare function columnGaps(given: TableField[], policies: Array<Pick<TablePolicy, 'type' | 'data'>>): ColumnGap[];
77
+ /** A column of the table one rule reads: the Authz node, its parameter (a path for a nested one) and the column. */
78
+ export interface ColumnRead {
79
+ type: string;
80
+ param: string;
81
+ column: string;
82
+ }
83
+ /**
84
+ * The columns of the table the rules read: each rule, its `with_check`, and the nodes nested in them, from the nodes'
85
+ * column parameters (registry defaults apply). `unknown` names the rule types with a part whose columns cannot be told:
86
+ * a stored raw expression, a type the registry does not have, or data its schema does not describe.
87
+ */
88
+ export declare function columnsReadByPolicies(policies: Array<Pick<TablePolicy, 'type' | 'data' | 'with_check'>>): {
89
+ columns: ColumnRead[];
90
+ unknown: string[];
91
+ };
92
+ /** What may be wrong with the rules of one table, by the shapes the backend docs warn about. */
93
+ export declare function accessFindings(input: TableAccessInput): AccessFinding[];
@@ -0,0 +1,434 @@
1
+ "use strict";
2
+ // Structural findings over the stored rules of one table: shapes the backend docs warn about, read from what each
3
+ // Authz node checks. No finding says who can or cannot reach a row: each one says what may happen, and fires when the
4
+ // rules leave it possible.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ACCESS_CHECKS = void 0;
7
+ exports.columnGaps = columnGaps;
8
+ exports.columnsReadByPolicies = columnsReadByPolicies;
9
+ exports.accessFindings = accessFindings;
10
+ const policies_1 = require("./policies");
11
+ const provisioning_1 = require("./provisioning");
12
+ const words_1 = require("./words");
13
+ exports.ACCESS_CHECKS = {
14
+ AuthzAllowAll: { person: 'anyone', always: true },
15
+ AuthzAppMemberOwner: { person: 'member', scope: 'app', owner: 'owner_field' },
16
+ AuthzAppMembership: { person: 'member', scope: 'app' },
17
+ AuthzColumnSecurity: { person: 'none' },
18
+ AuthzComposite: { person: 'mixed' },
19
+ AuthzDatabaseClaim: { person: 'session' },
20
+ AuthzDenyAll: { person: 'none' },
21
+ AuthzDirectOwner: { person: 'named', owner: 'entity_field' },
22
+ AuthzDirectOwnerAny: { person: 'named', owner: 'entity_fields' },
23
+ AuthzEntityMembership: { person: 'member', scope: 'row', team: 'entity_field' },
24
+ AuthzFilePath: { person: 'shared' },
25
+ AuthzHumanOnly: { person: 'session', limit: true },
26
+ AuthzMemberList: { person: 'named' },
27
+ AuthzMemberOwner: { person: 'member', scope: 'row', owner: 'owner_field', team: 'entity_field' },
28
+ AuthzNotReadOnly: { person: 'member', scope: 'row', team: 'entity_field', limit: true },
29
+ AuthzOrgHierarchy: { person: 'named' },
30
+ AuthzPeerOwnership: { person: 'member', scope: 'peer' },
31
+ AuthzPublishable: { person: 'anyone' },
32
+ AuthzRelatedEntityMembership: { person: 'member', scope: 'row' },
33
+ AuthzRelatedMemberList: { person: 'named' },
34
+ AuthzRelatedMemberOwner: { person: 'member', scope: 'row', owner: 'owner_field' },
35
+ AuthzRelatedPeerOwnership: { person: 'member', scope: 'peer' },
36
+ AuthzSystemOnly: { person: 'session', limit: true },
37
+ AuthzTemporal: { person: 'anyone' },
38
+ AuthzValueAllowed: { person: 'anyone' },
39
+ AuthzValueExists: { person: 'anyone' },
40
+ AuthzValueMatch: { person: 'anyone' }
41
+ };
42
+ const ANONYMOUS = 'anonymous';
43
+ // A field from a caller that does not give its default has a default no one knows, so what depends on it is never a
44
+ // guess.
45
+ function readableFields(fields) {
46
+ return fields?.map((field) => (field.default === undefined ? { ...field, default: 'unknown' } : field));
47
+ }
48
+ /**
49
+ * The columns the rules' Data nodes add that the table has with another type, another NOT NULL, or another default. A
50
+ * generator keeps a column the table already has as it is, so the rule then reads a column it did not make.
51
+ */
52
+ function columnGaps(given, policies) {
53
+ const fields = readableFields(given);
54
+ const expected = (0, provisioning_1.fieldsAddedByNodes)((0, provisioning_1.dataNodesForPolicies)(policies).nodes).fields;
55
+ return expected.flatMap((column) => {
56
+ const actual = fields.find((field) => field.name === column.name);
57
+ if (!actual)
58
+ return [];
59
+ const gaps = [];
60
+ if (actual.type !== undefined && actual.type !== column.type)
61
+ gaps.push('type');
62
+ if (actual.required === column.nullable)
63
+ gaps.push('required');
64
+ if (actual.default !== 'unknown' && column.default !== 'unknown' && JSON.stringify((0, policies_1.sorted)(actual.default)) !== JSON.stringify((0, policies_1.sorted)(column.default))) {
65
+ gaps.push('default');
66
+ }
67
+ return gaps.length ? [{ column: column.name, node: column.node, expected: column, actual, gaps }] : [];
68
+ });
69
+ }
70
+ // ─── Grants ──────────────────────────────────────────────────────
71
+ function granted(input, role, privilege) {
72
+ if (!input.grants)
73
+ return true;
74
+ return input.grants
75
+ .filter((grant) => grant.roles.includes(role) || grant.roles.includes(policies_1.PUBLIC))
76
+ .flatMap((grant) => grant.privileges)
77
+ .some((item) => String(Array.isArray(item) ? item[0] : item).toLowerCase() === privilege);
78
+ }
79
+ function rolesOf(input, parts) {
80
+ const named = [...parts.map((item) => item.role), ...(input.grants ?? []).flatMap((grant) => grant.roles)];
81
+ const roles = new Set([policies_1.SIGNED_IN, ...named.filter((role) => role !== policies_1.PUBLIC), ...(named.includes(policies_1.PUBLIC) ? [ANONYMOUS] : [])]);
82
+ return [policies_1.SIGNED_IN, ...[...roles].filter((role) => role !== policies_1.SIGNED_IN).sort()];
83
+ }
84
+ const FINDINGS = {
85
+ 'owner-outlives-membership': {
86
+ level: 'high',
87
+ summary: 'An owner check here does not check membership, so a person who leaves the team or the app may keep access to the rows they own.',
88
+ risk: 'A removed or banned member may still reach the rows that name them as their owner.',
89
+ fix: 'Use the owner check that also requires membership: AuthzMemberOwner for rows of a team, AuthzAppMemberOwner for rows of the whole app.'
90
+ },
91
+ 'app-membership-on-team-rows': {
92
+ level: 'medium',
93
+ summary: 'App membership here may let every member of the app in, whatever team the row belongs to, on a table whose rows belong to teams.',
94
+ risk: 'A member of one team may reach the rows of every other team.',
95
+ fix: 'Check membership of the team the row names (AuthzEntityMembership), and fence the owner check with it (AuthzMemberOwner).'
96
+ },
97
+ 'granted-without-policy': {
98
+ level: 'low',
99
+ summary: 'The table grants this operation, but no rule lets anyone do it, so the database refuses it.',
100
+ risk: 'People who expect to do it cannot.',
101
+ fix: 'Add a rule for this operation, or remove the grant.'
102
+ },
103
+ 'granted-role-without-policy': {
104
+ level: 'low',
105
+ summary: 'The table grants this operation to a role that no rule names, so the database refuses it for that role unless the role is a member of a role a rule names; these words cannot tell which roles are members of which.',
106
+ risk: 'People of that role who expect to do it may not be able to.',
107
+ fix: 'Add a rule for this operation for that role, or for public, or remove the grant.'
108
+ },
109
+ 'policies-without-row-security': {
110
+ level: 'high',
111
+ summary: 'The table has rules, but row security is off, so the rules do not apply.',
112
+ risk: 'Anyone the table grants an operation to can do it to every row.',
113
+ fix: 'Turn row security on for this table.'
114
+ },
115
+ 'anyone-can-change': {
116
+ level: 'high',
117
+ summary: 'No part of the rules for this change checks who the person is, so anyone who can use the table may create, change or delete rows.',
118
+ risk: 'Any signed-in person may change or delete rows that are not theirs.',
119
+ fix: 'Use a membership or owner rule for these operations, or add a restrictive one that checks who the person is; keep a rule for anyone for read only, and only when every row is public.'
120
+ },
121
+ 'limit-blocks-outside-grant': {
122
+ level: 'medium',
123
+ summary: 'A limit that requires membership may also block the people that another rule lets in on purpose without membership.',
124
+ risk: 'Shares, published rows or listed people outside the team may be cut off, so that rule does nothing for them.',
125
+ fix: 'Remove the membership limit, or require membership inside the rules that need it instead of as a limit on all of them.'
126
+ },
127
+ 'write-without-read': {
128
+ level: 'medium',
129
+ summary: 'The rule for this change may let in people who cannot read the row (for create: the row they make), and a change through the API reads it, so they may be refused.',
130
+ risk: 'People the rule names may get an error, and the words of the rule may promise access the table does not give.',
131
+ fix: 'Give read the same rule as the change or a wider one, or narrow the change to the people who can read the row; grant read where the table does not.'
132
+ },
133
+ 'raw-part-may-widen': {
134
+ level: 'high',
135
+ summary: 'A rule here holds a part its words may not fully state, in a place where it can let more people in (on its own, under OR, or under NOT); the words of the rule say which part, and why.',
136
+ risk: 'The part may let in people the words do not name, up to every signed-in person for every row.',
137
+ fix: 'Write the rule with Authz nodes, AND, OR and NOT, with the settings and column names its words state, so they state all of it; check the stored rule before you trust its words.'
138
+ },
139
+ 'reused-column-differs': {
140
+ level: 'medium',
141
+ summary: 'A column a rule reads is not as the rule\'s Data node makes it, so the table may not behave as the rule\'s words say; the details say how.',
142
+ risk: 'A create may fail for lack of a value, a row may name another owner or team than the words say, or the rule may not work on the column.',
143
+ fix: 'Give the column the type and the default its Data node gives, or set access that adds a column of its own.'
144
+ },
145
+ 'required-column-not-set': {
146
+ level: 'medium',
147
+ summary: 'A required column with no default is left from an access rule the table no longer has, so every create must send a value for it.',
148
+ risk: 'A create that does not send it fails, and nothing in the access of the table says why.',
149
+ fix: 'Give the column a default or make it optional, remove it, or set access whose rules use it again.'
150
+ }
151
+ };
152
+ const MAX_CLAUSES = 64;
153
+ const checkOf = (literal) => (literal.leaf ? exports.ACCESS_CHECKS[literal.leaf.type] : undefined);
154
+ function clausesOf(expr, positive = true) {
155
+ if (expr.kind === 'leaf')
156
+ return [[{ leaf: expr, positive }]];
157
+ if (expr.kind === 'raw')
158
+ return [[{ positive }]];
159
+ if (expr.kind === 'not')
160
+ return clausesOf(expr.arg, !positive);
161
+ const parts = expr.args.map((arg) => clausesOf(arg, positive));
162
+ if (parts.some((entry) => !entry))
163
+ return undefined;
164
+ let out;
165
+ if ((expr.kind === 'and') === positive) {
166
+ out = [[]];
167
+ for (const entry of parts) {
168
+ out = out.flatMap((clause) => entry.map((other) => [...clause, ...other]));
169
+ if (out.length > MAX_CLAUSES)
170
+ return undefined;
171
+ }
172
+ }
173
+ else {
174
+ out = parts.flat();
175
+ }
176
+ return out.length > MAX_CLAUSES ? undefined : out;
177
+ }
178
+ // The expression with each node its words may not fully state read as a part no Authz node describes, so that no
179
+ // finding rests on what those words say.
180
+ function readable(expr, related) {
181
+ if (expr.kind === 'leaf')
182
+ return (0, words_1.statesAll)(expr.type, expr.data, related) ? expr : { kind: 'raw' };
183
+ if (expr.kind === 'raw')
184
+ return expr;
185
+ if (expr.kind === 'not')
186
+ return { kind: 'not', arg: readable(expr.arg, related) };
187
+ return { kind: expr.kind, args: expr.args.map((arg) => readable(arg, related)) };
188
+ }
189
+ // A part no Authz node describes (a stored expression, a node the registry does not have), or a node its words may not
190
+ // fully state.
191
+ const unreadable = (literal) => !checkOf(literal);
192
+ // A part that limits who passes to people a known node names: a member, a named person or a share.
193
+ const namesKnownPeople = (literal) => literal.positive && ['member', 'named', 'shared'].includes(checkOf(literal)?.person);
194
+ // A literal that never holds: a check that lets no one in, or the negation of one that lets everyone in.
195
+ const never = (literal) => (literal.positive ? checkOf(literal)?.person === 'none' : checkOf(literal)?.always === true);
196
+ // The clauses that can hold; a tree too large to read gives none, so it fires nothing.
197
+ function clausesOfPart(item) {
198
+ return (clausesOf(item.expr) ?? []).filter((clause) => !clause.some(never));
199
+ }
200
+ // The literal limits who passes to people the rule names. A raw part or an unknown node counts as such a check, so that
201
+ // no finding rests on a guess.
202
+ function namesPeople(literal) {
203
+ const check = checkOf(literal);
204
+ if (!check)
205
+ return true;
206
+ return literal.positive && ['member', 'named', 'shared', 'mixed'].includes(check.person);
207
+ }
208
+ const memberOf = (literal, scopes) => literal.positive && checkOf(literal)?.person === 'member' && scopes.includes(checkOf(literal).scope);
209
+ function ownerIsRowId(literal) {
210
+ const owner = checkOf(literal)?.owner;
211
+ const column = owner ? literal.leaf.data[owner] : undefined;
212
+ const columns = Array.isArray(column) ? column : [column];
213
+ return columns.length > 0 && columns.every((name) => name === provisioning_1.ROW_ID);
214
+ }
215
+ // An owner check with no membership in it. An owner column named id means the row is the person.
216
+ const bareOwner = (literal) => literal.positive && Boolean(checkOf(literal)?.owner) && checkOf(literal).person !== 'member' && !ownerIsRowId(literal);
217
+ // A literal that admits people with no membership on purpose: row conditions, sessions, shares, listed people. A rule
218
+ // that lets everyone in with no check is not one: fencing it with a limit is how a table says "only these people".
219
+ function letsOutsidersIn(literal) {
220
+ const check = checkOf(literal);
221
+ if (!literal.positive || !check || check.always)
222
+ return false;
223
+ return ['anyone', 'session', 'shared'].includes(check.person) || (check.person === 'named' && !check.owner);
224
+ }
225
+ const permissiveClauses = (parts) => parts.filter(policies_1.lets).flatMap(clausesOfPart);
226
+ // A restrictive rule every clause of which meets `test` holds back everyone who fails it.
227
+ const fencedBy = (parts, test) => parts.some((item) => !(0, policies_1.lets)(item) && clausesOf(item.expr) !== undefined && clausesOfPart(item).every((clause) => clause.some(test)));
228
+ // Who passes is limited to people the rules name.
229
+ const limitsPeople = (parts) => permissiveClauses(parts).every((clause) => clause.some(namesPeople)) || fencedBy(parts, namesPeople);
230
+ function groups(parts, roles) {
231
+ return roles.map((role) => parts.filter((item) => (0, policies_1.appliesTo)(item, role)));
232
+ }
233
+ // ─── Columns the rules read ──────────────────────────────────────
234
+ // The columns an access rule's Data node adds, at their default names: entity_id, owner_id, is_published, ...
235
+ let accessColumns;
236
+ function accessColumnNames() {
237
+ accessColumns ??= new Set(Object.values(provisioning_1.TABLE_NEEDS).flatMap((need) => (need.data_node ? (0, provisioning_1.fieldsAddedByNodes)([need.data_node.type]).fields.map((field) => field.name) : [])));
238
+ return accessColumns;
239
+ }
240
+ const typeFits = (schema, value) => schema.type === undefined ||
241
+ [schema.type]
242
+ .flat()
243
+ .some((type) => (type === 'array' ? Array.isArray(value) : type === 'object' ? typeof value === 'object' && value !== null && !Array.isArray(value) : typeof value === type || (type === 'integer' && Number.isInteger(value))));
244
+ const join = (path, key) => (path ? `${path}.${key}` : String(key));
245
+ // The columns of this table a value reads under its schema: column parameters, other than another table's, nested
246
+ // expressions included. An object or a list of objects the schema does not describe could read any column.
247
+ function readValue(schema, value, path) {
248
+ const none = { columns: [], opaque: false, nested: [] };
249
+ if (value === undefined || value === null)
250
+ return none;
251
+ if (schema.format === 'authz-expression')
252
+ return { ...none, nested: [(0, policies_1.treeOf)(value)] };
253
+ // Alternative shapes of the value; an anyOf of required key groups constrains keys and is not one.
254
+ const shapes = (schema.anyOf ?? []).filter((entry) => entry.type !== undefined || entry.format !== undefined);
255
+ if (shapes.length) {
256
+ const branch = shapes.find((entry) => typeFits(entry, value));
257
+ return branch ? readValue(branch, value, path) : none;
258
+ }
259
+ if (schema.format === 'column-ref')
260
+ return typeof value === 'string' && schema['x-column-scope'] !== 'foreign' ? { ...none, columns: [{ param: path, column: value }] } : none;
261
+ const merge = (readings) => ({
262
+ columns: readings.flatMap((entry) => entry.columns),
263
+ opaque: readings.some((entry) => entry.opaque),
264
+ nested: readings.flatMap((entry) => entry.nested)
265
+ });
266
+ if (Array.isArray(value)) {
267
+ const items = !Array.isArray(schema.items) ? schema.items : undefined;
268
+ return items ? merge(value.map((item, i) => readValue(items, item, join(path, i)))) : { ...none, opaque: value.length > 0 };
269
+ }
270
+ if (typeof value === 'object') {
271
+ const record = value;
272
+ if (schema.properties) {
273
+ const described = merge(Object.entries(schema.properties).map(([key, inner]) => readValue(inner, record[key], join(path, key))));
274
+ const extra = Object.keys(record).some((key) => !schema.properties[key]);
275
+ return extra ? { ...described, opaque: true } : described;
276
+ }
277
+ return { ...none, opaque: Object.keys(record).length > 0 };
278
+ }
279
+ return none;
280
+ }
281
+ function readExpr(expr, owner, columns, unknown) {
282
+ if (expr.kind !== 'leaf') {
283
+ if (expr.kind === 'raw')
284
+ unknown.add(owner);
285
+ for (const arg of expr.kind === 'not' ? [expr.arg] : expr.kind === 'raw' ? [] : expr.args)
286
+ readExpr(arg, owner, columns, unknown);
287
+ return;
288
+ }
289
+ const node = policies_1.AUTHZ_NODES.get(expr.type);
290
+ if (!node) {
291
+ unknown.add(expr.type);
292
+ return;
293
+ }
294
+ const reading = readValue(node.parameter_schema, expr.data, '');
295
+ for (const { param, column } of reading.columns)
296
+ columns.push({ type: expr.type, param, column });
297
+ if (reading.opaque)
298
+ unknown.add(expr.type);
299
+ for (const nested of reading.nested)
300
+ readExpr(nested, expr.type, columns, unknown);
301
+ }
302
+ /**
303
+ * The columns of the table the rules read: each rule, its `with_check`, and the nodes nested in them, from the nodes'
304
+ * column parameters (registry defaults apply). `unknown` names the rule types with a part whose columns cannot be told:
305
+ * a stored raw expression, a type the registry does not have, or data its schema does not describe.
306
+ */
307
+ function columnsReadByPolicies(policies) {
308
+ const columns = [];
309
+ const unknown = new Set();
310
+ for (const policy of policies) {
311
+ for (const rule of [{ type: policy.type, data: policy.data }, ...(policy.with_check ? [policy.with_check] : [])]) {
312
+ const effective = (0, policies_1.effectivePolicy)(rule.type, rule.data ?? {});
313
+ readExpr((0, policies_1.exprOf)(effective.type, effective.data), rule.type, columns, unknown);
314
+ }
315
+ }
316
+ return { columns: (0, policies_1.unique)(columns, (entry) => JSON.stringify([entry.type, entry.param, entry.column])), unknown: [...unknown] };
317
+ }
318
+ // A required column with no default that an access rule's Data node adds, and that no rule of the table reads. When a
319
+ // part of the rules cannot be read, it may read the column, so nothing is reported.
320
+ function strandedColumns(input) {
321
+ if (!input.fields)
322
+ return [];
323
+ const { columns, unknown } = columnsReadByPolicies(input.policies);
324
+ if (unknown.length)
325
+ return [];
326
+ const read = new Set(columns.map((entry) => entry.column));
327
+ return input.fields.filter((field) => field.required && field.default === null && accessColumnNames().has(field.name) && !read.has(field.name)).map((field) => field.name);
328
+ }
329
+ /** What may be wrong with the rules of one table, by the shapes the backend docs warn about. */
330
+ function accessFindings(input) {
331
+ const readableParts = (parts) => parts.map((item) => ({ ...item, expr: readable(item.expr, input.related) }));
332
+ const partsOf = (privilege) => readableParts((0, policies_1.partsFor)(input.policies, privilege));
333
+ const all = readableParts(input.policies.map(policies_1.part));
334
+ const rlsOff = input.rls_enabled === false;
335
+ const literals = all.flatMap((item) => (clausesOf(item.expr) ?? []).flat());
336
+ // The membership nodes: no peer ownership, and no limit such as the read-only block.
337
+ const hasMember = literals.some((literal) => memberOf(literal, ['app', 'row']) && !checkOf(literal).limit);
338
+ const rowTeam = literals.some((literal) => memberOf(literal, ['row']));
339
+ // On a table of teams, only team membership fences an owner: an app member who left the team is still in the app.
340
+ const fence = (literal) => memberOf(literal, rowTeam ? ['row'] : ['app', 'row']);
341
+ const readParts = partsOf('select');
342
+ const roles = rolesOf(input, all);
343
+ const rules = {
344
+ 'owner-outlives-membership': (parts, operation) => hasMember &&
345
+ roles.some((role) => {
346
+ const mine = parts.filter((item) => (0, policies_1.appliesTo)(item, role));
347
+ const read = readParts.filter((item) => (0, policies_1.appliesTo)(item, role));
348
+ const open = permissiveClauses(mine).some((clause) => clause.some(bareOwner) && !clause.some(fence));
349
+ const readFenced = operation !== 'read' && (permissiveClauses(read).every((clause) => clause.some(fence)) || fencedBy(read, fence));
350
+ return open && !fencedBy(mine, fence) && !readFenced;
351
+ }),
352
+ 'app-membership-on-team-rows': (parts) => rowTeam &&
353
+ groups(parts, roles).some((mine) => {
354
+ const clauses = permissiveClauses(mine);
355
+ const app = clauses.some((clause) => clause.some((literal) => memberOf(literal, ['app']) && !checkOf(literal).owner));
356
+ return app && clauses.some((clause) => clause.some(bareOwner) && !clause.some((literal) => memberOf(literal, ['app', 'row'])));
357
+ }),
358
+ // No rule at all lets anyone do it: the database refuses it to every role.
359
+ 'granted-without-policy': (parts, operation) => Boolean(input.grants) && !rlsOff && !parts.some(policies_1.lets) && rolesOf(input, parts).some((role) => granted(input, role, policies_1.PRIVILEGE[operation])),
360
+ // A rule lets some role do it, but none names this granted role: a member of a role a rule names passes.
361
+ 'granted-role-without-policy': (parts, operation) => Boolean(input.grants) &&
362
+ !rlsOff &&
363
+ parts.some(policies_1.lets) &&
364
+ rolesOf(input, parts).some((role) => granted(input, role, policies_1.PRIVILEGE[operation]) && !parts.some((item) => (0, policies_1.appliesTo)(item, role) && (0, policies_1.lets)(item))),
365
+ 'policies-without-row-security': (parts) => rlsOff && parts.length > 0,
366
+ 'anyone-can-change': (parts, operation) => operation !== 'read' &&
367
+ !rlsOff &&
368
+ roles.some((role) => {
369
+ const mine = parts.filter((item) => (0, policies_1.appliesTo)(item, role));
370
+ const read = readParts.filter((item) => (0, policies_1.appliesTo)(item, role));
371
+ return mine.some(policies_1.lets) && granted(input, role, 'select') && !limitsPeople(mine) && !limitsPeople(read);
372
+ }),
373
+ 'limit-blocks-outside-grant': (parts) => groups(parts, roles).some((mine) => fencedBy(mine, (literal) => memberOf(literal, ['app', 'row', 'peer'])) &&
374
+ permissiveClauses(mine).some((clause) => !clause.some((literal) => memberOf(literal, ['app', 'row', 'peer'])) && clause.some(letsOutsidersIn))),
375
+ // A part the words may not state, in a permissive rule, in a clause with no part that names people: it can let anyone in.
376
+ // Under AND beside such a part it can only narrow; a restrictive rule can only narrow.
377
+ 'raw-part-may-widen': (parts) => parts.some((item) => (0, policies_1.lets)(item) && (clausesOf(item.expr) ?? []).some((clause) => !clause.some(never) && clause.some(unreadable) && !clause.some(namesKnownPeople))),
378
+ 'write-without-read': (parts, operation) => operation !== 'read' &&
379
+ !rlsOff &&
380
+ roles.some((role) => {
381
+ const mine = parts.filter((item) => (0, policies_1.appliesTo)(item, role));
382
+ if (!mine.some(policies_1.lets) || !granted(input, role, policies_1.PRIVILEGE[operation]))
383
+ return false;
384
+ if (!granted(input, role, 'select'))
385
+ return true;
386
+ return !limitsPeople(mine) && limitsPeople(readParts.filter((item) => (0, policies_1.appliesTo)(item, role)));
387
+ })
388
+ };
389
+ const findings = Object.entries(rules).flatMap(([id, fires]) => {
390
+ const operations = policies_1.OPERATIONS.filter((operation) => fires(partsOf(policies_1.PRIVILEGE[operation]), operation));
391
+ return operations.length ? [{ id, ...FINDINGS[id], operations }] : [];
392
+ });
393
+ const fields = readableFields(input.fields);
394
+ const stranded = strandedColumns({ ...input, fields });
395
+ if (stranded.length)
396
+ findings.push({ id: 'required-column-not-set', ...FINDINGS['required-column-not-set'], operations: ['create'], columns: stranded });
397
+ const gaps = fields ? columnGaps(fields, input.policies).filter(({ gaps: kinds }) => kinds.includes('type') || kinds.includes('default')) : [];
398
+ if (gaps.length) {
399
+ findings.push({
400
+ id: 'reused-column-differs',
401
+ ...FINDINGS['reused-column-differs'],
402
+ operations: gaps.some(({ gaps: kinds }) => kinds.includes('type')) ? policies_1.OPERATIONS : ['create'],
403
+ columns: gaps.map(({ column }) => column),
404
+ details: gaps.map(gapWords)
405
+ });
406
+ }
407
+ return findings;
408
+ }
409
+ const CURRENT_USER = { function: 'current_user_id', schema: 'jwt_public' };
410
+ // The default DataDirectOwner gives an owner column: the id of the person who makes the row.
411
+ const isCurrentUser = (value) => typeof value === 'object' && value !== null && 'function' in value && value.function === CURRENT_USER.function && value.schema === CURRENT_USER.schema;
412
+ function defaultWords(value) {
413
+ if (value === null || value === 'unknown')
414
+ return String(value);
415
+ if ('generated' in value)
416
+ return 'a value PostgreSQL computes';
417
+ if (isCurrentUser(value))
418
+ return 'the id of the person who makes the row';
419
+ if (value.function !== undefined)
420
+ return `${value.schema ? `${value.schema}.` : ''}${value.function}()`;
421
+ return `the value ${JSON.stringify(value.value)}`;
422
+ }
423
+ function gapWords({ column, node, expected, actual, gaps }) {
424
+ if (gaps.includes('type'))
425
+ return `${column} is ${actual.type}, and ${node} makes it ${expected.type}, so the rule cannot work on it.`;
426
+ if (actual.default === null)
427
+ return `${column} has no default, and ${node} gives it ${defaultWords(expected.default)}, so a create must send it itself.`;
428
+ if (expected.default === null && isCurrentUser(actual.default)) {
429
+ return `${column} defaults to the id of the person who makes the row, and ${node} gives it no default, so a row made without it names its maker.`;
430
+ }
431
+ if (expected.default === null)
432
+ return `${column} defaults to ${defaultWords(actual.default)}, and ${node} gives it no default, so a create that leaves it out gets that value.`;
433
+ return `${column} defaults to ${defaultWords(actual.default)}, and ${node} gives it ${defaultWords(expected.default)}.`;
434
+ }
@@ -0,0 +1,5 @@
1
+ export { ACCESS_CHECKS, type AccessCheck, type AccessFinding, accessFindings, type ColumnGap, columnGaps, type ColumnRead, columnsReadByPolicies, type TableAccessInput, type TableField } from './findings';
2
+ export { type AccessOperation, BUILT_IN_SCOPES, DERIVED_KEYS, type MembershipScope, policyDifference, type ResolvedPolicy, resolveEntityTypes, type RuleProblem, type TablePolicy, tablePolicyFromBlueprint, type TablePrivilege } from './policies';
3
+ export { ADDED_FIELDS, type AddedColumn, type AddedDefault, type AddedField, type ColumnDefault, type DataNodeNeed, dataNodesForPolicies, defaultFills, fieldsAddedByNodes, type NeededDataNode, ROW_ID, TABLE_NEEDS, type TableKind } from './provisioning';
4
+ export { checkRule, POLICY_ROLES } from './rule-check';
5
+ export { explainPolicy, POLICY_WORDS, type PolicyWordsTemplate } from './words';
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.POLICY_WORDS = exports.explainPolicy = exports.POLICY_ROLES = exports.checkRule = exports.TABLE_NEEDS = exports.ROW_ID = exports.fieldsAddedByNodes = exports.defaultFills = exports.dataNodesForPolicies = exports.ADDED_FIELDS = exports.tablePolicyFromBlueprint = exports.resolveEntityTypes = exports.policyDifference = exports.DERIVED_KEYS = exports.BUILT_IN_SCOPES = exports.columnsReadByPolicies = exports.columnGaps = exports.accessFindings = exports.ACCESS_CHECKS = void 0;
4
+ var findings_1 = require("./findings");
5
+ Object.defineProperty(exports, "ACCESS_CHECKS", { enumerable: true, get: function () { return findings_1.ACCESS_CHECKS; } });
6
+ Object.defineProperty(exports, "accessFindings", { enumerable: true, get: function () { return findings_1.accessFindings; } });
7
+ Object.defineProperty(exports, "columnGaps", { enumerable: true, get: function () { return findings_1.columnGaps; } });
8
+ Object.defineProperty(exports, "columnsReadByPolicies", { enumerable: true, get: function () { return findings_1.columnsReadByPolicies; } });
9
+ var policies_1 = require("./policies");
10
+ Object.defineProperty(exports, "BUILT_IN_SCOPES", { enumerable: true, get: function () { return policies_1.BUILT_IN_SCOPES; } });
11
+ Object.defineProperty(exports, "DERIVED_KEYS", { enumerable: true, get: function () { return policies_1.DERIVED_KEYS; } });
12
+ Object.defineProperty(exports, "policyDifference", { enumerable: true, get: function () { return policies_1.policyDifference; } });
13
+ Object.defineProperty(exports, "resolveEntityTypes", { enumerable: true, get: function () { return policies_1.resolveEntityTypes; } });
14
+ Object.defineProperty(exports, "tablePolicyFromBlueprint", { enumerable: true, get: function () { return policies_1.tablePolicyFromBlueprint; } });
15
+ var provisioning_1 = require("./provisioning");
16
+ Object.defineProperty(exports, "ADDED_FIELDS", { enumerable: true, get: function () { return provisioning_1.ADDED_FIELDS; } });
17
+ Object.defineProperty(exports, "dataNodesForPolicies", { enumerable: true, get: function () { return provisioning_1.dataNodesForPolicies; } });
18
+ Object.defineProperty(exports, "defaultFills", { enumerable: true, get: function () { return provisioning_1.defaultFills; } });
19
+ Object.defineProperty(exports, "fieldsAddedByNodes", { enumerable: true, get: function () { return provisioning_1.fieldsAddedByNodes; } });
20
+ Object.defineProperty(exports, "ROW_ID", { enumerable: true, get: function () { return provisioning_1.ROW_ID; } });
21
+ Object.defineProperty(exports, "TABLE_NEEDS", { enumerable: true, get: function () { return provisioning_1.TABLE_NEEDS; } });
22
+ var rule_check_1 = require("./rule-check");
23
+ Object.defineProperty(exports, "checkRule", { enumerable: true, get: function () { return rule_check_1.checkRule; } });
24
+ Object.defineProperty(exports, "POLICY_ROLES", { enumerable: true, get: function () { return rule_check_1.POLICY_ROLES; } });
25
+ var words_1 = require("./words");
26
+ Object.defineProperty(exports, "explainPolicy", { enumerable: true, get: function () { return words_1.explainPolicy; } });
27
+ Object.defineProperty(exports, "POLICY_WORDS", { enumerable: true, get: function () { return words_1.POLICY_WORDS; } });