@protobase/server 0.129.1 → 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 +11 -7
  56. package/dist/better-auth/store/offline/baseline-store.js +15 -12
  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 -7
  62. package/dist/better-auth/store/offline/offline-steps.js +29 -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 +7 -1
  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 +26 -10
  126. package/dist/internal.js +22 -8
  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,9 +1,12 @@
1
1
  import { membershipRoles } from "./role-definitions.js";
2
2
  import { parseAppRoles } from "./app-roles.js";
3
+ import { acrossOrganizations, inOrganization, inSignInScope } from "../../organization-scope/sign-in-organization.js";
3
4
  import { findMember, isOwner, organizationRoleOf, setAppRoles } from "./store.js";
4
5
  import { storeSqlOf } from "../store/store-sql.js";
5
6
  import { mayBeId } from "../store/store-reads.js";
6
7
  import { pageOf } from "../store/page-of.js";
8
+ import { builderName, rowsIn } from "./host-scope.js";
9
+ import { isEveryOrganization } from "@protobase/query";
7
10
  import { sql } from "kysely";
8
11
  //#region src/better-auth/organizations/host.ts
9
12
  const contextOf = async (auth) => await auth.$context;
@@ -31,11 +34,11 @@ const userByEmail = async (auth, email) => {
31
34
  if (!user) throw new Error(`No user with email ${email}`);
32
35
  return user.user;
33
36
  };
