@lowdefy/api 0.0.0-experimental-20260720072521 → 0.0.0-experimental-20260720135014

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 (97) hide show
  1. package/dist/context/createApiContext.js +1 -9
  2. package/dist/context/createAuthorize.js +8 -19
  3. package/dist/context/createEvaluateOperators.js +1 -2
  4. package/dist/index.js +3 -13
  5. package/dist/routes/agent/callAgent.js +180 -7
  6. package/dist/routes/{websocket/authorizeWebsocket.js → auth/callbacks/addUserFieldsToSession.js} +11 -10
  7. package/dist/routes/auth/callbacks/addUserFieldsToToken.js +30 -0
  8. package/dist/routes/auth/{hooks/composeAfterSlot.js → callbacks/createCallbackPlugins.js} +6 -11
  9. package/dist/routes/auth/callbacks/createCallbacks.js +46 -0
  10. package/dist/routes/auth/callbacks/createJWTCallback.js +77 -0
  11. package/dist/routes/auth/callbacks/createRedirectCallback.js +41 -0
  12. package/dist/routes/auth/callbacks/createSessionCallback.js +81 -0
  13. package/dist/routes/auth/callbacks/createSignInCallback.js +40 -0
  14. package/dist/routes/auth/callbacks/validateSessionRoles.js +33 -0
  15. package/dist/routes/{websocket/getWebsocketConfig.js → auth/createAdapter.js} +8 -14
  16. package/dist/routes/auth/createLogger.js +38 -0
  17. package/dist/routes/auth/createProviders.js +25 -0
  18. package/dist/routes/auth/events/createCreateUserEvent.js +41 -0
  19. package/dist/routes/auth/{organizations/getHookRequestHeaders.js → events/createEventPlugins.js} +6 -9
  20. package/dist/routes/auth/events/createEvents.js +56 -0
  21. package/dist/routes/auth/events/createLinkAccountEvent.js +43 -0
  22. package/dist/routes/auth/{strategies/getAuthStrategies.js → events/createSessionEvent.js} +17 -14
  23. package/dist/routes/auth/events/createSignInEvent.js +46 -0
  24. package/dist/routes/auth/events/createSignOutEvent.js +43 -0
  25. package/dist/routes/auth/events/createUpdateUserEvent.js +41 -0
  26. package/dist/routes/auth/getNextAuthConfig.js +75 -0
  27. package/dist/routes/endpoints/authorizeApiEndpoint.js +2 -8
  28. package/dist/routes/endpoints/callEndpoint.js +0 -20
  29. package/dist/routes/endpoints/control/controlReject.js +1 -3
  30. package/dist/routes/endpoints/control/controlThrow.js +1 -4
  31. package/dist/routes/endpoints/handleEndpointCall.js +1 -62
  32. package/dist/routes/endpoints/handleRequest.js +1 -8
  33. package/dist/routes/endpoints/handleValidateSchema.js +1 -3
  34. package/dist/routes/endpoints/runRoutine.js +0 -18
  35. package/dist/routes/endpoints/test/runTest.js +4 -3
  36. package/dist/routes/page/getPageConfig.js +8 -42
  37. package/dist/routes/request/authorizeRequest.js +2 -8
  38. package/dist/routes/request/callRequest.js +1 -8
  39. package/dist/routes/request/callRequestResolver.js +2 -6
  40. package/dist/test/testContext.js +6 -6
  41. package/package.json +10 -16
  42. package/dist/context/applySystemTrust.js +0 -33
  43. package/dist/context/createSystemContext.js +0 -72
  44. package/dist/context/normalizeInjectedCaller.js +0 -41
  45. package/dist/context/resolveAuthentication.js +0 -107
  46. package/dist/context/resolveStrategyCaller.js +0 -56
  47. package/dist/email/renderAuthEmail.js +0 -98
  48. package/dist/email/resolveThemeLogo.js +0 -35
  49. package/dist/routes/agent/prepareAgent.js +0 -169
  50. package/dist/routes/auth/buildAdminPlugin.js +0 -55
  51. package/dist/routes/auth/buildCaptchaPlugin.js +0 -61
  52. package/dist/routes/auth/buildPhoneNumberPlugin.js +0 -57
  53. package/dist/routes/auth/buildProviders.js +0 -51
  54. package/dist/routes/auth/createAuthLogger.js +0 -31
  55. package/dist/routes/auth/createSendEmail.js +0 -49
  56. package/dist/routes/auth/getBetterAuth.js +0 -72
  57. package/dist/routes/auth/getBetterAuthConfig.js +0 -439
  58. package/dist/routes/auth/getUserAdminRole.js +0 -32
  59. package/dist/routes/auth/hooks/authHookPoints.js +0 -192
  60. package/dist/routes/auth/hooks/buildEngineHooks.js +0 -43
  61. package/dist/routes/auth/hooks/buildHooks.js +0 -111
  62. package/dist/routes/auth/hooks/composeBeforeSlot.js +0 -41
  63. package/dist/routes/auth/hooks/createHookDispatch.js +0 -59
  64. package/dist/routes/auth/hooks/createUserAfterHook.js +0 -33
  65. package/dist/routes/auth/hooks/createUserBeforeHook.js +0 -47
  66. package/dist/routes/auth/hooks/findHookUser.js +0 -27
  67. package/dist/routes/auth/modelNames.js +0 -29
  68. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +0 -136
  69. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +0 -211
  70. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +0 -75
  71. package/dist/routes/auth/organizations/createAutoJoinHook.js +0 -63
  72. package/dist/routes/auth/organizations/ensureOrganization.js +0 -95
  73. package/dist/routes/auth/organizations/findPendingInvitation.js +0 -43
  74. package/dist/routes/auth/organizations/getOrganizationBinding.js +0 -65
  75. package/dist/routes/auth/organizations/resolvePinnedOrganization.js +0 -48
  76. package/dist/routes/auth/organizations/syncUserAdminRole.js +0 -102
  77. package/dist/routes/auth/resolveCookiePrefix.js +0 -30
  78. package/dist/routes/auth/strategies/createAuthStrategies.js +0 -77
  79. package/dist/routes/endpoints/handleAgentCall.js +0 -83
  80. package/dist/routes/endpoints/handleAuthStep.js +0 -124
  81. package/dist/routes/endpoints/handleRenderNotification.js +0 -189
  82. package/dist/routes/endpoints/runDetachedEndpoint.js +0 -85
  83. package/dist/routes/endpoints/runScheduledEndpoint.js +0 -102
  84. package/dist/routes/endpoints/runWebhookEndpoint.js +0 -118
  85. package/dist/routes/endpoints/runWebhookVerify.js +0 -94
  86. package/dist/routes/endpoints/scheduleBackground.js +0 -48
  87. package/dist/routes/notifications/derivePreview.js +0 -30
  88. package/dist/routes/notifications/getNotificationConfig.js +0 -32
  89. package/dist/routes/notifications/resolveNotificationLinks.js +0 -72
  90. package/dist/routes/page/dynamic/resolveDynamicContent.js +0 -172
  91. package/dist/routes/page/dynamic/unescapeOperators.js +0 -36
  92. package/dist/routes/page/dynamic/validateFragment.js +0 -104
  93. package/dist/routes/request/resolveTenant.js +0 -57
  94. package/dist/routes/websocket/createChannelRegistry.js +0 -278
  95. package/dist/routes/websocket/createWebSocketConnection.js +0 -131
  96. package/dist/routes/websocket/getWebsocketResolver.js +0 -33
  97. package/dist/routes/websocket/prepareChannel.js +0 -84
