@protobase/server 0.129.1 → 0.130.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 (253) hide show
  1. package/dist/assistant/query-runner/grants-sql.js +32 -0
  2. package/dist/assistant/query-runner/query-input.js +33 -0
  3. package/dist/assistant/query-runner/query-module.js +44 -0
  4. package/dist/assistant/query-runner/query-runner.d.ts +8 -11
  5. package/dist/assistant/query-runner/query-runner.js +15 -57
  6. package/dist/assistant/query-runner/read-query.js +54 -0
  7. package/dist/assistant/query-runner/runner-sql.js +4 -20
  8. package/dist/assistant/query-runner/steps/001-role.js +19 -0
  9. package/dist/auth-store.d.ts +2 -2
  10. package/dist/auth-store.js +3 -3
  11. package/dist/better-auth/auth-schema.d.ts +13 -4
  12. package/dist/better-auth/auth-schema.js +40 -32
  13. package/dist/better-auth/auth-settings.d.ts +59 -11
  14. package/dist/better-auth/auth-settings.js +57 -13
  15. package/dist/better-auth/auth-tables.d.ts +6 -3
  16. package/dist/better-auth/auth-tables.js +12 -7
  17. package/dist/better-auth/authenticator.js +10 -2
  18. package/dist/better-auth/create-auth.d.ts +62 -7
  19. package/dist/better-auth/create-auth.js +55 -14
  20. package/dist/better-auth/device-sign-in-check.js +13 -0
  21. package/dist/better-auth/names/declaration.d.ts +18 -5
  22. package/dist/better-auth/names/declaration.js +3 -1
  23. package/dist/better-auth/names/modules/auth.js +9 -0
  24. package/dist/better-auth/names/modules/index.d.ts +34 -4
  25. package/dist/better-auth/names/modules/organizations.js +10 -3
  26. package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
  27. package/dist/better-auth/names/modules-on.js +25 -2
  28. package/dist/better-auth/names/resolve-names.d.ts +9 -1
  29. package/dist/better-auth/names/resolve-names.js +15 -9
  30. package/dist/better-auth/organizations/accept-invitation.js +5 -4
  31. package/dist/better-auth/organizations/add-every-user.js +3 -2
  32. package/dist/better-auth/organizations/host-scope.d.ts +10 -0
  33. package/dist/better-auth/organizations/host-scope.js +15 -0
  34. package/dist/better-auth/organizations/host.d.ts +12 -6
  35. package/dist/better-auth/organizations/host.js +99 -61
  36. package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
  37. package/dist/better-auth/organizations/kept-organizations.js +62 -0
  38. package/dist/better-auth/organizations/member-endpoints.js +4 -3
  39. package/dist/better-auth/organizations/options.d.ts +15 -0
  40. package/dist/better-auth/organizations/options.js +19 -1
  41. package/dist/better-auth/organizations/people-endpoint.js +3 -2
  42. package/dist/better-auth/organizations/pinned-membership.js +81 -0
  43. package/dist/better-auth/organizations/pinned-sessions.js +46 -0
  44. package/dist/better-auth/organizations/session-organization.js +3 -2
  45. package/dist/better-auth/organizations/store.d.ts +1 -1
  46. package/dist/better-auth/organizations/store.js +14 -9
  47. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  48. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  49. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  50. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  51. package/dist/better-auth/store/adoption.js +25 -10
  52. package/dist/better-auth/store/drift.js +5 -4
  53. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  54. package/dist/better-auth/store/legacy-record.js +56 -0
  55. package/dist/better-auth/store/migration-sql.js +31 -26
  56. package/dist/better-auth/store/offline/archive-revival.d.ts +11 -0
  57. package/dist/better-auth/store/offline/archive-revival.js +25 -0
  58. package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
  59. package/dist/better-auth/store/offline/baseline-store.js +15 -12
  60. package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
  61. package/dist/better-auth/store/offline/contract-gate.js +35 -0
  62. package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
  63. package/dist/better-auth/store/offline/module-archive.js +95 -0
  64. package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
  65. package/dist/better-auth/store/offline/module-delete.js +99 -0
  66. package/dist/better-auth/store/offline/module-switches.d.ts +32 -0
  67. package/dist/better-auth/store/offline/module-switches.js +113 -0
  68. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  69. package/dist/better-auth/store/offline/name-changes.js +5 -2
  70. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -7
  71. package/dist/better-auth/store/offline/offline-steps.js +29 -20
  72. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  73. package/dist/better-auth/store/offline/retired-watch.js +43 -0
  74. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  75. package/dist/better-auth/store/offline/settings-names.js +10 -3
  76. package/dist/better-auth/store/offline/store-model.d.ts +27 -1
  77. package/dist/better-auth/store/offline/store-model.js +22 -5
  78. package/dist/better-auth/store/resources-outside.js +1 -1
  79. package/dist/better-auth/store/step-record.d.ts +13 -0
  80. package/dist/better-auth/store/step-record.js +59 -0
  81. package/dist/better-auth/store/steps/index.js +6 -1
  82. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  83. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  84. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  85. package/dist/better-auth/store/steps/render.d.ts +3 -0
  86. package/dist/better-auth/store/steps/render.js +48 -25
  87. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  88. package/dist/better-auth/store/steps/step-lint.js +31 -10
  89. package/dist/better-auth/store/steps/step.d.ts +18 -0
  90. package/dist/better-auth/store/steps/step.js +7 -1
  91. package/dist/better-auth/store/store-db.d.ts +6 -0
  92. package/dist/better-auth/store/store-db.js +11 -5
  93. package/dist/better-auth/store/store-names.d.ts +4 -0
  94. package/dist/better-auth/store/store-sql.d.ts +1 -1
  95. package/dist/better-auth/token-standing.js +12 -7
  96. package/dist/better-auth/users.d.ts +7 -2
  97. package/dist/better-auth/users.js +25 -3
  98. package/dist/built-in-resources.js +1 -1
  99. package/dist/calls/calls-module.js +42 -0
  100. package/dist/calls/calls-sql.js +4 -30
  101. package/dist/changes/capture-names.d.ts +3 -1
  102. package/dist/changes/capture-names.js +5 -2
  103. package/dist/changes/capture-schema-sql.d.ts +10 -0
  104. package/dist/changes/capture-schema-sql.js +21 -0
  105. package/dist/changes/capture-schema.d.ts +0 -18
  106. package/dist/changes/capture-schema.js +1 -74
  107. package/dist/changes/capture-sql.js +30 -24
  108. package/dist/changes/changes-input.js +36 -0
  109. package/dist/changes/changes-module.js +44 -0
  110. package/dist/changes/read-capture.js +67 -0
  111. package/dist/changes/steps/001-outbox.js +23 -0
  112. package/dist/channels/sends-module.js +37 -0
  113. package/dist/channels/sends-schema-sql.js +5 -5
  114. package/dist/comments/comments-module.js +30 -0
  115. package/dist/comments/comments-sql.js +1 -22
  116. package/dist/computed/buckets-sql.d.ts +5 -1
  117. package/dist/computed/buckets-sql.js +39 -46
  118. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  119. package/dist/computed/buckets-targets.js +50 -0
  120. package/dist/computed/computed-input.js +65 -0
  121. package/dist/computed/computed-module.js +102 -0
  122. package/dist/computed/formula-sql.js +14 -1
  123. package/dist/computed/read-computed.js +100 -0
  124. package/dist/computed/rollup-sql.js +13 -10
  125. package/dist/config-exports.d.ts +2 -2
  126. package/dist/create-admin.js +21 -5
  127. package/dist/derived/derived-module.js +89 -0
  128. package/dist/derived/derived-sql.js +1 -47
  129. package/dist/functions/define-function.d.ts +10 -4
  130. package/dist/functions/routes.js +5 -3
  131. package/dist/functions/supabase-routes.js +7 -5
  132. package/dist/history/history-module.js +34 -0
  133. package/dist/index.d.ts +19 -28
  134. package/dist/index.js +11 -21
  135. package/dist/internal.d.ts +30 -10
  136. package/dist/internal.js +26 -8
  137. package/dist/jobs/functions-sql.js +7 -11
  138. package/dist/jobs/job-data.js +36 -0
  139. package/dist/jobs/job-types.d.ts +6 -3
  140. package/dist/jobs/jobs-module.d.ts +5 -0
  141. package/dist/jobs/jobs-module.js +84 -0
  142. package/dist/jobs/run-job.d.ts +1 -1
  143. package/dist/jobs/run-job.js +7 -5
  144. package/dist/jobs/runtime.d.ts +9 -4
  145. package/dist/jobs/runtime.js +11 -6
  146. package/dist/jobs/schema.d.ts +0 -11
  147. package/dist/jobs/schema.js +1 -59
  148. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  149. package/dist/live/notices-module.js +30 -0
  150. package/dist/live/notices-sql.js +2 -1
  151. package/dist/mail/feedback/feedback-schema.js +3 -30
  152. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  153. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  154. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  155. package/dist/migration-record/check-record.d.ts +9 -7
  156. package/dist/migration-record/check-record.js +12 -11
  157. package/dist/migration-record/module-needs.js +30 -0
  158. package/dist/migration-record/read-record.js +27 -15
  159. package/dist/migration-record/record-model.d.ts +7 -2
  160. package/dist/migration-record/record-model.js +14 -6
  161. package/dist/migration-record/startup-decision.js +18 -7
  162. package/dist/migration-sql/additive-statements.d.ts +4 -0
  163. package/dist/migration-sql/additive-statements.js +105 -0
  164. package/dist/notifications/devices-module.js +61 -0
  165. package/dist/notifications/history-module.js +50 -0
  166. package/dist/notifications/notifications-targets.js +23 -0
  167. package/dist/notifications/read-table.js +16 -0
  168. package/dist/notifications/schema-sql.js +1 -22
  169. package/dist/notifications/schema.js +1 -101
  170. package/dist/notifications/table-names.js +40 -0
  171. package/dist/organization-scope/app-scope.js +38 -0
  172. package/dist/organization-scope/auth-request-organization.js +71 -0
  173. package/dist/organization-scope/organization-tables.js +20 -0
  174. package/dist/organization-scope/sign-in-organization.js +21 -0
  175. package/dist/package.js +1 -1
  176. package/dist/personal-mail/shared-sender-store.js +4 -2
  177. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  178. package/dist/relation-found.js +6 -0
  179. package/dist/relay/read-relay.js +85 -0
  180. package/dist/relay/realtime-members-sql.js +51 -28
  181. package/dist/relay/relay-module.js +53 -0
  182. package/dist/relay/relay-targets.js +28 -0
  183. package/dist/relay/session-end.js +1 -3
  184. package/dist/relay/sessions-sql.js +4 -27
  185. package/dist/rest/table-routes.js +9 -2
  186. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  187. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  188. package/dist/schema-modules/module-difference.d.ts +31 -0
  189. package/dist/schema-modules/module-difference.js +98 -0
  190. package/dist/schema-modules/modules-sql.js +13 -0
  191. package/dist/schema-modules/modules.d.ts +37 -0
  192. package/dist/schema-modules/modules.js +56 -0
  193. package/dist/schema-modules/needed-modules.d.ts +41 -0
  194. package/dist/schema-modules/needed-modules.js +61 -0
  195. package/dist/schema-modules/resource-difference.js +83 -0
  196. package/dist/schema-modules/schema-module.d.ts +112 -0
  197. package/dist/schema-modules/schema-module.js +8 -0
  198. package/dist/status/status-module.js +63 -0
  199. package/dist/status/status-targets.js +21 -0
  200. package/dist/types.d.ts +6 -1
  201. package/dist/user-tables/reloading-admin.d.ts +1 -0
  202. package/dist/user-tables/reloading-admin.js +1 -0
  203. package/dist/user-tables/schema-sql.js +1 -14
  204. package/dist/user-tables/schema.js +4 -27
  205. package/dist/user-tables/user-tables-module.js +38 -0
  206. package/dist/webhooks/table/delivery-log-module.js +36 -0
  207. package/dist/webhooks/table/owner-roles.js +3 -2
  208. package/dist/webhooks/table/schema-sql.js +27 -26
  209. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  210. package/dist/webhooks/table/webhooks-targets.js +26 -0
  211. package/dist/webhooks/webhooks.js +1 -1
  212. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  213. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  214. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  215. package/dist/workflows/read-catalogue.js +23 -0
  216. package/dist/workflows/schema-sql.js +12 -9
  217. package/dist/workflows/status-sql.js +12 -6
  218. package/dist/workflows/storage/storage-module.js +39 -0
  219. package/dist/workflows/storage/storage-sql.js +8 -5
  220. package/dist/workflows/workflows-schema-module.js +49 -0
  221. package/dist/workflows/workflows-tables-sql.js +32 -0
  222. package/dist/workflows/workflows-targets.js +16 -0
  223. package/package.json +6 -6
  224. package/dist/assistant/query-runner/runner-plan.js +0 -30
  225. package/dist/better-auth/store/migrations-table.js +0 -27
  226. package/dist/better-auth/store/modules-off.js +0 -17
  227. package/dist/calls/calls-sql.d.ts +0 -11
  228. package/dist/changes/capture-plan.js +0 -79
  229. package/dist/channels/sends-schema.d.ts +0 -7
  230. package/dist/channels/sends-schema.js +0 -18
  231. package/dist/comments/comments-sql.d.ts +0 -14
  232. package/dist/computed/buckets-plan.d.ts +0 -2
  233. package/dist/computed/buckets-plan.js +0 -88
  234. package/dist/computed/buckets-schema.js +0 -39
  235. package/dist/computed/computed-plan.js +0 -81
  236. package/dist/computed/computed-schema.d.ts +0 -16
  237. package/dist/computed/computed-schema.js +0 -63
  238. package/dist/derived/derived-sql.d.ts +0 -12
  239. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  240. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  241. package/dist/notifications/schema.d.ts +0 -14
  242. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  243. package/dist/realtime/relay/relay-schema.js +0 -20
  244. package/dist/relay/realtime-members-schema.js +0 -67
  245. package/dist/relay/relay-schema.d.ts +0 -14
  246. package/dist/relay/relay-schema.js +0 -28
  247. package/dist/status/schema.d.ts +0 -12
  248. package/dist/status/schema.js +0 -33
  249. package/dist/user-tables/schema.d.ts +0 -11
  250. package/dist/webhooks/table/schema.d.ts +0 -16
  251. package/dist/webhooks/table/schema.js +0 -56
  252. package/dist/workflows/schema.d.ts +0 -13
  253. package/dist/workflows/schema.js +0 -88