34
- /** An organization by its id or slug. */
35
- const findOrganizationByKey = async (auth, key) => {
37
+ /** An organization by its id or slug; null when there is none. */
38
+ const organizationByKey = async (auth, key) => {
36
39
  const context = await contextOf(auth);
37
40
  const { adapter } = context;
38
- const found = (mayBeId(context.options, key) ? await adapter.findOne({
41
+ return (mayBeId(context.options, key) ? await adapter.findOne({
39
42
  model: "organization",
40
43
  where: [{
41
44
  field: "id",
@@ -48,6 +51,10 @@ const findOrganizationByKey = async (auth, key) => {
48
51
  value: key
49
52
  }]
50
53
  });
54
+ };
55
+ /** An organization by its id or slug; refused when there is none. */
56
+ const findOrganizationByKey = async (auth, key) => {
57
+ const found = await organizationByKey(auth, key);
51
58
  if (!found) throw new Error(`No organization "${key}"`);
52
59
  return found;
53
60
  };
@@ -71,14 +78,25 @@ const createOrganization = async (auth, input) => {
71
78
  })) throw new Error(`An organization with slug "${input.slug}" exists already`);
72
79
  const now = /* @__PURE__ */ new Date();
73
80
  const id = input.id ?? await settings.generateId();
81
+ return inOrganization(id, () => createWithOwner(auth, {
82
+ id,
83
+ name: input.name.trim(),
84
+ slug: input.slug,
85
+ owner: owner.id,
86
+ createdAt: now
87
+ }));
88
+ };
89
+ const createWithOwner = async (auth, { id, name, slug, owner, createdAt }) => {
90
+ const settings = settingsOf(auth);
91
+ const { adapter } = await contextOf(auth);
74
92
  const { organization, member } = await adapter.transaction(async (trx) => {
75
93
  const organization = await trx.create({
76
94
  model: "organization",
77
95
  data: {
78
96
  id,
79
- name: input.name.trim(),
80
- slug: input.slug,
81
- createdAt: now
97
+ name,
98
+ slug,
99
+ createdAt
82
100
  },
83
101
  forceAllowId: true
84
102
  });
@@ -88,10 +106,10 @@ const createOrganization = async (auth, input) => {
88
106
  model: "member",
89
107
  data: {
90
108
  organizationId: organization.id,
91
- userId: owner.id,
109
+ userId: owner,
92
110
  role: "owner",
93
111
  appRoles: settings.creatorAppRoles,
94
- createdAt: now
112
+ createdAt
95
113
  }
96
114
  })
97
115
  };
@@ -120,18 +138,30 @@ const addMember = async (auth, input) => {
120
138
  })) throw new Error(`${input.email} is a member of ${organization.slug} already`);
121
139
  const role = checkOrganizationRole(input.role ?? "member");
122
140
  const appRoles = checkAppRoles(auth, input.appRoles ?? []);
123
- return adapter.create({
141
+ const data = {
142
+ organizationId: organization.id,
143
+ userId: user.id,
144
+ role,
145
+ appRoles,
146
+ createdAt: /* @__PURE__ */ new Date()
147
+ };
148
+ return inOrganization(organization.id, () => adapter.create({
124
149
  model: "member",
125
- data: {
126
- organizationId: organization.id,
127
- userId: user.id,
128
- role,
129
- appRoles,
130
- createdAt: /* @__PURE__ */ new Date()
131
- }
132
- });
150
+ data
151
+ }));
133
152
  };
134
- const memberOrThrow = async (auth, organizationKey, email) => {
153
+ /** Whether someone with `email` has an account and is a member of the organization with id `organizationId`. */
154
+ const isMemberByEmail = async (auth, organizationId, email) => {
155
+ const { adapter, internalAdapter } = await contextOf(auth);
156
+ const found = await internalAdapter.findUserByEmail(email.toLowerCase());
157
+ if (!found) return false;
158
+ return await findMember(adapter, {
159
+ organizationId,
160
+ userId: found.user.id
161
+ }) !== void 0;
162
+ };
163
+ /** The membership of the user with `email` in the organization with id or slug `organizationKey`; refused when there is none. */
164
+ const requireMember = async (auth, organizationKey, email) => {
135
165
  const organization = await findOrganizationByKey(auth, organizationKey);
136
166
  const user = await userByEmail(auth, email);
137
167
  const member = await findMember((await contextOf(auth)).adapter, {
@@ -148,58 +178,66 @@ const refuseLastOwner = async (auth, member, action) => {
148
178
  if (organizationRoleOf(member) !== "owner") return;
149
179
  const store = storeSqlOf(await contextOf(auth));
150
180
  const members = store.table("member");
151
- const { organization_id, role } = members.columns;
152
- const { rows } = await sql`select exists (select from ${members}
153
- where ${organization_id} = ${member.organizationId} and id <> ${member.id} and ${isOwner(sql`${role}`)}) as found`.execute(store.db);
181
+ const { role } = members.columns;
182
+ const { rows } = await sql`select exists (select from ${rowsIn(store, member.organizationId, members)} as m
183
+ where id <> ${member.id} and ${isOwner(sql`m.${role}`)}) as found`.execute(store.db);
154
184
  if (!rows[0].found) throw new Error(`Cannot ${action} the last owner`);
155
185
  };
156
186
  /** Changes a member's organization role, app roles, or both. */
157
187
  const setMemberRoles = async (auth, input) => {
158
- const { member } = await memberOrThrow(auth, input.organization, input.email);
188
+ const { member } = await requireMember(auth, input.organization, input.email);
159
189
  const { adapter } = await contextOf(auth);
160
- if (input.role !== void 0) {
161
- const role = checkOrganizationRole(input.role);
162
- if (role !== "owner") await refuseLastOwner(auth, member, "demote");
163
- await adapter.update({
164
- model: "member",
165
- where: [{
166
- field: "id",
167
- value: member.id
168
- }],
169
- update: { role }
190
+ return inOrganization(member.organizationId, async () => {
191
+ if (input.role !== void 0) {
192
+ const role = checkOrganizationRole(input.role);
193
+ if (role !== "owner") await refuseLastOwner(auth, member, "demote");
194
+ await adapter.update({
195
+ model: "member",
196
+ where: [{
197
+ field: "id",
198
+ value: member.id
199
+ }],
200
+ update: { role }
201
+ });
202
+ }
203
+ if (input.appRoles !== void 0) await setAppRoles(adapter, member, checkAppRoles(auth, input.appRoles));
204
+ return findMember(adapter, {
205
+ organizationId: member.organizationId,
206
+ userId: member.userId
170
207
  });
171
- }
172
- if (input.appRoles !== void 0) await setAppRoles(adapter, member.id, checkAppRoles(auth, input.appRoles));
173
- return findMember(adapter, {
174
- organizationId: member.organizationId,
175
- userId: member.userId
176
208
  });
177
209
  };
178
210
  /** Removes a member; refuses the last owner. */
179
211
  const removeMember = async (auth, input) => {
180
- const { member } = await memberOrThrow(auth, input.organization, input.email);
181
- await refuseLastOwner(auth, member, "remove");
182
- await (await contextOf(auth)).adapter.delete({
183
- model: "member",
184
- where: [{
185
- field: "id",
186
- value: member.id
187
- }]
212
+ const { member } = await requireMember(auth, input.organization, input.email);
213
+ const { adapter } = await contextOf(auth);
214
+ await inOrganization(member.organizationId, async () => {
215
+ await refuseLastOwner(auth, member, "remove");
216
+ await adapter.delete({
217
+ model: "member",
218
+ where: [{
219
+ field: "id",
220
+ value: member.id
221
+ }]
222
+ });
188
223
  });
189
224
  };
190
225
  /** The organizations a page of `listOrganizations` holds when it is not told. */
191
226
  const organizationsPageSize = 100;
192
227
  /**
193
- * A page of the organizations, oldest first, each with its members' emails and roles, oldest member first: `size` of
194
- * them from `after`, the `next` of the page before, as Postgres pages them, and their members in one join.
228
+ * A page of the organizations `scope` holds, oldest first, each with its members' emails and roles, oldest member
229
+ * first: `size` of them from `after`, the `next` of the page before, as Postgres pages them, and their members in one
230
+ * join.
195
231
  */
196
- const listOrganizations = async (auth, { after, size = 100 } = {}) => {
232
+ const listOrganizations = (auth, scope, page = {}) => inSignInScope(scope, () => organizationsPage(auth, scope, page));
233
+ const organizationsPage = async (auth, scope, { after, size = 100 }) => {
197
234
  settingsOf(auth);
198
235
  const store = storeSqlOf(await contextOf(auth));
199
236
  const organization = store.table("organization");
200
237
  const o = organization.columns;
238
+ const from = isEveryOrganization(scope) ? organization : sql`(select * from ${organization} where id = ${scope}) as o`;
201
239
  const page = await pageOf(store, {
202
- from: organization,
240
+ from,
203
241
  select: {
204
242
  id: sql`id`,
205
243
  name: o.name,
@@ -214,8 +252,8 @@ const listOrganizations = async (auth, { after, size = 100 } = {}) => {
214
252
  const m = store.table("member").columns;
215
253
  const { rows: members } = await sql`select m.${m.organization_id} as "organizationId",
216
254
  coalesce(u.${user.columns.email}, m.${m.user_id}::text) as email, m.${m.role} as role, m.${m.app_roles} as "appRoles"
217
- from ${store.table("member")} m left join ${user} u on u.id = m.${m.user_id}
218
- where m.${m.organization_id} = any(${ids}) order by m.${m.created_at}, m.id`.execute(store.db);
255
+ from ${rowsIn(store, scope, store.table("member"))} as m left join ${user} u on u.id = m.${m.user_id}
256
+ where m.${m.organization_id} = any(${ids}) order by m.${m.organization_id}, m.${m.created_at}, m.id`.execute(store.db);
219
257
  const membersOf = /* @__PURE__ */ new Map();
220
258
  for (const member of members) {
221
259
  const held = membersOf.get(member.organizationId);
@@ -244,7 +282,8 @@ const listOrganizations = async (auth, { after, size = 100 } = {}) => {
244
282
  * the first user of an app whose organizations were made before anyone could own them, such as by its seed. Returns
245
283
  * how many.
246
284
  */
247
- const ownOrganizationsWithoutMembers = async (auth, userId) => {
285
+ const ownOrganizationsWithoutMembers = (auth, userId) => acrossOrganizations("the first user owns every organization without members", () => ownEmptyOrganizations(auth, userId));
286
+ const ownEmptyOrganizations = async (auth, userId) => {
248
287
  const settings = settingsOf(auth);
249
288
  const store = storeSqlOf(await contextOf(auth));
250
289
  const member = store.table("member");
@@ -256,19 +295,18 @@ const ownOrganizationsWithoutMembers = async (auth, userId) => {
256
295
  return rows.length;
257
296
  };
258
297
  /**
259
- * Gives an app role to every owner of every organization who lacks it, in one statement, for a role the project adds
260
- * once organizations exist. Returns how many owners got it.
298
+ * Gives an app role to every owner in `scope` who lacks it, in one statement, for a role the project adds once
299
+ * organizations exist. Returns how many owners got it.
261
300
  */
262
- const addAppRoleToOwners = async (auth, appRole) => {
301
+ const addAppRoleToOwners = (auth, scope, appRole) => inSignInScope(scope, () => giveOwnersAppRole(auth, scope, appRole));
302
+ const giveOwnersAppRole = async (auth, scope, appRole) => {
263
303
  checkAppRoles(auth, [appRole]);
264
304
  const store = storeSqlOf(await contextOf(auth));
265
305
  const member = store.table("member");
266
- const { app_roles, role } = member.columns;
306
+ const { app_roles, organization_id, role } = member.columns;
267
307
  const held = sql`coalesce(${app_roles}, '[]'::jsonb)`;
268
- const { rows } = await sql`update ${member} set ${app_roles} = ${held} || jsonb_build_array(${appRole}::text)
269
- where ${isOwner(sql`${role}`)} and not ${held} @> jsonb_build_array(${appRole}::text)
270
- returning id`.execute(store.db);
271
- return rows.length;
308
+ const update = store.db.updateTable(builderName(member)).set({ [app_roles.name]: sql`${held} || jsonb_build_array(${appRole}::text)` }).where(sql`${isOwner(sql`${role}`)} and not ${held} @> jsonb_build_array(${appRole}::text)`);
309
+ return (await (isEveryOrganization(scope) ? update : update.where(organization_id.name, "=", scope)).returning("id").execute()).length;
272
310
  };
273
311
  //#endregion
274
- export { addAppRoleToOwners, addMember, createOrganization, findOrganizationByKey, listOrganizations, organizationsPageSize, ownOrganizationsWithoutMembers, removeMember, setMemberRoles };
312
+ export { addAppRoleToOwners, addMember, createOrganization, findOrganizationByKey, isMemberByEmail, listOrganizations, organizationByKey, organizationsPageSize, ownOrganizationsWithoutMembers, removeMember, setMemberRoles };
@@ -0,0 +1,21 @@
1
+ import { ResolvedNames } from "../names/resolve-names.js";
2
+ import { TenantValue } from "../../types.js";
3
+ import { DefaultOrganization } from "./options.js";
4
+ import { Kysely } from "kysely";
5
+ //#region src/better-auth/organizations/kept-organizations.d.ts
6
+ /** What the config says of organizations while they are off: the default organization, and the tenant it is pinned by. */
7
+ export type OrganizationsOff = {
8
+ default?: DefaultOrganization;
9
+ existingUsersRole?: string;
10
+ tenant?: TenantValue;
11
+ };
12
+ /** The organization everyone works in while organizations are off after being on, and the app role people who join then hold there. */
13
+ export type PinnedOrganization = {
14
+ id: string;
15
+ existingUsersRole?: string;
16
+ };
17
+ /** The store's names with organizations on, as the tables they kept are named. */
18
+ export declare const keptNames: (names: ResolvedNames) => ResolvedNames;
19
+ /** The organization pinned while organizations are off after being on, read from the store (`pinnedOrganization`). */
20
+ export type PinRead = () => Promise<PinnedOrganization | undefined>;
21
+ //#endregion
@@ -0,0 +1,62 @@
1
+ import { allModules } from "../names/modules-on.js";
2
+ import { NameClash, resolveNames } from "../names/resolve-names.js";
3
+ import { sql } from "kysely";
4
+ //#region src/better-auth/organizations/kept-organizations.ts
5
+ /** The store's names with organizations on, as the tables they kept are named. */
6
+ const keptNames = (names) => resolveNames({
7
+ ...names.input,
8
+ modules: allModules.filter((module) => module === "organizations" || names.modules.includes(module))
9
+ });
10
+ /**
11
+ * `keptNames`, or `undefined` when a name the config gives clashes with one of organizations', such as a user table
12
+ * named `member`: organizations were never on under these names, so the store keeps nothing of theirs.
13
+ */
14
+ const keptNamesOf = (names) => {
15
+ try {
16
+ return keptNames(names);
17
+ } catch (error) {
18
+ if (error instanceof NameClash) return;
19
+ throw error;
20
+ }
21
+ };
22
+ /** Why the server refuses to start once it finds the store holds organizations, or `undefined` when the config pins the default organization. */
23
+ const pinRefusal = (off) => {
24
+ if (!off.default) return "The auth store keeps the tables of organizations, which were on: give auth.organizations.default the organization that stands in for every one while they are off";
25
+ if (off.tenant !== off.default.id) return `Organizations were on and are off, so only the default organization works: set authenticate.tenant to its id, ${JSON.stringify(off.default.id)}, which is ${off.tenant === void 0 ? "unset" : JSON.stringify(off.tenant)}`;
26
+ };
27
+ /**
28
+ * The organization pinned while organizations are off after being on, which the store says by still holding
29
+ * organizations, its tables named as `kept` names them: `undefined` when it has no organization table, or no row in it, as a store from before organizations
30
+ * were a module of their own has, which made their tables whether they were on or not. A store that holds one is
31
+ * refused without `default`, or with `tenant` other than its id (`pinRefusal`). `db` is the store's database without the
32
+ * app's query plugins (`plainStoreDb`), as the tables are named in the database.
33
+ */
34
+ const pinnedOrganization = async (db, kept, off) => {
35
+ const organization = kept.table("organization");
36
+ const [table] = (await sql`select to_regclass(${String(organization)}) is not null as kept`.execute(db)).rows;
37
+ if (!table?.kept) return;
38
+ const [rows] = (await sql`select exists (select from ${organization}) as held`.execute(db)).rows;
39
+ if (!rows?.held) return;
40
+ const refusal = pinRefusal(off);
41
+ if (refusal) throw new Error(refusal);
42
+ return {
43
+ id: off.default.id,
44
+ ...off.existingUsersRole !== void 0 && { existingUsersRole: off.existingUsersRole }
45
+ };
46
+ };
47
+ /**
48
+ * `pinnedOrganization`, read once its first caller asks, such as the server's startup checks, and kept: the store's
49
+ * tables only change with a migration, which the server restarts after. A failed read is not kept, so the next asks again.
50
+ */
51
+ const pinOnce = (db, kept, off) => {
52
+ let read;
53
+ return () => {
54
+ read ??= pinnedOrganization(db, kept, off).catch((error) => {
55
+ read = void 0;
56
+ throw error;
57
+ });
58
+ return read;
59
+ };
60
+ };
61
+ //#endregion
62
+ export { keptNames, keptNamesOf, pinOnce, pinRefusal, pinnedOrganization };
@@ -1,5 +1,6 @@
1
1
  import "./role-definitions.js";
2
2
  import { checkAppRoleChange, effectiveRoles, globalRoles } from "./app-roles.js";
3
+ import { inOrganization } from "../../organization-scope/sign-in-organization.js";
3
4
  import { findMember, findMemberById, findOrganization, organizationRoleOf, setAppRoles } from "./store.js";
4
5
  import * as z$1 from "zod";
5
6
  import { APIError, createAuthEndpoint, sessionMiddleware } from "better-auth/api";
@@ -50,7 +51,7 @@ const memberEndpoints = ({ resolved }) => ({
50
51
  code: refusal.code,
51
52
  message: refusal.message
52
53
  });
53
- await setAppRoles(adapter, target.id, after);
54
+ await setAppRoles(adapter, target, after);
54
55
  return ctx.json({ member: {
55
56
  ...target,
56
57
  appRoles: after
@@ -83,7 +84,7 @@ const memberEndpoints = ({ resolved }) => ({
83
84
  code: "ALREADY_THE_OWNER",
84
85
  message: "Choose another member to hand the organization over to."
85
86
  });
86
- await adapter.transaction(async (trx) => {
87
+ await inOrganization(target.organizationId, () => adapter.transaction(async (trx) => {
87
88
  await trx.update({
88
89
  model: "member",
89
90
  where: [{
@@ -100,7 +101,7 @@ const memberEndpoints = ({ resolved }) => ({
100
101
  }],
101
102
  update: { role: ctx.body.keepAs ?? "admin" }
102
103
  });
103
- });
104
+ }));
104
105
  return ctx.json({ owner: target.id });
105
106
  }),
106
107
  /**
@@ -8,7 +8,20 @@ export type OrganizationNames = {
8
8
  singular: string;
9
9
  plural: string;
10
10
  };
11
+ /** The organization a store's rows belong to while organizations are off, and the first one when they turn on. */
12
+ export type DefaultOrganization = {
13
+ id: string;
14
+ name: string;
15
+ slug: string;
16
+ };
11
17
  export type OrganizationsOptions = {
18
+ /**
19
+ * The organization that stands in for every organization while they are off, which `protobase migration` makes when
20
+ * they turn on and gives the rows of an organization that were there already. Required once they were ever on.
21
+ */
22
+ default?: DefaultOrganization;
23
+ /** The app role each user there already holds in `default` when organizations turn on the first time. */
24
+ existingUsersRole?: string;
12
25
  /** The app roles an organization's creator holds there: `'all'` (default), every role a member can hold, or a list. */
13
26
  creatorAppRoles?: 'all' | string[];
14
27
  /** Who may create organizations: `'admins'` (default), superusers only, or `'everyone'` signed in. */
@@ -54,4 +67,6 @@ export type ResolvedOrganizations = {
54
67
  invitationUrl?: string;
55
68
  options: OrganizationsOptions;
56
69
  };
70
+ /** Whether the config's `auth.organizations` turns organizations on; refuses another shape, such as `true`. */
71
+ export declare const organizationsEnabled: (organizations: unknown) => boolean;
57
72
  //#endregion
@@ -1,5 +1,21 @@
1
1
  import { membershipRoles } from "./role-definitions.js";
2
2
  //#region src/better-auth/organizations/options.ts
3
+ /** Whether the config's `auth.organizations` turns organizations on; refuses another shape, such as `true`. */
4
+ const organizationsEnabled = (organizations) => {
5
+ if (organizations === void 0) return false;
6
+ const enabled = typeof organizations === "object" && organizations !== null ? organizations.enabled : void 0;
7
+ if (typeof enabled !== "boolean") throw new Error("auth.organizations takes { enabled: true, default: { id, name, slug }, existingUsersRole }; set enabled: false to turn them off");
8
+ return enabled;
9
+ };
10
+ /** Refuses a default organization without its id, name or slug. */
11
+ const checkDefaultOrganization = (organization) => {
12
+ const missing = [
13
+ "id",
14
+ "name",
15
+ "slug"
16
+ ].filter((key) => typeof organization[key] !== "string" || organization[key].trim() === "");
17
+ if (missing.length > 0) throw new Error(`organizations.default needs ${missing.join(", ")}, such as { id: 'main', name: 'Main', slug: 'main' }`);
18
+ };
3
19
  const resolveOrganizations = (options, definitions) => {
4
20
  const holdable = membershipRoles(definitions);
5
21
  const creatorAppRoles = options.creatorAppRoles === void 0 || options.creatorAppRoles === "all" ? holdable : options.creatorAppRoles;
@@ -8,6 +24,8 @@ const resolveOrganizations = (options, definitions) => {
8
24
  const names = options.names;
9
25
  if (names !== void 0 && (typeof names.singular !== "string" || names.singular.trim() === "" || typeof names.plural !== "string" || names.plural.trim() === "")) throw new Error("organizations.names needs a singular and a plural, such as { singular: \"Workspace\", plural: \"Workspaces\" }");
10
26
  if (options.createDescription !== void 0 && options.createDescription.trim() === "") throw new Error("organizations.createDescription cannot be empty");
27
+ if (options.default !== void 0) checkDefaultOrganization(options.default);
28
+ if (options.existingUsersRole !== void 0 && !holdable.includes(options.existingUsersRole)) throw new Error(`organizations.existingUsersRole is "${options.existingUsersRole}", which a member cannot hold: ${holdable.join(", ")}`);
11
29
  const days = options.invitationDays ?? 7;
12
30
  if (!(days > 0)) throw new Error("invitationDays must be more than 0");
13
31
  return {
@@ -23,4 +41,4 @@ const resolveOrganizations = (options, definitions) => {
23
41
  };
24
42
  };
25
43
  //#endregion
26
- export { resolveOrganizations };
44
+ export { checkDefaultOrganization, organizationsEnabled, resolveOrganizations };
@@ -1,3 +1,4 @@
1
+ import { acrossOrganizations } from "../../organization-scope/sign-in-organization.js";
1
2
  import { findMember } from "./store.js";
2
3
  import { storeSqlOf } from "../store/store-sql.js";
3
4
  import { sql } from "kysely";
@@ -32,8 +33,8 @@ const peopleEndpoint = createAuthEndpoint("/organization/people", {
32
33
  const store = storeSqlOf(ctx.context);
33
34
  const users = store.table("user");
34
35
  const m = store.table("member").columns;
35
- const { rows } = await sql`select u.id, u.${users.columns.name} as name, u.${users.columns.image} as image
36
- from ${users} u where exists (select from ${store.table("member")} m where m.${m.user_id} = u.id and m.${m.organization_id} = ${organizationId})`.execute(store.db);
36
+ const { rows } = await acrossOrganizations("users are read with their membership of the session's organization, which the SQL names itself", () => sql`select u.id, u.${users.columns.name} as name, u.${users.columns.image} as image
37
+ from ${users} u where exists (select from ${store.table("member")} m where m.${m.user_id} = u.id and m.${m.organization_id} = ${organizationId})`.execute(store.db));
37
38
  return ctx.json({ people: peopleOf(rows) });
38
39
  });
39
40
  //#endregion
@@ -0,0 +1,81 @@
1
+ import { findMember } from "./store.js";
2
+ import { createAuthMiddleware, getSessionFromCtx } from "better-auth/api";
3
+ import { APIError as APIError$1, BASE_ERROR_CODES } from "@better-auth/core/error";
4
+ //#region src/better-auth/organizations/pinned-membership.ts
5
+ /** The answer to someone who is no member of the pinned organization, the same as to a wrong password. */
6
+ const notPinnedMember = () => APIError$1.from("UNAUTHORIZED", BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD);
7
+ /**
8
+ * The member table organizations kept, as Better Auth's `member` model, so the pinned organization's members are read
9
+ * and written through the adapter of the request, in its transaction; `kept` names it as organizations on would. While
10
+ * `pin` reads an organization, a session whose user is no member of it, such as one from before organizations were
11
+ * turned off, is refused on each path `guarded` takes, such as those that issue credentials.
12
+ */
13
+ const pinnedMembershipPlugin = (kept, pin, guarded) => {
14
+ const member = kept.table("member");
15
+ const field = (name, attribute) => ({
16
+ ...attribute,
17
+ fieldName: member.fields[name].name
18
+ });
19
+ return {
20
+ id: "protobase-pinned-membership",
21
+ schema: { member: {
22
+ modelName: member.name,
23
+ fields: {
24
+ organizationId: field("organizationId", {
25
+ type: "string",
26
+ required: true
27
+ }),
28
+ userId: field("userId", {
29
+ type: "string",
30
+ required: true
31
+ }),
32
+ role: field("role", {
33
+ type: "string",
34
+ required: true
35
+ }),
36
+ createdAt: field("createdAt", {
37
+ type: "date",
38
+ required: true
39
+ }),
40
+ appRoles: field("appRoles", {
41
+ type: "string[]",
42
+ required: false
43
+ })
44
+ }
45
+ } },
46
+ hooks: { before: [{
47
+ matcher: (context) => context.path !== void 0 && guarded(context.path),
48
+ handler: createAuthMiddleware(async (ctx) => {
49
+ const pinned = await pin();
50
+ if (!pinned) return;
51
+ const session = await getSessionFromCtx(ctx);
52
+ if (!session) return;
53
+ if (!await isPinnedMember(ctx.context.adapter, pinned, session.user.id)) throw notPinnedMember();
54
+ })
55
+ }] }
56
+ };
57
+ };
58
+ /** Whether the user is a member of the pinned organization: `organization_id = pin and user_id = user`. */
59
+ const isPinnedMember = async (adapter, pin, userId) => await findMember(adapter, {
60
+ organizationId: pin.id,
61
+ userId
62
+ }) !== void 0;
63
+ /**
64
+ * Makes someone who joins while organizations are off a member of the pinned organization, as the users there already
65
+ * became one as organizations turned on: the organization role `member`, and `existingUsersRole` as their app role.
66
+ */
67
+ const joinPinned = async (adapter, pin, userId) => {
68
+ if (await isPinnedMember(adapter, pin, userId)) return;
69
+ await adapter.create({
70
+ model: "member",
71
+ data: {
72
+ organizationId: pin.id,
73
+ userId,
74
+ role: "member",
75
+ createdAt: /* @__PURE__ */ new Date(),
76
+ appRoles: pin.existingUsersRole === void 0 ? [] : [pin.existingUsersRole]
77
+ }
78
+ });
79
+ };
80
+ //#endregion
81
+ export { isPinnedMember, joinPinned, notPinnedMember, pinnedMembershipPlugin };
@@ -0,0 +1,46 @@
1
+ import { isPinnedMember, joinPinned, notPinnedMember } from "./pinned-membership.js";
2
+ import { getCurrentAdapter } from "@better-auth/core/context";
3
+ //#region src/better-auth/organizations/pinned-sessions.ts
4
+ /**
5
+ * The user and session hooks that keep sign-in to the pinned organization, while `pin` reads one. Every way of signing
6
+ * in ends in a session, which is refused to a user who is no member of it. A new user joins it once their row is
7
+ * committed; sign-up may make their session in the same transaction, before that, so a user the same request created
8
+ * gets it.
9
+ */
10
+ const pinnedSessionHooks = (pin, context) => {
11
+ const created = /* @__PURE__ */ new WeakMap();
12
+ const createdHere = (request, email) => request ? created.get(request)?.has(email) ?? false : false;
13
+ return {
14
+ user: {
15
+ before: async (user, request) => {
16
+ if (!request) return;
17
+ const emails = created.get(request) ?? /* @__PURE__ */ new Set();
18
+ emails.add(user.email.toLowerCase());
19
+ created.set(request, emails);
20
+ },
21
+ after: async (user) => {
22
+ const { adapter, internalAdapter } = await context();
23
+ const join = async () => {
24
+ const pinned = await pin();
25
+ if (pinned) await joinPinned(adapter, pinned, user.id);
26
+ };
27
+ await join().catch(async (error) => {
28
+ await internalAdapter.deleteUser(user.id);
29
+ throw error;
30
+ });
31
+ }
32
+ },
33
+ session: async (session, request) => {
34
+ const pinned = await pin();
35
+ if (!pinned) return;
36
+ const { adapter, internalAdapter } = await context();
37
+ const current = await getCurrentAdapter(adapter);
38
+ if (await isPinnedMember(current, pinned, session.userId)) return;
39
+ const user = await internalAdapter.findUserById(session.userId);
40
+ if (user && createdHere(request, user.email.toLowerCase())) return;
41
+ throw notPinnedMember();
42
+ }
43
+ };
44
+ };
45
+ //#endregion
46
+ export { pinnedSessionHooks };
@@ -1,4 +1,5 @@
1
1
  import { globalRoles } from "./app-roles.js";
2
+ import { acrossOrganizations } from "../../organization-scope/sign-in-organization.js";
2
3
  import { findMember, findOrganization, organizationRoleOf } from "./store.js";
3
4
  //#region src/better-auth/organizations/session-organization.ts
4
5
  /** The user field that keeps the organization someone last worked in, for their next sign-in. */
@@ -41,7 +42,7 @@ const startingOrganization = async (adapter, user) => {
41
42
  organizationId: last,
42
43
  userId: user.id
43
44
  }) || globalRoles(user.role).length > 0 && await findOrganization(adapter, last) !== null)) return last;
44
- const [oldest] = await adapter.findMany({
45
+ const [oldest] = await acrossOrganizations("a new session starts in the oldest of the user's own memberships", () => adapter.findMany({
45
46
  model: "member",
46
47
  where: [{
47
48
  field: "userId",
@@ -52,7 +53,7 @@ const startingOrganization = async (adapter, user) => {
52
53
  direction: "asc"
53
54
  },
54
55
  limit: 1
55
- });
56
+ }));
56
57
  return oldest?.organizationId;
57
58
  };
58
59
  /**