@protobase/server 0.129.0 → 0.130.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) 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.js +14 -9
  46. package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
  47. package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
  48. package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
  49. package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
  50. package/dist/better-auth/store/adoption.js +25 -10
  51. package/dist/better-auth/store/drift.js +5 -4
  52. package/dist/better-auth/store/legacy-record.d.ts +10 -0
  53. package/dist/better-auth/store/legacy-record.js +56 -0
  54. package/dist/better-auth/store/migration-sql.js +31 -26
  55. package/dist/better-auth/store/offline/baseline-store.d.ts +35 -0
  56. package/dist/better-auth/store/offline/baseline-store.js +65 -0
  57. package/dist/better-auth/store/offline/module-switches.d.ts +27 -0
  58. package/dist/better-auth/store/offline/module-switches.js +94 -0
  59. package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
  60. package/dist/better-auth/store/offline/name-changes.js +5 -2
  61. package/dist/better-auth/store/offline/offline-steps.d.ts +21 -6
  62. package/dist/better-auth/store/offline/offline-steps.js +30 -20
  63. package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
  64. package/dist/better-auth/store/offline/retired-watch.js +36 -0
  65. package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
  66. package/dist/better-auth/store/offline/settings-names.js +10 -3
  67. package/dist/better-auth/store/offline/store-model.d.ts +9 -1
  68. package/dist/better-auth/store/offline/store-model.js +22 -5
  69. package/dist/better-auth/store/resources-outside.js +1 -1
  70. package/dist/better-auth/store/step-record.d.ts +13 -0
  71. package/dist/better-auth/store/step-record.js +59 -0
  72. package/dist/better-auth/store/steps/index.js +6 -1
  73. package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
  74. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  75. package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
  76. package/dist/better-auth/store/steps/render.d.ts +3 -0
  77. package/dist/better-auth/store/steps/render.js +48 -25
  78. package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
  79. package/dist/better-auth/store/steps/step-lint.js +31 -10
  80. package/dist/better-auth/store/steps/step.d.ts +18 -0
  81. package/dist/better-auth/store/steps/step.js +13 -4
  82. package/dist/better-auth/store/store-db.d.ts +6 -0
  83. package/dist/better-auth/store/store-db.js +11 -5
  84. package/dist/better-auth/store/store-names.d.ts +4 -0
  85. package/dist/better-auth/token-standing.js +12 -7
  86. package/dist/better-auth/users.d.ts +7 -2
  87. package/dist/better-auth/users.js +25 -3
  88. package/dist/built-in-resources.js +1 -1
  89. package/dist/calls/calls-module.js +42 -0
  90. package/dist/calls/calls-sql.js +4 -30
  91. package/dist/changes/capture-names.d.ts +3 -1
  92. package/dist/changes/capture-names.js +5 -2
  93. package/dist/changes/capture-schema-sql.d.ts +10 -0
  94. package/dist/changes/capture-schema-sql.js +21 -0
  95. package/dist/changes/capture-schema.d.ts +0 -18
  96. package/dist/changes/capture-schema.js +1 -74
  97. package/dist/changes/capture-sql.js +30 -24
  98. package/dist/changes/changes-input.js +36 -0
  99. package/dist/changes/changes-module.js +44 -0
  100. package/dist/changes/read-capture.js +67 -0
  101. package/dist/changes/steps/001-outbox.js +23 -0
  102. package/dist/channels/sends-module.js +37 -0
  103. package/dist/channels/sends-schema-sql.js +5 -5
  104. package/dist/comments/comments-module.js +30 -0
  105. package/dist/comments/comments-sql.js +1 -22
  106. package/dist/computed/buckets-sql.d.ts +5 -1
  107. package/dist/computed/buckets-sql.js +39 -46
  108. package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
  109. package/dist/computed/buckets-targets.js +50 -0
  110. package/dist/computed/computed-input.js +65 -0
  111. package/dist/computed/computed-module.js +102 -0
  112. package/dist/computed/formula-sql.js +14 -1
  113. package/dist/computed/read-computed.js +100 -0
  114. package/dist/computed/rollup-sql.js +13 -10
  115. package/dist/config-exports.d.ts +2 -2
  116. package/dist/create-admin.js +21 -5
  117. package/dist/derived/derived-module.js +89 -0
  118. package/dist/derived/derived-sql.js +1 -47
  119. package/dist/functions/define-function.d.ts +10 -4
  120. package/dist/functions/routes.js +5 -3
  121. package/dist/functions/supabase-routes.js +7 -5
  122. package/dist/history/history-module.js +34 -0
  123. package/dist/index.d.ts +19 -28
  124. package/dist/index.js +11 -21
  125. package/dist/internal.d.ts +27 -10
  126. package/dist/internal.js +22 -7
  127. package/dist/jobs/functions-sql.js +7 -11
  128. package/dist/jobs/job-data.js +36 -0
  129. package/dist/jobs/job-types.d.ts +6 -3
  130. package/dist/jobs/jobs-module.d.ts +5 -0
  131. package/dist/jobs/jobs-module.js +84 -0
  132. package/dist/jobs/run-job.d.ts +1 -1
  133. package/dist/jobs/run-job.js +7 -5
  134. package/dist/jobs/runtime.d.ts +9 -4
  135. package/dist/jobs/runtime.js +11 -6
  136. package/dist/jobs/schema.d.ts +0 -11
  137. package/dist/jobs/schema.js +1 -59
  138. package/dist/jobs/steps/001-pg-boss-45.js +483 -0
  139. package/dist/live/notices-module.js +30 -0
  140. package/dist/live/notices-sql.js +2 -1
  141. package/dist/mail/feedback/feedback-schema.js +3 -30
  142. package/dist/mail/feedback/mail-feedback-module.js +37 -0
  143. package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
  144. package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
  145. package/dist/migration-record/check-record.d.ts +9 -7
  146. package/dist/migration-record/check-record.js +12 -11
  147. package/dist/migration-record/module-needs.js +30 -0
  148. package/dist/migration-record/read-record.js +27 -15
  149. package/dist/migration-record/record-model.d.ts +7 -2
  150. package/dist/migration-record/record-model.js +14 -6
  151. package/dist/migration-record/startup-decision.js +18 -7
  152. package/dist/migration-sql/additive-statements.d.ts +4 -0
  153. package/dist/migration-sql/additive-statements.js +105 -0
  154. package/dist/notifications/devices-module.js +61 -0
  155. package/dist/notifications/history-module.js +50 -0
  156. package/dist/notifications/notifications-targets.js +23 -0
  157. package/dist/notifications/read-table.js +16 -0
  158. package/dist/notifications/schema-sql.js +1 -22
  159. package/dist/notifications/schema.js +1 -101
  160. package/dist/notifications/table-names.js +40 -0
  161. package/dist/organization-scope/app-scope.js +38 -0
  162. package/dist/organization-scope/auth-request-organization.js +71 -0
  163. package/dist/organization-scope/organization-tables.js +20 -0
  164. package/dist/organization-scope/sign-in-organization.js +21 -0
  165. package/dist/package.js +1 -1
  166. package/dist/personal-mail/shared-sender-store.js +4 -2
  167. package/dist/realtime/relay/realtime-relay-module.js +37 -0
  168. package/dist/relation-found.js +6 -0
  169. package/dist/relay/read-relay.js +85 -0
  170. package/dist/relay/realtime-members-sql.js +51 -28
  171. package/dist/relay/relay-module.js +53 -0
  172. package/dist/relay/relay-targets.js +28 -0
  173. package/dist/relay/session-end.js +1 -3
  174. package/dist/relay/sessions-sql.js +4 -27
  175. package/dist/rest/table-routes.js +9 -2
  176. package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
  177. package/dist/schema-modules/feature-schemas-sql.js +51 -0
  178. package/dist/schema-modules/module-difference.d.ts +31 -0
  179. package/dist/schema-modules/module-difference.js +98 -0
  180. package/dist/schema-modules/modules-sql.js +13 -0
  181. package/dist/schema-modules/modules.d.ts +37 -0
  182. package/dist/schema-modules/modules.js +56 -0
  183. package/dist/schema-modules/needed-modules.d.ts +41 -0
  184. package/dist/schema-modules/needed-modules.js +61 -0
  185. package/dist/schema-modules/resource-difference.js +83 -0
  186. package/dist/schema-modules/schema-module.d.ts +112 -0
  187. package/dist/schema-modules/schema-module.js +8 -0
  188. package/dist/status/status-module.js +63 -0
  189. package/dist/status/status-targets.js +21 -0
  190. package/dist/types.d.ts +6 -1
  191. package/dist/user-tables/reloading-admin.d.ts +1 -0
  192. package/dist/user-tables/reloading-admin.js +1 -0
  193. package/dist/user-tables/schema-sql.js +1 -14
  194. package/dist/user-tables/schema.js +4 -27
  195. package/dist/user-tables/user-tables-module.js +38 -0
  196. package/dist/webhooks/table/delivery-log-module.js +36 -0
  197. package/dist/webhooks/table/owner-roles.js +3 -2
  198. package/dist/webhooks/table/schema-sql.js +27 -26
  199. package/dist/webhooks/table/webhooks-schema-module.js +63 -0
  200. package/dist/webhooks/table/webhooks-targets.js +26 -0
  201. package/dist/webhooks/webhooks.js +1 -1
  202. package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
  203. package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
  204. package/dist/workflows/custom-steps/runners-sql.js +10 -7
  205. package/dist/workflows/read-catalogue.js +23 -0
  206. package/dist/workflows/schema-sql.js +12 -9
  207. package/dist/workflows/status-sql.js +12 -6
  208. package/dist/workflows/storage/storage-module.js +39 -0
  209. package/dist/workflows/storage/storage-sql.js +8 -5
  210. package/dist/workflows/workflows-schema-module.js +49 -0
  211. package/dist/workflows/workflows-tables-sql.js +32 -0
  212. package/dist/workflows/workflows-targets.js +16 -0
  213. package/package.json +6 -6
  214. package/dist/assistant/query-runner/runner-plan.js +0 -30
  215. package/dist/better-auth/store/migrations-table.js +0 -27
  216. package/dist/better-auth/store/modules-off.js +0 -17
  217. package/dist/calls/calls-sql.d.ts +0 -11
  218. package/dist/changes/capture-plan.js +0 -79
  219. package/dist/channels/sends-schema.d.ts +0 -7
  220. package/dist/channels/sends-schema.js +0 -18
  221. package/dist/comments/comments-sql.d.ts +0 -14
  222. package/dist/computed/buckets-plan.d.ts +0 -2
  223. package/dist/computed/buckets-plan.js +0 -88
  224. package/dist/computed/buckets-schema.js +0 -39
  225. package/dist/computed/computed-plan.js +0 -81
  226. package/dist/computed/computed-schema.d.ts +0 -16
  227. package/dist/computed/computed-schema.js +0 -63
  228. package/dist/derived/derived-sql.d.ts +0 -12
  229. package/dist/mail/feedback/feedback-schema.d.ts +0 -7
  230. package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
  231. package/dist/notifications/schema.d.ts +0 -14
  232. package/dist/realtime/relay/relay-schema.d.ts +0 -7
  233. package/dist/realtime/relay/relay-schema.js +0 -20
  234. package/dist/relay/realtime-members-schema.js +0 -67
  235. package/dist/relay/relay-schema.d.ts +0 -14
  236. package/dist/relay/relay-schema.js +0 -28
  237. package/dist/status/schema.d.ts +0 -12
  238. package/dist/status/schema.js +0 -33
  239. package/dist/user-tables/schema.d.ts +0 -11
  240. package/dist/webhooks/table/schema.d.ts +0 -16
  241. package/dist/webhooks/table/schema.js +0 -56
  242. package/dist/workflows/schema.d.ts +0 -13
  243. package/dist/workflows/schema.js +0 -88