@@ -0,0 +1,32 @@
1
+ import { queryRoleSql } from "./runner-sql.js";
2
+ //#region src/assistant/query-runner/grants-sql.ts
3
+ const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
4
+ const literal = (text) => `'${text.replaceAll("'", "''")}'`;
5
+ /** A table as `to_regclass` takes it: the search path decides when it names no schema. */
6
+ const regclassText = ({ schema, name }) => schema ? `${quoted(schema)}.${quoted(name)}` : quoted(name);
7
+ const overTable = (table, declarations, body) => [
8
+ "do $$",
9
+ "declare",
10
+ ` query_role text := ${queryRoleSql};`,
11
+ ` found regclass := to_regclass(${literal(regclassText(table))});`,
12
+ ...declarations,
13
+ "begin",
14
+ " if found is null then return; end if;",
15
+ ...body,
16
+ "end $$;"
17
+ ].join("\n");
18
+ /** Gives the query role select on `table` and usage on its schema; nothing while the table does not exist. */
19
+ const grantsSql = (table) => overTable(table, [], [" execute format('grant usage on schema %s to %I', (select relnamespace::regnamespace from pg_class where oid = found), query_role);", " execute format('grant select on table %s to %I', found, query_role);"]);
20
+ const held = (acl, privilege) => `exists (select from aclexplode(${acl}) a where a.grantee = (select oid from pg_roles where rolname = query_role) and a.privilege_type = '${privilege}')`;
21
+ /**
22
+ * Takes select on `table` back from the query role, and usage on its schema once the role reads no other table there;
23
+ * usage it does not hold itself is left alone, such as on a schema only its owner may grant on.
24
+ */
25
+ const revokeSql = (table) => overTable(table, [" found_schema regnamespace;"], [
26
+ " select relnamespace into found_schema from pg_class where oid = found;",
27
+ " execute format('revoke select on table %s from %I', found, query_role);",
28
+ ` if exists (select from pg_class c where c.relnamespace = found_schema and ${held("c.relacl", "SELECT")}) or not ${held("(select nspacl from pg_namespace where oid = found_schema)", "USAGE")} then return; end if;`,
29
+ " execute format('revoke usage on schema %s from %I', found_schema, query_role);"
30
+ ]);
31
+ //#endregion
32
+ export { grantsSql, regclassText, revokeSql };
@@ -0,0 +1,33 @@
1
+ import { storeAuthTables } from "../../better-auth/auth-tables.js";
2
+ //#region src/assistant/query-runner/query-input.ts
3
+ const same = (a, b) => a.name === b.name && (a.schema ?? "public") === (b.schema ?? "public");
4
+ /**
5
+ * What the query module takes from the app: each resource's table the role reads, by resource, but a table of the auth
6
+ * store `store` names or of one of its guarded schemas, and a table an earlier resource has already, so taking one
7
+ * resource's grants back never takes another's.
8
+ */
9
+ const queryInput = (models, store) => {
10
+ const guarded = store ? storeAuthTables(store) : {
11
+ tables: [],
12
+ schemas: []
13
+ };
14
+ const grants = {};
15
+ for (const model of models) {
16
+ const table = {
17
+ ...model.table.schema !== void 0 && { schema: model.table.schema },
18
+ name: model.table.name
19
+ };
20
+ if (table.schema !== void 0 && guarded.schemas.includes(table.schema)) continue;
21
+ if (guarded.tables.some((auth) => same(auth, table)) || Object.values(grants).some((given) => same(given.table, table))) continue;
22
+ grants[model.name] = {
23
+ table,
24
+ input: table
25
+ };
26
+ }
27
+ return {
28
+ names: {},
29
+ resources: { grants }
30
+ };
31
+ };
32
+ //#endregion
33
+ export { queryInput };
@@ -0,0 +1,44 @@
1
+ import { runnerSql } from "./runner-sql.js";
2
+ import { grantsSql, revokeSql } from "./grants-sql.js";
3
+ import { readQuery } from "./read-query.js";
4
+ import { roleStep } from "./steps/001-role.js";
5
+ //#region src/assistant/query-runner/query-module.ts
6
+ /**
7
+ * The query role's select on one resource's table and usage on its schema. Taken back once the resource is gone,
8
+ * leaving usage on the schema while the role reads another table there.
9
+ */
10
+ const grants = {
11
+ name: "grants",
12
+ title: "The grants of the query role",
13
+ version: 1,
14
+ compatibleFrom: 1,
15
+ sql: (_names, input) => grantsSql(input),
16
+ drop: (_names, table) => revokeSql(table),
17
+ keptWhileOthers: false
18
+ };
19
+ /**
20
+ * The role the built-in assistant's read-only queries run as, `<database>_query`, which reads only the resources'
21
+ * tables (`queryInput`), and `query.run_read_only`, the runner every query goes through as that role.
22
+ */
23
+ const queryModule = {
24
+ label: "the query role of the assistant's read-only queries",
25
+ title: "The role the assistant's read-only queries run as, which reads only the resources' tables",
26
+ steps: [{
27
+ step: 1,
28
+ name: "role",
29
+ title: "The query role",
30
+ additive: true,
31
+ sql: roleStep
32
+ }],
33
+ replaceables: [{
34
+ name: "runner",
35
+ title: "The runner the queries go through, query.run_read_only()",
36
+ version: 1,
37
+ compatibleFrom: 1,
38
+ sql: runnerSql
39
+ }],
40
+ resourceReplaceables: [grants],
41
+ read: readQuery(grants)
42
+ };
43
+ //#endregion
44
+ export { queryModule };
@@ -1,4 +1,3 @@
1
- import { ResourceModel } from "@protobase/schema";
2
1
  import { Db } from "@protobase/query";