@@ -1,136 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import { organization } from 'better-auth/plugins';
16
- import { createAccessControl } from 'better-auth/plugins/access';
17
- import { defaultRoles, defaultStatements } from 'better-auth/plugins/organization/access';
18
- import createAfterAcceptInvitationHook from './createAfterAcceptInvitationHook.js';
19
- import modelNames from '../modelNames.js';
20
- // Organizations are always on - the membership and boundary mechanism for
21
- // every app. The build collects the app's role catalog (auth.roles, a list of
22
- // { id, label, description }); each role.id registers in the plugin's access
23
- // control with empty permission statements - enough for the member APIs to
24
- // accept it for storage and assignment, but authorizing nothing at the AC
25
- // statement layer. Real statements per role are the permissions milestone's.
26
- //
27
- // One reserved authority role, id "$lowdefy-system" (the "$" namespace is
28
- // un-authorable, so no real user can hold it), carries the statements the
29
- // audited admin steps need - they drive member mutations by invoking the org
30
- // endpoint handlers directly, which still run hasPermission against the acting
31
- // member row (fabricated in createActingMemberAdapter, claiming this role).
32
- //
33
- // The wiring is policy-aware:
34
- // - pinned: pass only catalogRoles + the reserved role (no defaultRoles), and
35
- // set creatorRole to "$lowdefy-system". With defaultRoles dropped, owner/
36
- // admin/member no longer resolve as real plugin roles, so they become inert
37
- // app-feature strings with no hidden org-admin power; the acting member is
38
- // the creator, so it passes the plugin's creator-protection guards.
39
- // - tenant: keep the built-in owner/admin/member tier active (self-serve
40
- // per-org administration), so pass defaultRoles and leave creatorRole at its
41
- // default ("owner"). The reserved role is still registered but is not
42
- // load-bearing here - the audited steps belong to the pinned admin module.
43
- function buildOrganizationPlugin({ authConfig, getAuth, sendInvitationEmail }) {
44
- const ac = createAccessControl(defaultStatements);
45
- const catalogRoles = {};
46
- (authConfig.roles ?? []).forEach((role)=>{
47
- catalogRoles[role.id] = ac.newRole({});
48
- });
49
- catalogRoles['$lowdefy-system'] = ac.newRole({
50
- member: [
51
- 'create',
52
- 'update',
53
- 'delete'
54
- ],
55
- invitation: [
56
- 'create',
57
- 'cancel'
58
- ],
59
- organization: [
60
- 'update',
61
- 'delete'
62
- ]
63
- });
64
- const policy = authConfig.organizations?.policy ?? 'pinned';
65
- const roles = policy === 'tenant' ? {
66
- ...catalogRoles,
67
- ...defaultRoles
68
- } : {
69
- ...catalogRoles
70
- };
71
- const options = {
72
- ac,
73
- roles,
74
- // Organization creation is engine-only: the pinned org is seeded by
75
- // ensure-by-slug and tenant orgs are minted lazily at session.create -
76
- // both system actions that bypass this client-facing switch.
77
- allowUserToCreateOrganization: false,
78
- // Re-invite replaces: inviting an email with a pending invitation cancels
79
- // it and creates a fresh one with the new role, attributes, and profile
80
- // (old accept links die with the canceled row). resend: true instead
81
- // re-sends the existing invitation unchanged with a refreshed expiry.
82
- cancelPendingInvitationsOnReInvite: true,
83
- schema: {
84
- organization: {
85
- modelName: modelNames.organization
86
- },
87
- member: {
88
- modelName: modelNames.member,
89
- // Per-(user, org) admin-set authorization inputs - internal, not an
90
- // app-facing additionalFields surface.
91
- additionalFields: {
92
- attributes: {
93
- type: 'json',
94
- required: false,
95
- input: false
96
- }
97
- }
98
- },
99
- invitation: {
100
- modelName: modelNames.invitation,
101
- // An invitation may carry an opaque profile bag; accepting
102
- // shallow-merges it onto the accepting user's user.profile,
103
- // invitation winning per key. Invite-time member attributes ride the
104
- // invitation the same way - accepting copies them onto the minted
105
- // member row, so an invited user's authorization parameters hold
106
- // from their first session.
107
- additionalFields: {
108
- attributes: {
109
- type: 'json',
110
- required: false
111
- },
112
- profile: {
113
- type: 'json',
114
- required: false
115
- }
116
- }
117
- }
118
- },
119
- organizationHooks: {
120
- afterAcceptInvitation: createAfterAcceptInvitationHook({
121
- getAuth,
122
- userAdminRole: authConfig.userAdminRole ?? null
123
- })
124
- },
125
- sendInvitationEmail
126
- };
127
- // Under pinned the reserved role is the creator, so the plugin's creator
128
- // short-circuit and creator-protection guards key on it rather than "owner".
129
- // Under tenant creatorRole stays at its "owner" default (last-owner
130
- // protection keys on it), so it is left unset.
131
- if (policy !== 'tenant') {
132
- options.creatorRole = '$lowdefy-system';
133
- }
134
- return organization(options);
135
- }
136
- export default buildOrganizationPlugin;
@@ -1,211 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import { APIError } from 'better-auth/api';
16
- import { getOrgAdapter } from 'better-auth/plugins';
17
- import ensureOrganization from './ensureOrganization.js';
18
- import findPendingInvitation from './findPendingInvitation.js';
19
- import getHookRequestHeaders from './getHookRequestHeaders.js';
20
- // The engine-tier session.create hook that applies the active-org policy.
21
- // session.create is the one provider-agnostic choke point - it fires for
22
- // email/password, magic link and OAuth alike.
23
- //
24
- // pinned: a member of the pinned org gets it as the active organization; a
25
- // non-member with a pending, unexpired invitation is admitted far enough to
26
- // accept (the membership wall in resolveAuthentication still gates every
27
- // protected page until then); anyone else is rejected before a session is
28
- // minted, with a distinct error code the client surfaces inline.
29
- //
30
- // tenant: the active org is the user's business - the oldest membership when
31
- // they hold several; a user with a pending invitation gets a session but no
32
- // org (they proceed to accept); a fresh signup mints its own organization
33
- // lazily, as owner, through the org plugin's adapter layer (the endpoint
34
- // cannot serve the mint - see applyTenantPolicy).
35
- function createActiveOrgPolicyHook({ getAuth, organizations }) {
36
- async function applyPinnedPolicy({ auth, adapter, internalAdapter, session, ctx }) {
37
- const organization = await ensureOrganization({
38
- auth,
39
- slug: organizations.org
40
- });
41
- const member = await adapter.findOne({
42
- model: 'member',
43
- where: [
44
- {
45
- field: 'userId',
46
- value: session.userId
47
- },
48
- {
49
- field: 'organizationId',
50
- value: organization.id
51
- }
52
- ]
53
- });
54
- if (member) {
55
- return {
56
- data: {
57
- ...session,
58
- activeOrganizationId: organization.id
59
- }
60
- };
61
- }
62
- // Open signup ensures membership here as well as at user.create.after:
63
- // BetterAuth queues after-hooks and flushes them at the end of the
64
- // request (confirmed at 1.6.23), so a signup that mints an immediate
65
- // session reaches this hook before the auto-join has run. The two joins
66
- // are idempotent - each skips when the member row already exists.
67
- if (organizations.signup === 'open') {
68
- await auth.api.addMember({
69
- body: {
70
- userId: session.userId,
71
- organizationId: organization.id,
72
- role: 'member'
73
- },
74
- headers: getHookRequestHeaders(ctx)
75
- });
76
- return {
77
- data: {
78
- ...session,
79
- activeOrganizationId: organization.id
80
- }
81
- };
82
- }
83
- const user = await internalAdapter.findUserById(session.userId);
84
- const invitation = user ? await findPendingInvitation({
85
- adapter,
86
- email: user.email,
87
- organizationId: organization.id
88
- }) : null;
89
- if (invitation) {
90
- // The pending-invitation carve-out: the invitee needs a session to
91
- // accept, so the session is created without an active organization.
92
- return;
93
- }
94
- throw new APIError('FORBIDDEN', {
95
- message: 'You have not been granted access to this application.',
96
- code: 'MEMBERSHIP_REQUIRED'
97
- });
98
- }
99
- async function applyTenantPolicy({ auth, adapter, internalAdapter, session }) {
100
- const members = await adapter.findMany({
101
- model: 'member',
102
- where: [
103
- {
104
- field: 'userId',
105
- value: session.userId
106
- }
107
- ],
108
- sortBy: {
109
- field: 'createdAt',
110
- direction: 'asc'
111
- },
112
- limit: 1
113
- });
114
- if (members.length > 0) {
115
- return {
116
- data: {
117
- ...session,
118
- activeOrganizationId: members[0].organizationId
119
- }
120
- };
121
- }
122
- const user = await internalAdapter.findUserById(session.userId);
123
- const invitation = user ? await findPendingInvitation({
124
- adapter,
125
- email: user.email
126
- }) : null;
127
- if (invitation) {
128
- // An invited user joins the inviter's tenant on accept - mint nothing.
129
- // If the invitation expires unaccepted, the next login lands here with
130
- // no pending invitation and mints their own tenant.
131
- return;
132
- }
133
- // Minted through the org plugin's own adapter layer - the same layer its
134
- // createOrganization endpoint drives. The endpoint itself cannot serve
135
- // this call at 1.6.23: a headerless system-action call cannot resolve
136
- // the engine's dynamic baseURL, and forwarding the firing request's
137
- // headers makes the endpoint demand a session that does not exist yet.
138
- const orgPlugin = auth.options.plugins.find((plugin)=>plugin.id === 'organization');
139
- const orgAdapter = getOrgAdapter(await auth.$context, orgPlugin.options);
140
- const slug = `org-${session.userId}`;
141
- // The mint is not atomic - an earlier attempt may have written the org
142
- // row and failed before the member row. Reuse the orphan so the retry
143
- // does not trip the unique slug index and lock the user out of login.
144
- let organization = await adapter.findOne({
145
- model: 'organization',
146
- where: [
147
- {
148
- field: 'slug',
149
- value: slug
150
- }
151
- ]
152
- });
153
- if (!organization) {
154
- try {
155
- organization = await orgAdapter.createOrganization({
156
- organization: {
157
- name: user?.name || user?.email || session.userId,
158
- slug,
159
- createdAt: new Date()
160
- }
161
- });
162
- } catch (error) {
163
- // A racing login minted the org between the find and the create -
164
- // the unique slug index rejected this write, so read the winner's row.
165
- organization = await adapter.findOne({
166
- model: 'organization',
167
- where: [
168
- {
169
- field: 'slug',
170
- value: slug
171
- }
172
- ]
173
- });
174
- if (!organization) {
175
- throw error;
176
- }
177
- }
178
- }
179
- await orgAdapter.createMember({
180
- userId: session.userId,
181
- organizationId: organization.id,
182
- role: 'owner'
183
- });
184
- return {
185
- data: {
186
- ...session,
187
- activeOrganizationId: organization.id
188
- }
189
- };
190
- }
191
- return async function activeOrgPolicyHook(session, ctx) {
192
- const auth = getAuth();
193
- const { adapter, internalAdapter } = await auth.$context;
194
- if (organizations.policy === 'tenant') {
195
- return applyTenantPolicy({
196
- auth,
197
- adapter,
198
- internalAdapter,
199
- session
200
- });
201
- }
202
- return applyPinnedPolicy({
203
- auth,
204
- adapter,
205
- internalAdapter,
206
- session,
207
- ctx
208
- });
209
- };
210
- }
211
- export default createActiveOrgPolicyHook;
@@ -1,75 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import { type } from '@lowdefy/helpers';
16
- import syncUserAdminRole from './syncUserAdminRole.js';
17
- // The engine-tier binding on the organization plugin's afterAcceptInvitation
18
- // hook (an organizationHooks callback, not a database hook - it fires after
19
- // the member row is created). An invitation may carry an opaque profile bag;
20
- // accepting shallow-merges it onto the accepting user's user.profile,
21
- // invitation winning per key - an opaque copy the engine never reads inside.
22
- // The merge is in-band: a failed copy fails the accept and the user retries.
23
- // Invite-time member attributes ride the invitation the same way: accepting
24
- // copies invitation.attributes onto the minted member row (an adapter-layer
25
- // update, parallel to the opaque profile merge), so an invited user's
26
- // authorization parameters hold from their first session instead of an empty
27
- // bag until an admin edits the member.
28
- function createAfterAcceptInvitationHook({ getAuth, userAdminRole }) {
29
- return async function afterAcceptInvitationHook({ invitation, member, user }) {
30
- const { adapter, internalAdapter } = await getAuth().$context;
31
- if (type.isObject(invitation.profile)) {
32
- // The hook's user is the session user, which may be a cookie-cached
33
- // copy - the merge base is read from the user row so a read-merge-write
34
- // never resurrects a stale profile.
35
- const userRow = await adapter.findOne({
36
- model: 'user',
37
- where: [
38
- {
39
- field: 'id',
40
- value: user.id
41
- }
42
- ]
43
- });
44
- await internalAdapter.updateUser(user.id, {
45
- profile: {
46
- ...userRow.profile ?? {},
47
- ...invitation.profile
48
- }
49
- });
50
- }
51
- if (type.isObject(invitation.attributes)) {
52
- await adapter.update({
53
- model: 'member',
54
- where: [
55
- {
56
- field: 'id',
57
- value: member.id
58
- }
59
- ],
60
- update: {
61
- attributes: invitation.attributes
62
- }
63
- });
64
- }
65
- // The accept mints member roles from the invitation, so it is one of the
66
- // engine-owned writers of the user.role denormalization. In-band like the
67
- // copies above: a failed sync fails the accept and the user retries.
68
- await syncUserAdminRole({
69
- auth: getAuth(),
70
- userAdminRole,
71
- userId: user.id
72
- });
73
- };
74
- }
75
- export default createAfterAcceptInvitationHook;
@@ -1,63 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import ensureOrganization from './ensureOrganization.js';
16
- import getHookRequestHeaders from './getHookRequestHeaders.js';
17
- // The engine-tier user.create.after hook for open signup under the pinned
18
- // policy: auto-join the pinned org with an empty role, through the
19
- // server-only addMember endpoint so the plugin's invariants and hooks run.
20
- // The user passes the membership wall by row existence while role-gated
21
- // pages still gate them; _user.roles reads []. With
22
- // requireEmailVerification the signup holds this member row but obtains no
23
- // session until verified, so joining at user-create is safe.
24
- //
25
- // BetterAuth flushes after-hooks at the end of the request (confirmed at
26
- // 1.6.23), so a signup minting an immediate session runs the session.create
27
- // policy hook first - that hook also ensures membership under open signup,
28
- // and this one skips when the member row already exists.
29
- function createAutoJoinHook({ getAuth, organizations }) {
30
- return async function autoJoinHook(user, ctx) {
31
- const auth = getAuth();
32
- const organization = await ensureOrganization({
33
- auth,
34
- slug: organizations.org
35
- });
36
- const { adapter } = await auth.$context;
37
- const member = await adapter.findOne({
38
- model: 'member',
39
- where: [
40
- {
41
- field: 'userId',
42
- value: user.id
43
- },
44
- {
45
- field: 'organizationId',
46
- value: organization.id
47
- }
48
- ]
49
- });
50
- if (member) {
51
- return;
52
- }
53
- await auth.api.addMember({
54
- body: {
55
- userId: user.id,
56
- organizationId: organization.id,
57
- role: ''
58
- },
59
- headers: getHookRequestHeaders(ctx)
60
- });
61
- };
62
- }
63
- export default createAutoJoinHook;
@@ -1,95 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import { setPinnedOrganization } from './getOrganizationBinding.js';
16
- // Ensure-by-slug seeding for the pinned organization: no org with the
17
- // configured slug means create it, otherwise do nothing. Idempotent and
18
- // self-bootstrapping - a fresh environment needs no manual seed step.
19
- // The organization row is written through the adapter, not the plugin's
20
- // createOrganization endpoint: at better-auth@1.6.23 that endpoint requires
21
- // a creator user (it mints an owner member row), and a seeded org has no
22
- // creator - membership is granted by invite. Racing instances are
23
- // backstopped by the unique slug index.
24
- const ensuredByAuth = new WeakMap();
25
- async function findOrganizationBySlug({ adapter, slug }) {
26
- return adapter.findOne({
27
- model: 'organization',
28
- where: [
29
- {
30
- field: 'slug',
31
- value: slug
32
- }
33
- ]
34
- });
35
- }
36
- async function ensure({ auth, slug }) {
37
- const { adapter } = await auth.$context;
38
- const existing = await findOrganizationBySlug({
39
- adapter,
40
- slug
41
- });
42
- if (existing) {
43
- return existing;
44
- }
45
- try {
46
- return await adapter.create({
47
- model: 'organization',
48
- data: {
49
- name: slug,
50
- slug,
51
- createdAt: new Date()
52
- }
53
- });
54
- } catch (error) {
55
- // A racing instance created the org between the find and the create -
56
- // the unique slug index rejected this write, so read the winner's row.
57
- const created = await findOrganizationBySlug({
58
- adapter,
59
- slug
60
- });
61
- if (created) {
62
- return created;
63
- }
64
- throw error;
65
- }
66
- }
67
- function ensureOrganization({ auth, slug }) {
68
- let bySlug = ensuredByAuth.get(auth);
69
- if (!bySlug) {
70
- bySlug = new Map();
71
- ensuredByAuth.set(auth, bySlug);
72
- }
73
- if (!bySlug.has(slug)) {
74
- const promise = ensure({
75
- auth,
76
- slug
77
- }).then((organization)=>{
78
- // Retain the ensured row for synchronous request-time reads - the
79
- // _organization operator and step organizationId defaulting.
80
- setPinnedOrganization({
81
- auth,
82
- organization,
83
- slug
84
- });
85
- return organization;
86
- }).catch((error)=>{
87
- // Do not memoize a failure - the next fire retries the ensure.
88
- bySlug.delete(slug);
89
- throw error;
90
- });
91
- bySlug.set(slug, promise);
92
- }
93
- return bySlug.get(slug);
94
- }
95
- export default ensureOrganization;
@@ -1,43 +0,0 @@
1
- /*
2
- Copyright 2020-2026 Lowdefy, Inc
3
-
4
- Licensed under the Apache License, Version 2.0 (the "License");
5
- you may not use this file except in compliance with the License.
6
- You may obtain a copy of the License at
7
-
8
- http://www.apache.org/licenses/LICENSE-2.0
9
-
10
- Unless required by applicable law or agreed to in writing, software
11
- distributed under the License is distributed on an "AS IS" BASIS,
12
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- See the License for the specific language governing permissions and
14
- limitations under the License.
15
- */ import { type } from '@lowdefy/helpers';
16
- // Reads the first pending, unexpired invitation for an email - mirroring the
17
- // organization plugin's own findPendingInvitation lookup (lowercased email,
18
- // status "pending", expiry filtered in code). organizationId narrows the
19
- // lookup to one org for the pinned policy; the tenant policy matches any org.
20
- async function findPendingInvitation({ adapter, email, organizationId }) {
21
- const where = [
22
- {
23
- field: 'email',
24
- value: email.toLowerCase()
25
- },
26
- {
27
- field: 'status',
28
- value: 'pending'
29
- }
30
- ];
31
- if (!type.isNone(organizationId)) {
32
- where.push({
33
- field: 'organizationId',
34
- value: organizationId
35
- });
36
- }
37
- const invitations = await adapter.findMany({
38
- model: 'invitation',
39
- where
40
- });
41
- return invitations.find((invitation)=>new Date(invitation.expiresAt) > new Date()) ?? null;
42
- }
43
- export default findPendingInvitation;