@@ -1,33 +1,71 @@
1
+ import { modulesOf } from "./names/modules-on.js";
2
+ import { resolveNames } from "./names/resolve-names.js";
3
+ import { signInOrganization } from "../organization-scope/sign-in-organization.js";
4
+ import { organizationsEnabled } from "./organizations/options.js";
1
5
  import { buildAuth } from "./create-auth.js";
6
+ import { noOrganizationTables, organizationTables } from "../organization-scope/organization-tables.js";
7
+ import { appScope } from "../organization-scope/app-scope.js";
2
8
  import { senderVerifierList } from "../personal-mail/verifiers/verifier-list.js";
9
+ import { scopedDb } from "@protobase/query";
3
10
  //#region src/better-auth/auth-settings.ts
11
+ const organizationOfHook = (input) => {
12
+ const { organization, member, invitation } = input ?? {};
13
+ const id = organization?.id ?? member?.organizationId ?? invitation?.organizationId;
14
+ return typeof id === "string" ? id : void 0;
15
+ };
4
16
  const organizationOptions = (organizations, hooks, app) => {
5
- if (!organizations) return void 0;
17
+ if (!organizationsEnabled(organizations)) return void 0;
18
+ const { enabled: _, ...options } = organizations;
6
19
  const own = hooks.organizationHooks ?? {};
7
- const betterAuthHooks = Object.fromEntries(Object.entries(own).map(([name, hook]) => [name, (input) => hook(input, app)]));
20
+ const betterAuthHooks = Object.fromEntries(Object.entries(own).map(([name, hook]) => [name, (input) => hook(input, app(organizationOfHook(input)))]));
8
21
  return {
9
- ...organizations === true ? {} : organizations,
10
- ...hooks.generateOrganizationId && { generateId: () => hooks.generateOrganizationId(app) },
11
- ...hooks.onOrganizationCreated && { onCreated: (input) => hooks.onOrganizationCreated(input, app) },
12
- ...hooks.beforeOrganizationDeleted && { beforeDelete: (organization) => hooks.beforeOrganizationDeleted(organization, app) },
22
+ ...options,
23
+ ...hooks.generateOrganizationId && { generateId: () => hooks.generateOrganizationId(app(void 0)) },
24
+ ...hooks.onOrganizationCreated && { onCreated: (input) => hooks.onOrganizationCreated(input, app(input.organization.id)) },
25
+ ...hooks.beforeOrganizationDeleted && { beforeDelete: (organization) => hooks.beforeOrganizationDeleted(organization, app(organization.id)) },
13
26
  ...Object.keys(betterAuthHooks).length > 0 && { hooks: betterAuthHooks }
14
27
  };
15
28
  };