3
2
  //#region src/assistant/query-runner/query-runner.d.ts
4
3
  /** A table as config names it: the search path decides when it names no schema. */
@@ -12,15 +11,13 @@ export type GuardedTables = {
12
11
  schemas: readonly string[];
13
12
  };
14
13
  /**
15
- * The SQL that makes the role the assistant's read-only queries run as, and its runner, and grants it exactly the
16
- * resources' tables, never an auth table; `undefined` when the database is current.
14
+ * Refuses to go on while the runner of the assistant's read-only queries, which the record of migrations says is there,
15
+ * does not run as a role weaker than the app's: it is no security definer, or runs as the app's role itself or one it
16
+ * is a member of, a superuser, a login role, or one that can read an auth table, or while that role may call a
17
+ * security-definer function that runs as a role able to read one. A migration cannot promise these: they are the live
18
+ * database's, such as a grant made by hand. It checks the owner's privileges, not its name, so a database cloned under
19
+ * another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its
20
+ * table until then.
17
21
  */
18
- export declare const queryRunnerMigration: (db: Db, models: readonly ResourceModel[], authTables: GuardedTables) => Promise<string | undefined>;
19
- /**
20
- * Refuses to go on while the runner of the assistant's read-only queries is missing or out of date, or runs as a role
21
- * that is not weaker than the app's: the app's role itself or one it is a member of, a superuser, a login role, or one
22
- * that can read an auth table, or while the role may call a security-definer function that runs as a role able to
23
- * read one. It checks the owner's privileges, not its name, so a database cloned under another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its table until then.
24
- */
25
- export declare const checkQueryRunner: (db: Db, authTables: GuardedTables) => Promise<void>;
22
+ export declare const checkQueryRoleSafety: (db: Db, authTables: GuardedTables) => Promise<void>;
26
23
  //#endregion