29
+ const organizationsOffOf = (organizations, tenant) => ({
30
+ ...organizations?.default && { default: organizations.default },
31
+ ...organizations?.existingUsersRole !== void 0 && { existingUsersRole: organizations.existingUsersRole },
32
+ ...tenant !== void 0 && { tenant }
33
+ });
16
34
  /** createAuth's options for the `auth` settings, the store in the app's own database. */
17
- const appAuthOptions = (settings, { db, hooks = {}, mailer, workflowConnections }) => {
35
+ const appAuthOptions = (settings, { db, hooks = {}, mailer, workflowConnections, tenant, pinned }) => {
18
36
  const { schema = "auth", secret, generateUserId, mailer: mail, organizations, mcp, ...rest } = settings;
19
37
  if (!secret) throw new Error("the auth secret is not set: give it the app's secret, PROTOBASE_SECRET, made with `openssl rand -base64 32`");
20
- const app = { db };
38
+ const on = organizationsEnabled(organizations);
39
+ const names = resolveNames({
40
+ schema,
41
+ tables: rest.tables,
42
+ modules: modulesOf({
43
+ ...rest,
44
+ mcp,
45
+ organizations: on
46
+ })
47
+ });
48
+ const scope = on ? organizationTables(names) : noOrganizationTables;
49
+ const app = (organization) => ({ db: scopedDb(db, scope, organization) });
50
+ const hookScope = appScope({
51
+ organizations: on,
52
+ names,
53
+ pinned
54
+ });
55
+ const outside = async () => {
56
+ const { tables, pinned: organization } = await hookScope();
57
+ return { db: scopedDb(db, tables, organization) };
58
+ };
21
59
  const organizationsOptions = organizationOptions(organizations, hooks, app);
22
- const userId = hooks.generateUserId ? () => hooks.generateUserId(app) : generateUserId;
23
- const onUserCreated = hooks.onUserCreated && ((user, context) => hooks.onUserCreated(user, context, app));
60
+ const userId = hooks.generateUserId ? async () => hooks.generateUserId(await outside()) : generateUserId;
61
+ const onUserCreated = hooks.onUserCreated && (async (user, context) => hooks.onUserCreated(user, context, await outside()));
24
62
  const verifiers = senderVerifierList();
25
63
  hooks.senderVerifiers?.(verifiers.add_verifier);
26
64
  const senderVerifiers = verifiers.freeze();
27
65
  return {
28
66
  ...rest,
29
67
  database: {
30
- db,
68
+ db: on ? scopedDb(db, scope, signInOrganization) : db,
31
69
  type: "postgres",
32
70
  schemaName: schema,
33
71
  transaction: true
@@ -36,13 +74,19 @@ const appAuthOptions = (settings, { db, hooks = {}, mailer, workflowConnections
36
74
  ...userId && { generateUserId: userId },
37
75
  ...onUserCreated && { onUserCreated },
38
76
  ...mail === false ? { mailer: false } : mailer && { mailer },
39
- ...organizationsOptions && { organizations: organizationsOptions },
77
+ ...organizationsOptions ? { organizations: organizationsOptions } : { organizationsOff: organizationsOffOf(organizations, tenant) },
40
78
  ...mcp && { mcp },
41
79
  ...workflowConnections && { workflowConnections },
42
80
  ...senderVerifiers.length > 0 && { senderVerifiers }
43
81
  };
44
82
  };
45
83
  /** The app's Better Auth from its `auth` settings, built at serve time with only the plugins they turn on. */
46
- const buildAppAuth = (settings, input) => buildAuth(appAuthOptions(settings, input));
84
+ const buildAppAuth = (settings, input) => {
85
+ const auth = buildAuth(appAuthOptions(settings, {
86
+ ...input,
87
+ pinned: async () => (await auth).pinnedOrganization()
88
+ }));
89
+ return auth;
90
+ };
47
91
  //#endregion
48
92
  export { appAuthOptions, buildAppAuth };
@@ -1,4 +1,5 @@
1
1
  import { AdminAuth } from "./create-auth.js";
2
+ import "./store/store-names.js";
2
3
  //#region src/better-auth/auth-tables.d.ts
3
4
  /** A table as config names it: the search path decides when it names no schema. */
4
5
  export type TableName = {
@@ -11,9 +12,11 @@ export type AuthStoreTables = {
11
12
  schemas: string[];
12
13
  };
13
14
  /**
14
- * The admin store's tables, which the assistant's queries and the app's resources must never read: every table of the
15
- * store's names, with `users.keyTable` the table under the user view too, such as Supabase's `auth.users`, whose
16
- * password hashes the view leaves out but the table holds, and every table of `users.guardedSchemas`.
15
+ * The admin store's tables, which the assistant's queries and the app's resources must never read: every table of
16
+ * every module under the store's names, those of a module that is off included, which may keep its rows, each named on
17
+ * its own so a module that is off never clashes with one that is on; with `users.keyTable` the table under the user
18
+ * view too, such as Supabase's `auth.users`, whose password hashes the view leaves out but the table holds; and every
19
+ * table of `users.guardedSchemas`.
17
20
  */
18
21
  export declare const authStoreTables: (auth: AdminAuth) => AuthStoreTables;
19
22
  //#endregion
@@ -1,13 +1,18 @@
1
+ import { builtInModules } from "./names/modules/index.js";
2
+ import { tableNameOf } from "./names/resolve-names.js";
1
3
  import { storeNames } from "./store/store-names.js";
2
4
  //#region src/better-auth/auth-tables.ts
3
5
  /**
4
- * The admin store's tables, which the assistant's queries and the app's resources must never read: every table of the
5
- * store's names, with `users.keyTable` the table under the user view too, such as Supabase's `auth.users`, whose
6
- * password hashes the view leaves out but the table holds, and every table of `users.guardedSchemas`.
6
+ * The admin store's tables, which the assistant's queries and the app's resources must never read: every table of
7
+ * every module under the store's names, those of a module that is off included, which may keep its rows, each named on
8
+ * its own so a module that is off never clashes with one that is on; with `users.keyTable` the table under the user
9
+ * view too, such as Supabase's `auth.users`, whose password hashes the view leaves out but the table holds; and every
10
+ * table of `users.guardedSchemas`.
7
11
  */
8
- const authStoreTables = (auth) => {
9
- const { schema, names, users } = storeNames(auth);
10
- const own = Object.values(names.tables).map(({ name }) => ({
12
+ const authStoreTables = (auth) => storeAuthTables(storeNames(auth));
13
+ /** The admin store's tables (`authStoreTables`), from the store's names alone, as `protobase migration` reads them from the config. */
14
+ const storeAuthTables = ({ schema, names, users }) => {
15
+ const own = [...new Set(builtInModules.flatMap((module) => Object.keys(module.tables)).map((table) => tableNameOf(names.input.tables ?? {}, table)))].map((name) => ({
11
16
  schema,
12
17
  name
13
18
  }));
@@ -20,4 +25,4 @@ const authStoreTables = (auth) => {
20
25
  };
21
26
  };
22
27
  //#endregion
23
- export { authStoreTables };
28
+ export { authStoreTables, storeAuthTables };
@@ -1,5 +1,8 @@
1
1
  import { jwtSessions } from "../auth/jwt.js";
2
2
  import { noGlobalRole } from "./organizations/role-definitions.js";
3
+ import { storeSqlOf } from "./store/store-sql.js";
4
+ import { tokenOrganization } from "./personal-access-tokens/pinned-tokens.js";
5
+ import { keptNames } from "./organizations/kept-organizations.js";
3
6
  import { cachedKeys } from "./jwks-cache.js";
4
7
  import { checkTokenStanding, checkUserStanding, tokenClaims } from "./token-standing.js";
5
8
  import { accessTokenType, withAccessTokens } from "./api-access-tokens.js";
@@ -40,12 +43,17 @@ const betterAuthAuthenticator = (options) => {
40
43
  const { issuer } = tokens;
41
44
  const organizations = options.organizations ?? Boolean(options.auth?.organizations);
42
45
  const { auth } = options;
46
+ const pinOf = async () => auth && !organizations ? (await auth.pinnedOrganization())?.id : void 0;
43
47
  const personal = auth?.personalAccessTokens && {
44
48
  prefix: auth.personalAccessTokens.prefix,
45
49
  sessionOf: personalAccessTokenSessions({
46
50
  prefix: auth.personalAccessTokens.prefix,
47
51
  context: () => auth.$context,
48
52
  organizations,
53
+ ...auth && !organizations && { pinned: {
54
+ pin: auth.pinnedOrganization,
55
+ organizationOf: (store, id) => tokenOrganization(storeSqlOf(store), keptNames(auth.names), id)
56
+ } },
49
57
  ...options.tenant !== void 0 && { tenant: options.tenant }
50
58
  })
51
59
  };
@@ -110,7 +118,7 @@ const betterAuthAuthenticator = (options) => {
110
118
  };
111
119
  let replayStore;
112
120
  const dpopReplayStore = () => replayStore ??= options.auth ? options.auth.$context.then(({ internalAdapter }) => createDpopReplayStore(internalAdapter)) : Promise.resolve(createInMemoryDpopReplayStore());
113
- const ownStanding = (context, payload, session) => checkTokenStanding(context, tokenClaims(payload, session.user.roles, organizations ? session.tenant : void 0), organizations);
121
+ const ownStanding = async (context, payload, session) => checkTokenStanding(context, tokenClaims(payload, session.user.roles, organizations ? session.tenant : void 0), organizations, void 0, await pinOf());
114
122
  const grantStanding = async (context, payload, session) => {
115
123
  await checkMcpGrant(context.adapter, {
116
124
  userId: payload.sub,
@@ -118,7 +126,7 @@ const betterAuthAuthenticator = (options) => {
118
126
  issuedAt: payload.iat
119
127
  });
120
128
  const { sessionId: _, ...claims } = tokenClaims(payload, session.user.roles, organizations ? session.tenant : void 0);
121
- const organizationRole = await checkUserStanding(context, claims, organizations);
129
+ const organizationRole = await checkUserStanding(context, claims, organizations, void 0, await pinOf());
122
130
  return organizationRole ? { organizationRole } : {};
123
131
  };
124
132
  const own = sessionOf({ audience: options.audience ?? issuer }, ownStanding);
@@ -33,9 +33,10 @@ import { mcpAuthPlugins } from "./mcp/mcp-auth-plugins.js";
33
33
  import { OpenIdProviderOptions } from "./openid-provider/openid-provider-options.js";
34
34
  import { openIdProviderPlugins } from "./openid-provider/openid-provider-plugins.js";
35
35
  import { PersonalAccessTokensOptions } from "./personal-access-tokens/options.js";
36
- import { OrganizationsOptions, ResolvedOrganizations } from "./organizations/options.js";
37
36
  import { JobDefinition } from "../jobs/job-types.js";
38
37
  import { Session } from "../types.js";
38
+ import { OrganizationsOptions, ResolvedOrganizations } from "./organizations/options.js";
39
+ import { OrganizationsOff, PinRead } from "./organizations/kept-organizations.js";
39
40
  import { PlatformSignIn } from "./platform-sign-in.js";
40
41
  import { SsoOptions } from "./saml-sign-in.js";
41
42
  import { samlPlugin } from "./saml-plugin.js";
@@ -217,6 +218,13 @@ export type CreateAuthOptions = {
217
218
  * alone, with tokens for the origin of `baseURL` unless `clientId` names another.
218
219
  */
219
220
  signInProviders?: readonly PlatformSignIn[];
221
+ /**
222
+ * Lets the platform's sign-in providers from the environment sign in devices (`PROTOBASE_SIGN_IN_DEVICES=true`, or
223
+ * `..._DEVICES` of a provider named by its id), which keep their tables in the store: a migration makes them, as it is
224
+ * written from the config alone. A provider of `signInProviders` with `devices: true` needs no switch. Without it, an
225
+ * environment provider that signs in devices stops the server at startup. Default off.
226
+ */
227
+ signInDevices?: boolean;
220
228
  /**
221
229
  * Single sign-on with the app's SAML 2.0 identity providers, for example `{ saml: [{ id: 'okta', name: 'Okta',
222
230
  * domains: ['example.com'], idp: { metadata } }] }` (see `SamlProvider`). Like `socialProviders`, a provider signs up
@@ -229,6 +237,13 @@ export type CreateAuthOptions = {
229
237
  * are held globally (on the user) or per membership. Off by default: the app works as one organization.
230
238
  */
231
239
  organizations?: OrganizationsOptions;
240
+ /**
241
+ * What the config says of organizations while they are off: their default organization and `authenticate.tenant`.
242
+ * The instance reads once whether the store still holds organizations, so they were on (`pinnedOrganization`), and
243
+ * then pins the default organization, refusing a tenant other than its id: only its members sign in and use their
244
+ * tokens, people who join become its members, and personal access tokens are made in it.
245
+ */
246
+ organizationsOff?: OrganizationsOff;
232
247
  /**
233
248
  * Turns on an OAuth provider for MCP clients: a client such as an AI assistant or code editor that speaks MCP registers
234
249
  * itself, the person signs in on the app's own pages and allows it on the connect page, and the client gets tokens
@@ -5439,7 +5454,7 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
5439
5454
  name?: string;
5440
5455
  slug?: string;
5441
5456
  logo?: string | null;
5442
- metadata?: Record<string, any>;
5457
+ metadata? /** Extra origins that may call the auth endpoints, such as the exact host of a dev tunnel. `baseURL` and `origins` are always trusted. */ : Record<string, any>;
5443
5458
  [key: string]: any;
5444
5459
  };
5445
5460
  }>;
@@ -6417,6 +6432,26 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
6417
6432
  handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
6418
6433
  }[];
6419
6434
  };
6435
+ } | {
6436
+ id: "protobase-pinned-membership";
6437
+ schema: {
6438
+ member: {
6439
+ modelName: string;
6440
+ fields: {
6441
+ organizationId: import("better-auth").DBFieldAttribute;
6442
+ userId: import("better-auth").DBFieldAttribute;
6443
+ role: import("better-auth").DBFieldAttribute;
6444
+ createdAt: import("better-auth").DBFieldAttribute;
6445
+ appRoles: import("better-auth").DBFieldAttribute;
6446
+ };
6447
+ };
6448
+ };
6449
+ hooks: {
6450
+ before: {
6451
+ matcher: (context: import("better-auth").HookEndpointContext) => boolean;
6452
+ handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
6453
+ }[];
6454
+ };
6420
6455
  } | {
6421
6456
  id: "protobase-personal-access-tokens";
6422
6457
  schema: Record<"personalAccessToken", {
@@ -6905,7 +6940,7 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
6905
6940
  SERVER_ONLY: true;
6906
6941
  };
6907
6942
  }, {
6908
- jwks_uri? /** The roles with their labels, for the role switcher. */ : string | undefined;
6943
+ jwks_uri?: string | undefined;
6909
6944
  userinfo_endpoint: string;
6910
6945
  acr_values_supported?: string[] | undefined;
6911
6946
  subject_types_supported: ("public" | "pairwise")[];
@@ -6937,7 +6972,9 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
6937
6972
  introspection_endpoint_auth_signing_alg_values_supported?: import("better-auth").PrivateKeyJwtSigningAlgorithm[] | undefined;
6938
6973
  code_challenge_methods_supported: "S256"[];
6939
6974
  authorization_response_iss_parameter_supported?: boolean | undefined;
6940
- client_id_metadata_document_supported?: boolean | undefined;
6975
+ client_id_metadata_document_supported?
6976
+ /** The roles with their labels, for the role switcher. */
6977
+ /** The roles with their labels, for the role switcher. */ : boolean | undefined;
6941
6978
  backchannel_logout_supported?: boolean | undefined;
6942
6979
  backchannel_logout_session_supported?: boolean | undefined;
6943
6980
  dpop_signing_alg_values_supported?: import("better-auth/plugins").JWSAlgorithms[] | undefined;
@@ -9598,7 +9635,7 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
9598
9635
  SERVER_ONLY: true;
9599
9636
  };
9600
9637
  }, {
9601
- jwks_uri? /** The roles with their labels, for the role switcher. */ : string | undefined;
9638
+ jwks_uri?: string | undefined;
9602
9639
  userinfo_endpoint: string;
9603
9640
  acr_values_supported?: string[] | undefined;
9604
9641
  subject_types_supported: ("public" | "pairwise")[];
@@ -9630,7 +9667,9 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
9630
9667
  introspection_endpoint_auth_signing_alg_values_supported?: import("better-auth").PrivateKeyJwtSigningAlgorithm[] | undefined;
9631
9668
  code_challenge_methods_supported: "S256"[];
9632
9669
  authorization_response_iss_parameter_supported?: boolean | undefined;
9633
- client_id_metadata_document_supported?: boolean | undefined;
9670
+ client_id_metadata_document_supported?
9671
+ /** The roles with their labels, for the role switcher. */
9672
+ /** The roles with their labels, for the role switcher. */ : boolean | undefined;
9634
9673
  backchannel_logout_supported?: boolean | undefined;
9635
9674
  backchannel_logout_session_supported?: boolean | undefined;
9636
9675
  dpop_signing_alg_values_supported?: import("better-auth/plugins").JWSAlgorithms[] | undefined;
@@ -12423,7 +12462,15 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
12423
12462
  databaseHooks: {
12424
12463
  user: {
12425
12464
  create: {
12426
- after?: ((user: import("better-auth").User & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>) | undefined;
12465
+ after?: ((user: {
12466
+ id: string;
12467
+ createdAt: Date;
12468
+ updatedAt: Date;
12469
+ email: string;
12470
+ emailVerified: boolean;
12471
+ name: string;
12472
+ image?: string | null | undefined;
12473
+ } & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>) | undefined;
12427
12474
  before: (user: {
12428
12475
  id: string;
12429
12476
  createdAt: Date;
@@ -12668,6 +12715,14 @@ export declare const createAuth: (options: CreateAuthOptions, plugins?: AuthPlug
12668
12715
  roles: string[];
12669
12716
  roleDefinitions: RoleDefinitions;
12670
12717
  organizations: ResolvedOrganizations | undefined;
12718
+ /**
12719
+ * The organization everyone works in while organizations are off after being on, `undefined` while they are on or
12720
+ * were never on; read from the store once (`pinOnce`), and refused with a tenant other than its id, which the
12721
+ * server's startup checks ask first.
12722
+ */
12723
+ pinnedOrganization: PinRead;
12724
+ /** The tables of organizations that sign-in reads while they are off, when the store holds them only after they were on. */
12725
+ keptTables: string[];
12671
12726
  defaultRole: string | undefined;
12672
12727
  /** New users get their ids from `generateUserId` instead of Better Auth's random text. */
12673
12728
  generatesUserIds: boolean;
@@ -1,5 +1,8 @@
1
1
  import { appOrigins, multiHostBaseURL, readOrigins, resolveOrigins } from "./origins.js";
2
2
  import { appNameOver, defaultAppName } from "../app-name.js";
3
+ import { modulesOf } from "./names/modules-on.js";
4
+ import { resolveNames } from "./names/resolve-names.js";
5
+ import { storeSchema } from "./store/store-names.js";
3
6
  import { goTrueIssuer, goTrueKeyPair } from "../gotrue/keys.js";
4
7
  import { defaultSignInPolicy } from "./sign-in-policy.js";
5
8
  import { roleDefinitions } from "./organizations/role-definitions.js";
@@ -11,6 +14,7 @@ import { resolvePersonalMail } from "../personal-mail/personal-mail-providers.js
11
14
  import { personalMailer } from "../personal-mail/personal-mailer.js";
12
15
  import { mailLinkHooks } from "../personal-mail/mail-link-hooks.js";
13
16
  import { storeNamesPlugin } from "./names/names-plugin.js";
17
+ import { plainStoreDb } from "./store/store-db.js";
14
18
  import { storeSqlOf } from "./store/store-sql.js";
15
19
  import { sqlSenderStore } from "../personal-mail/sender-store.js";
16
20
  import { mailSendersPlugin } from "../personal-mail/mail-senders-plugin.js";
@@ -52,7 +56,10 @@ import { resolveOAuthApi } from "./oauth-api.js";
52
56
  import { mcpUnusedPaths, resolveMcp } from "./mcp/mcp-plugins.js";
53
57
  import { sessionOrganizationHooks } from "./organizations/session-organization.js";
54
58
  import { resolvePersonalAccessTokens } from "./personal-access-tokens/options.js";
55
- import { personalAccessTokensPlugin } from "./personal-access-tokens/token-plugin.js";
59
+ import { personalAccessTokenPaths, personalAccessTokensPlugin } from "./personal-access-tokens/token-plugin.js";
60
+ import { keptNamesOf, pinOnce } from "./organizations/kept-organizations.js";
61
+ import { pinnedMembershipPlugin } from "./organizations/pinned-membership.js";
62
+ import { pinnedSessionHooks } from "./organizations/pinned-sessions.js";
56
63
  import { organizationPlugin } from "./organizations/organization-plugin.js";
57
64
  import { derivedSlugPlugin } from "./organizations/derived-slug.js";
58
65
  import { protobaseOrganizationPlugin } from "./organizations/protobase-plugin.js";
@@ -69,6 +76,7 @@ import { readPlatformSignIns } from "./platform-sign-in-env.js";
69
76
  import { deviceLinksPlugin } from "./platform-devices.js";
70
77
  import { hiddenAccountsPlugin, oneAccountPerProvider } from "./platform-accounts.js";
71
78
  import { fixedAuthorizationParamsPlugin } from "./platform-authorization-params.js";
79
+ import { checkDeviceSignIn } from "./device-sign-in-check.js";
72
80
  import { appSignInPolicy } from "./app-sign-in-policy.js";
73
81
  import { assertNoEndpointKeyClashes } from "./endpoint-key-clashes.js";
74
82
  import { idTokenSignInPlugin } from "./id-token-sign-in.js";
@@ -86,8 +94,6 @@ import { tokenClaims } from "./token-claims.js";
86
94
  import { twoFactorAfterFirstFactor } from "./two-factor-challenge.js";
87
95
  import { metadataField, userTable } from "./user-table.js";
88
96
  import { betterAuthNames } from "./names/better-auth-names.js";
89
- import { resolveNames } from "./names/resolve-names.js";
90
- import { storeSchema } from "./store/store-names.js";
91
97
  import { usersPlugin } from "./users/users-plugin.js";
92
98
  import { APIError } from "better-auth/api";
93
99
  import { betterAuth } from "better-auth";
@@ -121,6 +127,11 @@ const platformOrigins = () => readOrigins(globalThis.process?.env ?? {});
121
127
  const platformPasskeyDomain = () => readPasskeyDomain(globalThis.process?.env ?? {});
122
128
  const platformLockedAccounts = () => readLockedAccounts(globalThis.process?.env ?? {});
123
129
  const tokenLifetime = "15m";
130
+ const optionsNames = (options) => resolveNames({
131
+ schema: storeSchema({ options }),
132
+ tables: options.tables,
133
+ modules: modulesOf(options)
134
+ });
124
135
  /**
125
136
  * Better Auth for a single-tenant admin: sign-in with a password, an emailed code or a passkey, two-factor
126
137
  * authentication, and the sign-in policy admins set; no public sign-up unless `signUp` turns it on (every account is
@@ -151,6 +162,17 @@ const noMailer = () => ({
151
162
  refresh: mailboxOff
152
163
  });
153
164
  const organizationPaths = ["/organization/set-active", "/organization/accept-invitation"];
165
+ /**
166
+ * What a session whose user is no member of the pinned organization, such as one from before organizations were turned
167
+ * off, may not do: get an API token or a personal access token, or use an admin's powers over people, the sign-in
168
+ * policy and the registered clients, as creating or inviting someone who would then work in the default organization.
169
+ */
170
+ const pinnedGuards = (path) => path === "/token" || path === personalAccessTokenPaths.create || [
171
+ "/admin/",
172
+ "/users/",
173
+ "/policy/",
174
+ "/openid-provider/"
175
+ ].some((prefix) => path.startsWith(prefix));
154
176
  /** The reads every page load makes, which the rate limit leaves out: they check a session, never a credential. */
155
177
  const pageLoadReads = [
156
178
  "/get-session",
@@ -161,11 +183,11 @@ const pageLoadReads = [
161
183
  * The options `createAuth` gives Better Auth, with the roles, default role, mailer, operator provider and platform
162
184
  * sign-in provider already resolved.
163
185
  */
164
- const betterAuthOptions = (options, { origins = [], passkeyDomain, roles, definitions, defaultRole, appName = defaultAppName, mailer, signUpRole, signUpDomains, signUpFields = resolveSignUpFields(void 0), operator, platformSignIn = [], saml = [], organizations, mcp, api, openId, personalAccessTokens, context = noContext, signInPolicy = defaultSignInPolicy, mobile, deletion, mailSenderUse, senderVerifications: verifications, personalMailer: mailOf = noMailer, sharedSenders, lockedAccounts = [], connections, names = resolveNames({
165
- schema: storeSchema({ options }),
166
- tables: options.tables
167
- }), ...plugins }) => {
186
+ const betterAuthOptions = (options, { origins = [], passkeyDomain, roles, definitions, defaultRole, appName = defaultAppName, mailer, signUpRole, signUpDomains, signUpFields = resolveSignUpFields(void 0), operator, platformSignIn = [], saml = [], organizations, mcp, api, openId, personalAccessTokens, context = noContext, signInPolicy = defaultSignInPolicy, mobile, deletion, mailSenderUse, senderVerifications: verifications, personalMailer: mailOf = noMailer, sharedSenders, lockedAccounts = [], connections, names = optionsNames(options), pinned: off, ...plugins }) => {
168
187
  const named = betterAuthNames(names);
188
+ off?.kept;
189
+ const pin = off?.pin;
190
+ const pinned = pin && pinnedSessionHooks(pin, context);
169
191
  const mailProviders = resolvePersonalMail(options.personalMail ?? [], Object.keys(options.socialProviders ?? {}), options.encryptOAuthTokens === true);
170
192
  const connectionHooks = connections && connections.resolved.length > 0 ? connectionAccountHooks(connections.resolved, connections.events) : void 0;
171
193
  const ownProviders = (connections?.resolved ?? []).filter(({ declaration }) => "oauth" in declaration).map(({ providerId }) => providerId);
@@ -392,10 +414,13 @@ const betterAuthOptions = (options, { origins = [], passkeyDomain, roles, defini
392
414
  ...organizations && { organizations }
393
415
  }),
394
416
  ...passwordHashes.length > 0 ? [rehashPasswordsPlugin(passwordHashes)] : [],
417
+ ...off ? [pinnedMembershipPlugin(off.kept, off.pin, pinnedGuards)] : [],
395
418
  ...personalAccessTokens ? [personalAccessTokensPlugin({
396
419
  options: personalAccessTokens,
397
420
  definitions,
398
- names: named
421
+ names: named,
422
+ organizations: Boolean(organizations),
423
+ ...off && { pinned: off }
399
424
  })] : [],
400
425
  ...mailProviders.length > 0 ? [mailSendersPlugin(mailProviders, named, mailOf, mailSenderUse, verifications, sharedSenders)] : [],
401
426
  ...mcp ? loaded(plugins.mcpAuthPlugins, "mcp")({
@@ -431,6 +456,7 @@ const betterAuthOptions = (options, { origins = [], passkeyDomain, roles, defini
431
456
  user: {
432
457
  create: {
433
458
  before: async (user, context) => {
459
+ await pinned?.user.before(user, context);
434
460
  const given = String(user.role ?? "").split(",").map((name) => name.trim()).filter(Boolean);
435
461
  const unknown = given.find((name) => !roles.includes(name));
436
462
  if (given.length === 0 || unknown !== void 0) throw new APIError("BAD_REQUEST", { message: `Choose a role for the new user: ${roles.join(", ")}` });
@@ -448,11 +474,14 @@ const betterAuthOptions = (options, { origins = [], passkeyDomain, roles, defini
448
474
  emailVerified: true
449
475
  } : withId, /* @__PURE__ */ new Date()) };
450
476
  },
451
- ...options.onUserCreated && { after: options.onUserCreated }
477
+ ...pinned ? { after: async (user, context) => {
478
+ await pinned.user.after(user);
479
+ await options.onUserCreated?.(user, context);
480
+ } } : options.onUserCreated && { after: options.onUserCreated }
452
481
  },
453
482
  update: { before: async (user) => ({ data: confirmedOnUpdate(user, /* @__PURE__ */ new Date()) }) }
454
483
  },
455
- session: refusingConnectionSessions(withEndedReplaced(organizations ? sessionOrganizationHooks(context) : {}), connectionHooks?.session.create?.before),
484
+ session: refusingConnectionSessions(refusingConnectionSessions(withEndedReplaced(organizations ? sessionOrganizationHooks(context) : {}), connectionHooks?.session.create?.before), pinned?.session),
456
485
  account: ((mail) => connectionHooks ? bothAccountHooks(mail, connectionHooks.account) : mail)(bothAccountHooks(oneAccountPerProvider(singleSubject), mailLinkHooks(mailProviders)))
457
486
  },
458
487
  rateLimit: {
@@ -547,6 +576,7 @@ const createAuth = (options, plugins = {}) => {
547
576
  const signInSettings = options.signInProviders ?? platformSignInSettings();
548
577
  const socialProviders = Object.keys(options.socialProviders ?? {});
549
578
  const platformSignIn = platformSignInFor(resolvePlatformSignIns(signInSettings, options.baseURL), socialProviders);
579
+ checkDeviceSignIn(platformSignIn, modulesOf(options));
550
580
  const saml = resolveSamlProviders(options.sso?.saml ?? [], [...socialProviders, ...platformSignIn.map(({ provider }) => provider)]);
551
581
  const personalMail = resolvePersonalMail(options.personalMail ?? [], socialProviders, options.encryptOAuthTokens === true);
552
582
  if (Object.keys(options.connections ?? {}).length > 0 && options.encryptOAuthTokens !== true) throw new Error("auth.connections: the connected accounts' tokens would be stored in plain text; turn on auth.encryptOAuthTokens");
@@ -583,13 +613,16 @@ const createAuth = (options, plugins = {}) => {
583
613
  context
584
614
  }));
585
615
  const lockedAccounts = platformLockedAccounts();
586
- const names = resolveNames({
587
- schema: storeSchema({ options }),
588
- tables: options.tables
589
- });
616
+ const names = optionsNames(options);
617
+ const kept = options.organizationsOff && !options.organizations ? keptNamesOf(names) : void 0;
618
+ const pin = kept && pinOnce(plainStoreDb({ options }), kept, options.organizationsOff);
590
619
  const authOptions = betterAuthOptions(options, {
591
620
  ...plugins,
592
621
  names,
622
+ ...kept && pin && { pinned: {
623
+ kept,
624
+ pin
625
+ } },
593
626
  mobile,
594
627
  deletion,
595
628
  mailSenderUse: senderUse,
@@ -660,6 +693,14 @@ const createAuth = (options, plugins = {}) => {
660
693
  roles,
661
694
  roleDefinitions: definitions,
662
695
  organizations,
696
+ /**
697
+ * The organization everyone works in while organizations are off after being on, `undefined` while they are on or
698
+ * were never on; read from the store once (`pinOnce`), and refused with a tenant other than its id, which the
699
+ * server's startup checks ask first.
700
+ */
701
+ pinnedOrganization: pin ?? (async () => void 0),
702
+ /** The tables of organizations that sign-in reads while they are off, when the store holds them only after they were on. */
703
+ keptTables: kept ? [kept.table("member").name] : [],
663
704
  defaultRole,
664
705
  /** New users get their ids from `generateUserId` instead of Better Auth's random text. */
665
706
  generatesUserIds: Boolean(options.generateUserId),
@@ -0,0 +1,13 @@
1
+ //#region src/better-auth/device-sign-in-check.ts
2
+ /**
3
+ * Refuses a platform sign-in provider that signs in devices while their module is off, as the store then has no tables
4
+ * for them: only one from the environment can, since one of `signInProviders` with `devices: true` turns the module on.
5
+ */
6
+ const checkDeviceSignIn = (providers, modules) => {
7
+ if (modules.includes("platform_devices")) return;
8
+ const device = providers.find(({ devices }) => devices);
9
+ if (!device) return;
10
+ throw new Error(`The platform sign-in provider "${device.provider}" signs in devices while auth.signInDevices is off: turn on auth.signInDevices in protobase.config.ts, then write its migration with \`protobase migration\` and apply it`);
11
+ };
12
+ //#endregion
13
+ export { checkDeviceSignIn };
@@ -8,14 +8,27 @@ export type ColumnDeclaration = {
8
8
  field: string;
9
9
  attribute?: Omit<DBFieldAttribute, 'fieldName'>;
10
10
  };
11
- export type TableDeclaration = {
11
+ /**
12
+ * What an index of a table whose rows belong to an organization serves: lookups within one organization, which lead
13
+ * with its `organization_id`, or across them, such as a lookup key or a secret, which stays unique app-wide.
14
+ */
15
+ export type IndexScope = 'organization' | 'global';
16
+ type TableBase = {
12
17
  /** Better Auth's model the table holds; none for a table only Protobase reads, such as the record of migrations. */
13
18
  model?: string;
14
- /** Whether a row belongs to one organization or to the whole app. */
15
- scope: 'global' | 'organization';
16
19
  /** Each column but `id`, which keeps its name, by internal name. */
17
20
  columns: Record<string, ColumnDeclaration>;
18
- /** The indexes Protobase makes, by internal name, each starting with the table's internal name and `_`. */
19
- indexes?: string[];
20
21
  };
22
+ /**
23
+ * A table: whether a row belongs to the whole app or to one organization, and the indexes Protobase makes, by
24
+ * internal name, each starting with the table's internal name and `_`; each index of a table of an organization's
25
+ * rows says what it serves.
26
+ */
27
+ export type TableDeclaration = TableBase & ({
28
+ scope: 'global';
29
+ indexes?: string[];
30
+ } | {
31
+ scope: 'organization';
32
+ indexes?: Record<string, IndexScope>;
33
+ });
21
34
  //#endregion
@@ -6,5 +6,7 @@ const own = (name, attribute) => ({
6
6
  field: name,
7
7
  attribute
8
8
  });
9
+ /** The indexes a table declares with what each serves: every index of a table of the whole app's rows serves it whole. */
10
+ const indexScopes = (table) => table.scope === "organization" ? table.indexes ?? {} : Object.fromEntries((table.indexes ?? []).map((index) => [index, "global"]));
9
11
  //#endregion
10
- export { field, own };
12
+ export { field, indexScopes, own };
@@ -116,6 +116,15 @@ const auth = {
116
116
  name: field("name"),
117
117
  applied_at: field("appliedAt")
118
118
  }
119
+ },
120
+ auth_steps: {
121
+ scope: "global",
122
+ columns: {
123
+ module: field("module"),
124
+ step: field("step"),
125
+ target: field("target"),
126
+ applied_at: field("appliedAt")
127
+ }
119
128
  }
120
129
  }
121
130
  };