@@ -1,57 +1,11 @@
1
- import { modelVariables } from "../model-settings.js";
2
- import { migrationCommand } from "../../jobs/schema.js";
3
- import { queryRoleSql, queryRunnerSignature, queryRunnerSql, runnerBody } from "./runner-sql.js";
4
- import { plannedGrants } from "./runner-plan.js";
1
+ import { queryRunnerSignature } from "./runner-sql.js";
2
+ import { regclassText } from "./grants-sql.js";
5
3
  import { sql } from "kysely";
6
4
  //#region src/assistant/query-runner/query-runner.ts
7
- const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
8
- const regclassText = ({ schema, name }) => schema ? `${quoted(schema)}.${quoted(name)}` : quoted(name);
9
- const roleSql = sql.raw(queryRoleSql);
10
5
  const rowsOf = async (db, query) => (await query.execute(db)).rows;
11
6
  const guardedRelations = ({ tables, schemas }) => sql`select c.oid, c.relnamespace from pg_class c join pg_namespace n on n.oid = c.relnamespace
12
7
  where c.oid in (select to_regclass(t.name) from unnest(${tables.map(regclassText)}::text[]) as t(name)) or n.nspname = any(${[...schemas]}::text[])`;
13
- const resolved = (db, tables) => rowsOf(db, sql`select n.nspname as schema, c.relname as name from unnest(${tables.map(regclassText)}::text[]) with ordinality as t(name, n)
14
- join pg_class c on c.oid = to_regclass(t.name) join pg_namespace n on n.oid = c.relnamespace order by t.n`);
15
- const readRunner = async (db) => {
16
- const [runner] = await rowsOf(db, sql`select p.prosrc as source, p.prosecdef as definer, pg_get_userbyid(p.proowner) as owner,
17
- (p.proacl is null or exists (select from aclexplode(p.proacl) a where a.grantee = 0 and a.privilege_type = 'EXECUTE')) as executable
18
- from pg_proc p where p.oid = to_regprocedure(${queryRunnerSignature})`);
19
- return runner;
20
- };
21
- /** What the database holds of the query role and its runner, and the tables the role should read and must not. Only reads the catalogue. */
22
- const readQueryRunner = async (db, models, authTables) => {
23
- const [role] = await rowsOf(db, sql`select ${roleSql} as name, exists (select from pg_roles where rolname = ${roleSql}) as exists`);
24
- const tables = await rowsOf(db, sql`select n.nspname as schema, c.relname as name from pg_class c join pg_namespace n on n.oid = c.relnamespace, aclexplode(c.relacl) a
25
- where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'SELECT' order by 1, 2`);
26
- const schemas = await rowsOf(db, sql`select n.nspname as schema from pg_namespace n, aclexplode(n.nspacl) a
27
- where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'USAGE' order by 1`);
28
- return {
29
- role,
30
- runner: await readRunner(db),
31
- resources: await resolved(db, models.map((model) => model.table)),
32
- authTables: await resolved(db, authTables.tables),
33
- guardedSchemas: [...authTables.schemas],
34
- granted: {
35
- tables,
36
- schemas: schemas.map((found) => found.schema)
37
- }
38
- };
39
- };
40
- /**
41
- * The SQL that makes the role the assistant's read-only queries run as, and its runner, and grants it exactly the
42
- * resources' tables, never an auth table; `undefined` when the database is current.
43
- */
44
- const queryRunnerMigration = async (db, models, authTables) => {
45
- const { role, runner, resources, authTables: auth, guardedSchemas, granted } = await readQueryRunner(db, models, authTables);
46
- const plan = plannedGrants({
47
- resources,
48
- authTables: auth,
49
- guardedSchemas,
50
- granted
51
- });
52
- return role.exists && runner?.source === runnerBody && runner.definer && runner.owner === role.name && !runner.executable && plan.grants.length === 0 && plan.revokes.length === 0 ? void 0 : queryRunnerSql(plan);
53
- };
54
- const refusal = (state) => /* @__PURE__ */ new Error(`The query role of the assistant's read-only queries ${state}. Write it as a migration with \`${migrationCommand}\`, run with the built-in assistant's key set (${modelVariables.apiKey} or options.assistant.apiKey), apply it with the project's migrations, then start again.`);
8
+ const refusal = (state) => /* @__PURE__ */ new Error(`The query role of the assistant's read-only queries ${state}. Take back by hand what it was given, then start again.`);
55
9
  const leakingFunctions = (db, authTables) => rowsOf(db, sql`with runner as (select proowner as role from pg_proc where oid = to_regprocedure(${queryRunnerSignature}))
56
10
  select format('%I.%I(%s)', n.nspname, p.proname, pg_get_function_identity_arguments(p.oid)) as name
57
11
  from pg_proc p join pg_namespace n on n.oid = p.pronamespace, runner
@@ -61,18 +15,22 @@ const leakingFunctions = (db, authTables) => rowsOf(db, sql`with runner as (sele
61
15
  where has_schema_privilege(p.proowner, c.relnamespace, 'USAGE') and has_any_column_privilege(p.proowner, c.oid, 'SELECT'))
62
16
  order by 1`);
63
17
  /**
64
- * Refuses to go on while the runner of the assistant's read-only queries is missing or out of date, or runs as a role
65
- * that is not weaker than the app's: the app's role itself or one it is a member of, a superuser, a login role, or one
66
- * that can read an auth table, or while the role may call a security-definer function that runs as a role able to
67
- * read one. It checks the owner's privileges, not its name, so a database cloned under another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its table until then.
18
+ * Refuses to go on while the runner of the assistant's read-only queries, which the record of migrations says is there,
19
+ * does not run as a role weaker than the app's: it is no security definer, or runs as the app's role itself or one it
20
+ * is a member of, a superuser, a login role, or one that can read an auth table, or while that role may call a
21
+ * security-definer function that runs as a role able to read one. A migration cannot promise these: they are the live
22
+ * database's, such as a grant made by hand. It checks the owner's privileges, not its name, so a database cloned under
23
+ * another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its
24
+ * table until then.
68
25
  */
69
- const checkQueryRunner = async (db, authTables) => {
70
- const [runner] = await rowsOf(db, sql`select p.prosrc as source, p.prosecdef as definer,
26
+ const checkQueryRoleSafety = async (db, authTables) => {
27
+ const [runner] = await rowsOf(db, sql`select p.prosecdef as definer,
71
28
  (o.rolsuper or o.rolcanlogin or pg_has_role(p.proowner, current_user, 'MEMBER')) as strong,
72
29
  exists (select from (${guardedRelations(authTables)}) c
73
30
  where has_schema_privilege(p.proowner, c.relnamespace, 'USAGE') and has_any_column_privilege(p.proowner, c.oid, 'SELECT')) as reads_auth
74
31
  from pg_proc p join pg_roles o on o.oid = p.proowner where p.oid = to_regprocedure(${queryRunnerSignature})`);
75
- if (!runner || !runner.definer || runner.source !== runnerBody) throw refusal("is missing");
32
+ if (!runner) return;
33
+ if (!runner.definer) throw refusal(`is not what ${queryRunnerSignature} runs as: it is no security definer`);
76
34
  if (runner.strong) throw refusal("is not weaker than the app's database role");
77
35
  if (runner.reads_auth) throw refusal("can read the auth schema");
78
36
  const leaking = await leakingFunctions(db, authTables);
@@ -80,4 +38,4 @@ const checkQueryRunner = async (db, authTables) => {
80
38
  throw new Error(`The query role of the assistant's read-only queries can read the auth schema through the security-definer functions ${leaking.map((found) => found.name).join(", ")}. Revoke execute on them from PUBLIC, or move them to a schema without a resource, then start again.`);
81
39
  };
82
40
  //#endregion
83
- export { checkQueryRunner, queryRunnerMigration, readQueryRunner };
41
+ export { checkQueryRoleSafety };
@@ -0,0 +1,54 @@
1
+ import { queryRoleSql, queryRunnerSchema, queryRunnerSignature, runnerBody } from "./runner-sql.js";
2
+ import { resourceEntry } from "../../schema-modules/resource-difference.js";
3
+ import { regclassText } from "./grants-sql.js";
4
+ import { sql } from "kysely";
5
+ //#region src/assistant/query-runner/read-query.ts
6
+ const roleSql = sql.raw(queryRoleSql);
7
+ const rowsOf = async (db, query) => (await query.execute(db)).rows;
8
+ const same = (a, b) => a.schema === b.schema && a.name === b.name;
9
+ /**
10
+ * The query module as the database has it for `input`: step 1 once the role and the runner's schema are there, the
11
+ * runner at version 1 when it is this version's, run as the role and not executable by PUBLIC, each resource whose
12
+ * table the role reads, at no digest when it lacks usage on the table's schema, so its grants are written again; and
13
+ * each table the role reads that no resource has, by its name, so they are taken back. Nothing without the role.
14
+ */
15
+ const readQuery = (grants) => async (db, input) => {
16
+ const [role] = await rowsOf(db, sql`select ${roleSql} as name, exists (select from pg_roles where rolname = ${roleSql}) as exists, to_regnamespace(${queryRunnerSchema}) is not null as schema`);
17
+ if (!role.exists) return;
18
+ const [runner] = await rowsOf(db, sql`select p.prosrc as source, p.prosecdef as definer, pg_get_userbyid(p.proowner) as owner,
19
+ (p.proacl is null or exists (select from aclexplode(p.proacl) a where a.grantee = 0 and a.privilege_type = 'EXECUTE')) as executable
20
+ from pg_proc p where p.oid = to_regprocedure(${queryRunnerSignature})`);
21
+ const granted = await rowsOf(db, sql`select n.nspname as schema, c.relname as name from pg_class c join pg_namespace n on n.oid = c.relnamespace, aclexplode(c.relacl) a
22
+ where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'SELECT' order by 1, 2`);
23
+ const usage = (await rowsOf(db, sql`select n.nspname as schema from pg_namespace n, aclexplode(n.nspacl) a
24
+ where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'USAGE'`)).map((found) => found.schema);
25
+ const given = Object.entries(input.resources[grants.name] ?? {});
26
+ const resolved = await rowsOf(db, sql`select n.nspname as schema, c.relname as name from unnest(${given.map(([, one]) => regclassText(one.table))}::text[]) with ordinality as t(name, place)
27
+ left join pg_class c on c.oid = to_regclass(t.name) left join pg_namespace n on n.oid = c.relnamespace order by t.place`);
28
+ const entries = {};
29
+ given.forEach(([key, one], i) => {
30
+ const table = resolved[i];
31
+ if (table.schema === null || table.name === null || !granted.some((found) => same(found, table))) return;
32
+ const entry = resourceEntry(grants, input.names, one);
33
+ entries[key] = usage.includes(table.schema) ? entry : {
34
+ ...entry,
35
+ digest: ""
36
+ };
37
+ });
38
+ for (const found of granted) {
39
+ if (resolved.some((table) => table.schema !== null && same(found, table))) continue;
40
+ entries[`${found.schema}.${found.name}`] = {
41
+ version: grants.version,
42
+ digest: "",
43
+ table: found
44
+ };
45
+ }
46
+ const current = runner?.source === runnerBody && runner.definer && runner.owner === role.name && !runner.executable;
47
+ return {
48
+ lastStep: role.schema ? 1 : 0,
49
+ replaceables: current ? { runner: 1 } : {},
50
+ ...Object.keys(entries).length > 0 && { resources: { [grants.name]: entries } }
51
+ };
52
+ };
53
+ //#endregion
54
+ export { readQuery };
@@ -30,27 +30,11 @@ begin
30
30
  close rows;
31
31
  end
32
32
  `;
33
- const literal = (text) => `'${text.replaceAll("'", "''")}'`;
34
- const grantSql = ({ grants, revokes }) => [...grants.map((grant) => grant.on === "schema" ? ` execute format('grant usage on schema %I to %I', ${literal(grant.schema)}, query_role);` : ` execute format('grant select on table %I.%I to %I', ${literal(grant.schema)}, ${literal(grant.name)}, query_role);`), ...revokes.map((revoke) => revoke.on === "schema" ? ` execute format('revoke usage on schema %I from %I', ${literal(revoke.schema)}, query_role);` : ` execute format('revoke select on table %I.%I from %I', ${literal(revoke.schema)}, ${literal(revoke.name)}, query_role);`)];
35
33
  /**
36
- * The SQL that makes the query role and the runner, and gives the role exactly `grants`, taking back `revokes`. It
37
- * applies again on a database that has them. The migrating role becomes a member of the role, which Postgres 16 needs
38
- * to hand it the function, and so may execute the runner; PUBLIC may not. The role bypasses row-level security only
39
- * when the migrating role may give it that: a superuser, or a role with BYPASSRLS on Postgres 16 or later.
34
+ * The runner, made again and handed to the query role, which it runs every statement as; the migrating role, a member
35
+ * of the role, may execute it, PUBLIC may not.
40
36
  */
41
- const queryRunnerSql = (plan) => [
42
- `create schema if not exists ${queryRunnerSchema};`,
43
- [
44
- "do $$",
45
- "declare",
46
- ` query_role text := ${queryRoleSql};`,
47
- "begin",
48
- " if not exists (select from pg_roles where rolname = query_role) then execute format('create role %I nologin', query_role); end if;",
49
- " execute format('grant %I to current_user', query_role);",
50
- " if (select rolsuper or (rolbypassrls and current_setting('server_version_num')::int >= 160000) from pg_roles where rolname = current_user) then execute format('alter role %I bypassrls', query_role); end if;",
51
- ...grantSql(plan),
52
- "end $$;"
53
- ].join("\n"),
37
+ const runnerSql = () => [
54
38
  `create or replace function ${queryRunnerFunction}(statement text, row_limit integer) returns setof json language plpgsql security definer as $f$${runnerBody}$f$;`,
55
39
  [
56
40
  "do $$",
@@ -65,4 +49,4 @@ const queryRunnerSql = (plan) => [
65
49
  `revoke execute on function ${queryRunnerSignature} from public;`
66
50
  ].join("\n\n");
67
51
  //#endregion
68
- export { queryRoleSql, queryRunnerFunction, queryRunnerSchema, queryRunnerSignature, queryRunnerSql, runnerBody };
52
+ export { queryRoleSql, queryRunnerFunction, queryRunnerSchema, queryRunnerSignature, runnerBody, runnerSql };
@@ -0,0 +1,19 @@
1
+ import { queryRoleSql, queryRunnerSchema } from "../runner-sql.js";
2
+ //#region src/assistant/query-runner/steps/001-role.ts
3
+ /**
4
+ * The runner's schema and the role the read-only queries run as. The migrating role becomes a member of the role,
5
+ * which Postgres 16 needs to hand it the runner. The role bypasses row-level security only when the migrating role may
6
+ * give it that: a superuser, or a role with BYPASSRLS on Postgres 16 or later.
7
+ */
8
+ const roleStep = () => `create schema if not exists ${queryRunnerSchema};
9
+
10
+ do $$
11
+ declare
12
+ query_role text := ${queryRoleSql};
13
+ begin
14
+ if not exists (select from pg_roles where rolname = query_role) then execute format('create role %I nologin', query_role); end if;
15
+ execute format('grant %I to current_user', query_role);
16
+ if (select rolsuper or (rolbypassrls and current_setting('server_version_num')::int >= 160000) from pg_roles where rolname = current_user) then execute format('alter role %I bypassrls', query_role); end if;
17
+ end $$;`;
18
+ //#endregion
19
+ export { roleStep };
@@ -1,6 +1,6 @@
1
1
  //#region src/auth-store.d.ts
2
2
  /** The store's tables besides the user table, under their built-in names. */
3
3
  export declare const storeTableNames: string[];
4
- /** The record of the store's migrations, under its built-in name. */
5
- export declare const migrationsTableName: string;
4
+ /** The records of the store's steps, `auth_steps`, and of the versions a store recorded before it, under their built-in names. */
5
+ export declare const storeRecordNames: string[];
6
6
  //#endregion
@@ -3,7 +3,7 @@ import { storeTableNamesOf } from "./better-auth/store/table-names.js";
3
3
  //#region src/auth-store.ts
4
4
  /** The store's tables besides the user table, under their built-in names. */
5
5
  const storeTableNames = storeTableNamesOf(resolveNames({ schema: void 0 }));
6
- /** The record of the store's migrations, under its built-in name. */
7
- const migrationsTableName = resolveNames({ schema: void 0 }).table("auth_migrations").name;
6
+ /** The records of the store's steps, `auth_steps`, and of the versions a store recorded before it, under their built-in names. */
7
+ const storeRecordNames = [resolveNames({ schema: void 0 }).table("auth_steps").name, resolveNames({ schema: void 0 }).table("auth_migrations").name];
8
8
  //#endregion
9
- export { migrationsTableName, storeTableNames };
9
+ export { storeRecordNames, storeTableNames };
@@ -1,10 +1,19 @@
1
1
  import { AdminAuth } from "./create-auth.js";
2
+ import { KeptModule } from "./store/offline/store-model.js";
3
+ import "../internal.js";
2
4
  //#region src/better-auth/auth-schema.d.ts
3
5
  /**
4
- * The SQL that brings the admin store to this version of Protobase: the steps it has not applied, each version
5
- * followed by its row in `auth_migrations`; for a new store, that table first. A store an earlier Protobase made
6
- * without the record is adopted: the versions it matches are recorded as applied (`planAdoption`), the others' steps
7
- * follow. `undefined` when the store is current. The SQL never drops anything.
6
+ * The SQL that brings the admin store to this version of Protobase: the parts of the modules that are on it has not
7
+ * applied, each followed by its row in `auth_steps`; for a store without that table, the table first. A store that
8
+ * recorded versions of the former chain in `auth_migrations` gets its parts recorded from them; one an earlier
9
+ * Protobase made without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
10
+ * others' steps follow. `undefined` when the store is current. The SQL never drops anything.
8
11
  */
9
12
  export declare const authSchemaMigration: (auth: AdminAuth) => Promise<string | undefined>;
13
+ /**
14
+ * The modules the config turns off whose steps the store has, each at its last step, which a project's first snapshot
15
+ * keeps: the store has their tables. Read from `auth_steps`, or from `auth_migrations`, or for a store with neither,
16
+ * from the versions its adoption finds it has.
17
+ */
18
+ export declare const keptStoreModules: (auth: AdminAuth) => Promise<KeptModule[]>;
10
19
  //#endregion
@@ -1,49 +1,57 @@
1
- import { plainStoreDb } from "./store/store-db.js";
1
+ import { allModules } from "./names/modules-on.js";
2
2
  import { storeNames } from "./store/store-names.js";
3
- import { appliedVersions } from "./store/migrations-table.js";
4
- import { latestStoreVersion, legacyVersions } from "./store/steps/legacy-versions.js";
5
- import { migrationsTableSql, stepsSql } from "./store/migration-sql.js";
3
+ import { plainStoreDb } from "./store/store-db.js";
4
+ import { appliedSteps, hadOf } from "./store/step-record.js";
5
+ import { keptModule } from "./store/offline/store-model.js";
6
+ import { recordedSteps } from "./store/offline/baseline-store.js";
7
+ import { stepRecordSql, stepsSql } from "./store/migration-sql.js";
6
8
  import { renderSteps } from "./store/steps/render.js";
7
- import { migrationNames } from "./store/steps/step.js";
9
+ import { appliedVersions, stepRecordMigration, stepsOfVersions } from "./store/legacy-record.js";
10
+ import { migrationNames, organizationsInput } from "./store/steps/step.js";
8
11
  import { adoptionSql, planAdoption, storeHasTables } from "./store/adoption.js";
9
- import { hadByVersion, refuseModulesOff } from "./store/modules-off.js";
10
12
  //#region src/better-auth/auth-schema.ts
11
- const refuseNewer = (applied) => {
12
- const newest = applied.at(-1);
13
- if (newest !== void 0 && newest > latestStoreVersion) throw new Error(`The auth store is at migration ${newest}, newer than the ${latestStoreVersion} this version of Protobase knows; upgrade Protobase`);
14
- };
15
- /**
16
- * The steps whose versions `applied` lacks, each version followed by its row in `auth_migrations`; written only with
17
- * every module on (`refuseModulesOff`, `hadByVersion`).
18
- */
19
- const pendingSql = (names, applied) => {
20
- const rendered = renderSteps(migrationNames(names), names.names.modules, hadByVersion(applied));
21
- const versions = legacyVersions.map(({ version }) => version).filter((version) => !applied.includes(version));
22
- return rendered.length === 0 ? void 0 : stepsSql(names, rendered, versions);
13
+ const pendingSql = (auth, names, had) => {
14
+ const rendered = renderSteps(migrationNames(names), names.names.modules, had, organizationsInput(auth.organizations?.options));
15
+ return rendered.length === 0 ? [] : [stepsSql(names, rendered)];
23
16
  };
24
17
  /**
25
- * The SQL that brings the admin store to this version of Protobase: the steps it has not applied, each version
26
- * followed by its row in `auth_migrations`; for a new store, that table first. A store an earlier Protobase made
27
- * without the record is adopted: the versions it matches are recorded as applied (`planAdoption`), the others' steps
28
- * follow. `undefined` when the store is current. The SQL never drops anything.
18
+ * The SQL that brings the admin store to this version of Protobase: the parts of the modules that are on it has not
19
+ * applied, each followed by its row in `auth_steps`; for a store without that table, the table first. A store that
20
+ * recorded versions of the former chain in `auth_migrations` gets its parts recorded from them; one an earlier
21
+ * Protobase made without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
22
+ * others' steps follow. `undefined` when the store is current. The SQL never drops anything.
29
23
  */
30
24
  const authSchemaMigration = async (auth) => {
31
25
  const names = storeNames(auth);
32
- refuseModulesOff(names);
33
26
  const db = plainStoreDb(auth);
34
- const applied = await appliedVersions(db, names);
35
- if (applied !== void 0) {
36
- refuseNewer(applied);
37
- return pendingSql(names, applied);
38
- }
39
- if (!await storeHasTables(db, names)) return [migrationsTableSql(names), pendingSql(names, [])].join("\n\n");
27
+ const applied = await appliedSteps(db, names);
28
+ if (applied !== void 0) return pendingSql(auth, names, hadOf(applied))[0];
29
+ const record = stepRecordSql(names);
30
+ const versions = await appliedVersions(db, names);
31
+ if (versions !== void 0) return [stepRecordMigration(names), ...pendingSql(auth, names, hadOf(stepsOfVersions(versions)))].join("\n\n");
32
+ if (!await storeHasTables(db, names)) return [record, ...pendingSql(auth, names, hadOf([]))].join("\n\n");
40
33
  const { adopted, pending } = await planAdoption(db, names);
41
- const rest = pending.length === 0 ? [] : [pendingSql(names, adopted.map(({ migration }) => migration.version))];
34
+ const rest = pending.length === 0 ? [] : pendingSql(auth, names, hadOf(stepsOfVersions(adopted.map(({ migration }) => migration.version))));
42
35
  return [
43
- migrationsTableSql(names),
36
+ record,
44
37
  adoptionSql(names, adopted),
45
38
  ...rest
46
39
  ].join("\n\n");
47
40
  };
41
+ const adoptedVersions = async (db, names) => await storeHasTables(db, names) ? (await planAdoption(db, names)).adopted.map(({ migration }) => migration.version) : [];
42
+ /**
43
+ * The modules the config turns off whose steps the store has, each at its last step, which a project's first snapshot
44
+ * keeps: the store has their tables. Read from `auth_steps`, or from `auth_migrations`, or for a store with neither,
45
+ * from the versions its adoption finds it has.
46
+ */
47
+ const keptStoreModules = async (auth) => {
48
+ const names = storeNames(auth);
49
+ const db = plainStoreDb(auth);
50
+ const steps = await appliedSteps(db, names);
51
+ const versions = steps === void 0 ? await appliedVersions(db, names) ?? await adoptedVersions(db, names) : void 0;
52
+ const applied = steps ?? stepsOfVersions(versions ?? []);
53
+ const recorded = recordedSteps(applied);
54
+ return allModules.filter((module) => !names.names.modules.includes(module) && recorded[module] !== void 0).map((module) => keptModule(names, module, recorded[module]));
55
+ };
48
56
  //#endregion
49
- export { authSchemaMigration };
57
+ export { authSchemaMigration, keptStoreModules };
@@ -24,18 +24,24 @@ import { SignInPolicy } from "./sign-in-policy.js";
24
24
  import { McpAuthOptions } from "./mcp/mcp-plugins.js";
25
25
  import { OAuthApiResource } from "./oauth-api.js";
26
26
  import { PersonalAccessTokensOptions } from "./personal-access-tokens/options.js";
27
- import { OrganizationsOptions, ResolvedOrganizations } from "./organizations/options.js";
28
27
  import { JobDefinition } from "../jobs/job-types.js";
29
- import { Session } from "../types.js";
28
+ import { Session, TenantValue } from "../types.js";
29
+ import { OrganizationsOptions, ResolvedOrganizations } from "./organizations/options.js";
30
+ import { PinRead } from "./organizations/kept-organizations.js";
30
31
  import { SignUpField } from "./sign-up/sign-up-fields.js";
31
32
  import { CreateAuthOptions, UserCreatedHook } from "./create-auth.js";
32
33
  import "../index.js";
33
- import { Db } from "@protobase/query";
34
+ import { Db, ScopedDb } from "@protobase/query";
34
35
  import { OrganizationOptions } from "better-auth/plugins/organization";
35
36
  //#region src/better-auth/auth-settings.d.ts
36
- /** What every hook of the project's own gets as its last argument: the app's database, the one jobs get. */
37
+ /**
38
+ * What every hook of the project's own gets as its last argument: the app's database, kept to the organization the
39
+ * hook is about on the tables whose rows belong to one (`ScopedDb`), such as the new organization in
40
+ * `onOrganizationCreated`; a hook about no organization, such as `onUserCreated`, sees none of their rows, and while
41
+ * organizations are off after being on, the pinned organization's.
42
+ */
37
43
  export type HookContext = {
38
- db: Db;
44
+ db: ScopedDb;
39
45
  };
40
46
  type OrganizationHooks = NonNullable<OrganizationOptions['organizationHooks']>;
41
47
  /**
@@ -68,7 +74,7 @@ export type AuthHooks = {
68
74
  * `auth` in `protobase.config.ts`: the sign-in settings as data. The store is the app's own database, in `schema`;
69
75
  * the hooks and a mailer of the project's own are found in auth/hooks.ts and auth/mailer.ts.
70
76
  */
71
- export type AuthSettings = Omit<CreateAuthOptions, 'database' | 'secret' | 'generateUserId' | 'onUserCreated' | 'mailer' | 'organizations' | 'mcp' | 'workflowConnections' | 'senderVerifiers'> & {
77
+ export type AuthSettings = Omit<CreateAuthOptions, 'database' | 'secret' | 'generateUserId' | 'onUserCreated' | 'mailer' | 'organizations' | 'organizationsOff' | 'mcp' | 'workflowConnections' | 'senderVerifiers'> & {
72
78
  /** Signs cookies and encrypts the JWT private keys, such as `PROTOBASE_SECRET`. Generate with `openssl rand -base64 32`. */
73
79
  secret?: string;
74
80
  /** The schema of the auth store in the app's database; default `auth`. */
@@ -77,22 +83,34 @@ export type AuthSettings = Omit<CreateAuthOptions, 'database' | 'secret' | 'gene
77
83
  generateUserId?: 'uuid';
78
84
  /** `false` turns mail off whatever the environment says; default SMTP from `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM`. */
79
85
  mailer?: false;
80
- /** Turns on organizations (see `OrganizationsOptions`); their hooks are in the hooks module. */
81
- organizations?: true | Omit<OrganizationsOptions, 'generateId' | 'onCreated' | 'beforeDelete' | 'hooks'>;
86
+ /**
87
+ * Organizations (see `OrganizationsOptions`): `enabled` turns them on; their hooks are in the hooks module. Turning them
88
+ * off sets `enabled: false` and keeps `default`, whose organization then stands in for every one.
89
+ */
90
+ organizations?: Omit<OrganizationsOptions, 'generateId' | 'onCreated' | 'beforeDelete' | 'hooks'> & {
91
+ enabled: boolean;
92
+ };
82
93
  /** Turns on the OAuth provider for MCP clients: `true`, or the endpoint's `path` and the `connectPage`. */
83
94
  mcp?: true | Omit<McpAuthOptions, 'fetchClientMetadata'>;
84
95
  };
85
96
  export type AppAuthInput = {
86
- /** The app's database: sign-in queries run through it, its plugins included, and the hooks get it. */
97
+ /**
98
+ * The app's database: sign-in queries run through it, its plugins included, kept with organizations on to the
99
+ * organization the request works in (`signInOrganization`); each hook gets it kept to the organization it is about.
100
+ */
87
101
  db: Db;
88
102
  hooks?: AuthHooks;
89
103
  /** A mailer of the project's own, in place of the default. */
90
104
  mailer?: Mailer;
91
105
  /** The connections the app's workflow plugins declare, which people connect accounts through. */
92
106
  workflowConnections?: CreateAuthOptions['workflowConnections'];
107
+ /** `authenticate.tenant`, which pins the default organization while organizations are off after being on. */
108
+ tenant?: TenantValue;
109
+ /** The organization pinned while organizations are off after being on (`pinnedOrganization`), which hooks about none work in. */
110
+ pinned?: PinRead;
93
111
  };
94
112
  /** createAuth's options for the `auth` settings, the store in the app's own database. */
95
- export declare const appAuthOptions: (settings: AuthSettings, { db, hooks, mailer, workflowConnections }: AppAuthInput) => CreateAuthOptions;
113
+ export declare const appAuthOptions: (settings: AuthSettings, { db, hooks, mailer, workflowConnections, tenant, pinned }: AppAuthInput) => CreateAuthOptions;
96
114
  /** The app's Better Auth from its `auth` settings, built at serve time with only the plugins they turn on. */
97
115
  export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput) => Promise<import("better-auth").Auth<{
98
116
  user: {
@@ -6229,6 +6247,26 @@ export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput)
6229
6247
  handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
6230
6248
  }[];
6231
6249
  };
6250
+ } | {
6251
+ id: "protobase-pinned-membership";
6252
+ schema: {
6253
+ member: {
6254
+ modelName: string;
6255
+ fields: {
6256
+ organizationId: import("better-auth").DBFieldAttribute;
6257
+ userId: import("better-auth").DBFieldAttribute;
6258
+ role: import("better-auth").DBFieldAttribute;
6259
+ createdAt: import("better-auth").DBFieldAttribute;
6260
+ appRoles: import("better-auth").DBFieldAttribute;
6261
+ };
6262
+ };
6263
+ };
6264
+ hooks: {
6265
+ before: {
6266
+ matcher: (context: import("better-auth").HookEndpointContext) => boolean;
6267
+ handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
6268
+ }[];
6269
+ };
6232
6270
  } | {
6233
6271
  id: "protobase-personal-access-tokens";
6234
6272
  schema: Record<"personalAccessToken", {
@@ -12235,7 +12273,15 @@ export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput)
12235
12273
  databaseHooks: {
12236
12274
  user: {
12237
12275
  create: {
12238
- after?: ((user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>) | undefined;
12276
+ after?: ((user: {
12277
+ id: string;
12278
+ createdAt: Date;
12279
+ updatedAt: Date;
12280
+ email: string;
12281
+ emailVerified: boolean;
12282
+ name: string;
12283
+ image?: string | null | undefined;
12284
+ } & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>) | undefined;
12239
12285
  before: (user: {
12240
12286
  id: string;
12241
12287
  createdAt: Date;
@@ -12464,6 +12510,8 @@ export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput)
12464
12510
  roles: string[];
12465
12511
  roleDefinitions: RoleDefinitions;
12466
12512
  organizations: ResolvedOrganizations | undefined;
12513
+ pinnedOrganization: PinRead;
12514
+ keptTables: string[];
12467
12515
  defaultRole: string | undefined;
12468
12516
  generatesUserIds: boolean;
12469
12517
  mail: boolean;