@lowdefy/plugin-better-auth 7.1.0 → 7.3.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.
@@ -13,63 +13,83 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
- import { getOrgAdapter } from 'better-auth/plugins';
17
- import getPluginEndpoint from './support/getPluginEndpoint.js';
18
- import invokeEndpoint from './support/invokeEndpoint.js';
19
- // The engine config sets allowUserToCreateOrganization: false; the endpoint
20
- // bypasses that switch only for "system actions" - a call with NO session, NO
21
- // headers, and an explicit body.userId which becomes the creator/owner. So this
22
- // step must not inject an acting session or pass a headers key at all.
23
- async function CreateOrganization({ acting, auth, properties }) {
24
- const { userId: propertiesUserId, ...organizationFields } = properties;
25
- const userId = propertiesUserId ?? acting.user?.id;
26
- const authContext = await auth.$context;
27
- // A provisioned organization has no creator - membership arrives by
28
- // invitation. Without a creator the endpoint cannot serve the write: it
29
- // requires one and mints them as an owner member. So the row is written
30
- // straight through the org plugin's own adapter layer, minting no member.
31
- if (type.isNone(userId)) {
32
- if (type.isNone(organizationFields.name) || type.isNone(organizationFields.slug)) {
33
- throw new Error('CreateOrganization requires "name" and "slug" when run without a userId (creator-less provisioning).');
34
- }
35
- const orgPlugin = auth.options.plugins.find((plugin)=>plugin.id === 'organization');
36
- const orgAdapter = getOrgAdapter(authContext, orgPlugin.options);
37
- // createOrganization spreads the row verbatim and adds no timestamp.
38
- const organization = await orgAdapter.createOrganization({
39
- organization: {
40
- ...organizationFields,
41
- createdAt: new Date()
42
- }
43
- });
44
- // Adapter-layer writes fire no organizationHooks, so the org plugin's
45
- // declared afterCreateOrganization is invoked directly - the endpoint
46
- // path's after-create side effects hold on this path too. Same payload
47
- // shape as the endpoint's call ({ organization, member, user }); a
48
- // provisioned organization has no creator, so member and user are null.
49
- await orgPlugin.options?.organizationHooks?.afterCreateOrganization?.({
50
- organization,
51
- member: null,
52
- user: null
53
- });
54
- return organization;
16
+ const organizationProperties = [
17
+ 'name',
18
+ 'slug',
19
+ 'logo',
20
+ 'metadata'
21
+ ];
22
+ // The org plugin's createOrganization endpoint body schema does not run on
23
+ // this path (see CreateOrganization), so the step checks the properties
24
+ // itself: the endpoint's name, slug, logo and metadata, and userId. The org
25
+ // plugin declares no additional organization fields a routine may set.
26
+ function checkProperties(properties) {
27
+ const unknown = Object.keys(properties).filter((key)=>key !== 'userId' && !organizationProperties.includes(key));
28
+ if (unknown.length > 0) {
29
+ throw new Error(`CreateOrganization does not take ${unknown.map((key)=>`"${key}"`).join(', ')}. It takes "name", "slug", "logo", "metadata" and "userId".`);
30
+ }
31
+ const { logo, metadata, name, slug, userId } = properties;
32
+ if (!type.isString(name) || name === '') {
33
+ throw new Error('CreateOrganization requires a "name" string property.');
34
+ }
35
+ if (!type.isString(slug) || slug === '') {
36
+ throw new Error('CreateOrganization requires a "slug" string property.');
37
+ }
38
+ if (!type.isNone(logo) && !type.isString(logo)) {
39
+ throw new Error('CreateOrganization requires a "logo" string property.');
40
+ }
41
+ if (!type.isNone(metadata) && !type.isObject(metadata)) {
42
+ throw new Error('CreateOrganization requires a "metadata" object property.');
43
+ }
44
+ if (!type.isNone(userId) && (!type.isString(userId) || userId === '')) {
45
+ throw new Error('CreateOrganization requires "userId" to be a user id string.');
55
46
  }
56
- const endpoint = getPluginEndpoint({
57
- authContext,
58
- endpointKey: 'createOrganization',
59
- pluginId: 'organization'
47
+ }
48
+ // The rows are written by the engine's provisionOrganization, not the org
49
+ // plugin's createOrganization endpoint. The endpoint mints its creator as an
50
+ // owner member with no app roles, so granting auth.organizations.creatorAppRoles
51
+ // would take a second write, and undoing both rows when that one failed. The
52
+ // engine writes the owner row with its app roles in the one write, the same
53
+ // way the tenant signup mint does, and a run that fails between the
54
+ // organization and owner writes is finished by the creator's next run for the
55
+ // same slug.
56
+ //
57
+ // A provisioned organization has no creator - membership arrives by
58
+ // invitation - so without a userId it gets no member row. The step is
59
+ // system-scoped, so there is no caller to default the creator to.
60
+ async function CreateOrganization({ auth, properties, provisionOrganization }) {
61
+ checkProperties(properties);
62
+ const { userId } = properties;
63
+ const organization = {};
64
+ organizationProperties.forEach((key)=>{
65
+ if (!type.isNone(properties[key])) {
66
+ organization[key] = properties[key];
67
+ }
60
68
  });
61
- return invokeEndpoint({
62
- endpoint,
63
- input: {
64
- body: {
65
- ...properties,
66
- userId
67
- },
68
- context: {
69
- ...authContext
70
- }
69
+ if (!type.isNone(userId)) {
70
+ const { internalAdapter } = await auth.$context;
71
+ const user = await internalAdapter.findUserById(userId);
72
+ if (type.isNone(user)) {
73
+ throw new Error(`CreateOrganization creator "${userId}" is not a user.`);
71
74
  }
75
+ }
76
+ const provisioned = await provisionOrganization({
77
+ organization,
78
+ userId
72
79
  });
80
+ if (type.isNone(provisioned)) {
81
+ throw new Error(`CreateOrganization refused - an organization with slug "${organization.slug}" already exists.`);
82
+ }
83
+ if (type.isNone(provisioned.member)) {
84
+ return provisioned.organization;
85
+ }
86
+ // The endpoint's result shape, which routines already read the owner from.
87
+ return {
88
+ ...provisioned.organization,
89
+ members: [
90
+ provisioned.member
91
+ ]
92
+ };
73
93
  }
74
94
  // system scope: under the pinned policy organizations are seeded by
75
95
  // ensureOrganization, under tenant they are minted lazily at session create, and
@@ -21,7 +21,9 @@ async function InviteMember({ acting, auth, organizationId, properties }) {
21
21
  // appRoles, attributes, contactId and profile are registered invitation
22
22
  // additionalFields in the engine config; accepting the invitation
23
23
  // shallow-merges profile onto the user's profile bag (invitation wins per
24
- // key), sets contactId on the user row, and copies attributes and appRoles
24
+ // key), sets contactId on a login that has no link yet (an invitation naming
25
+ // a different contact than the login holds is refused), and copies
26
+ // attributes and appRoles
25
27
  // onto the minted member row. Each is declared without input: false
26
28
  // precisely so this body may carry it.
27
29
  const { appRoles, attributes, contactId, email, orgRole, profile, resend } = properties;
@@ -46,6 +48,11 @@ async function InviteMember({ acting, auth, organizationId, properties }) {
46
48
  if (!type.isNone(contactId) && !type.isString(contactId)) {
47
49
  throw new Error('InviteMember "contactId" is not a string.');
48
50
  }
51
+ // Accepting sets the link once, so an empty link would stick and refuse
52
+ // every later invitation that names a contact.
53
+ if (contactId === '') {
54
+ throw new Error('InviteMember "contactId" is an empty string.');
55
+ }
49
56
  // An omitted orgRole must still send something: createInvitation's body
50
57
  // schema declares role as required, so undefined fails the zod body, and ''
51
58
  // passes it silently - BetterAuth filters the empty entry out before
@@ -0,0 +1,110 @@
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
+ function holdsOwnerTier({ member }) {
17
+ return (member.role ?? '').split(',').map((role)=>role.trim()).includes('owner');
18
+ }
19
+ // Suspending takes a person out of one organization without banning their
20
+ // login, which BanUser does for every organization in the deployment, and
21
+ // without deleting their member row, which RemoveMember does. The row keeps its
22
+ // roles, attributes and display copies, so the app's own queries still find the
23
+ // person - a report of everyone who held a role - while every membership check
24
+ // treats them as a non-member: they resolve unauthenticated, cannot sign in to a
25
+ // pinned app, and their MCP tokens stop working.
26
+ //
27
+ // Adapter-direct, like UpdateMemberRoles: the flag is an admin-set
28
+ // authorization input, not an org-tier change, so it fires no member.update
29
+ // database hooks.
30
+ //
31
+ // An owner is never suspended - their org tier is changed first, with
32
+ // UpdateMemberOrgRole. The organization plugin's owner guards (an admin cannot
33
+ // remove or demote an owner, the last owner cannot leave, be removed or demote
34
+ // themselves) count every owner row and know nothing of suspension, so a
35
+ // suspended owner would let an admin lock an owner out and let the last
36
+ // active owner leave behind only suspended ones. Keeping suspended rows out of
37
+ // the owner tier keeps those guards exact; beforeUpdateMemberRole refuses the
38
+ // other way in, promoting a suspended member.
39
+ //
40
+ // organizationId is part of the authored property surface but the step never
41
+ // resolves it: the floor resolves the target organization (defaulting to the
42
+ // pinned one), authorizes the caller there, and passes the result in.
43
+ async function SuspendMember({ acting, auth, organizationId, properties }) {
44
+ const { memberId } = properties;
45
+ if (type.isNone(memberId)) {
46
+ throw new Error('SuspendMember requires a "memberId" property.');
47
+ }
48
+ const { adapter } = await auth.$context;
49
+ const where = [
50
+ {
51
+ field: 'id',
52
+ value: memberId
53
+ },
54
+ {
55
+ field: 'organizationId',
56
+ value: organizationId
57
+ }
58
+ ];
59
+ const member = await adapter.findOne({
60
+ model: 'member',
61
+ where
62
+ });
63
+ if (type.isNone(member)) {
64
+ throw new Error(`SuspendMember found no member "${memberId}" in organization "${organizationId}".`);
65
+ }
66
+ if (holdsOwnerTier({
67
+ member
68
+ })) {
69
+ throw new Error(`SuspendMember cannot suspend member "${memberId}" - they are an owner of organization "${organizationId}". Change their org role with UpdateMemberOrgRole first.`);
70
+ }
71
+ // A caller who suspends themselves resolves unauthenticated from the next
72
+ // request on, with no way back short of another administrator.
73
+ if (acting.system !== true && member.userId === acting.user.id) {
74
+ throw new Error(`SuspendMember cannot suspend member "${memberId}" - it is the caller's own membership.`);
75
+ }
76
+ // Written only while the role is still the one read, so a promotion to owner
77
+ // that lands between the read and this write is not suspended with it. The
78
+ // row can also be removed in between.
79
+ const suspended = await adapter.update({
80
+ model: 'member',
81
+ where: [
82
+ ...where,
83
+ {
84
+ field: 'role',
85
+ value: member.role
86
+ }
87
+ ],
88
+ update: {
89
+ suspended: true
90
+ }
91
+ });
92
+ if (type.isNone(suspended)) {
93
+ throw new Error(`SuspendMember found no member "${memberId}" in organization "${organizationId}" with role "${member.role}". It was removed or its org role changed - try again.`);
94
+ }
95
+ return suspended;
96
+ }
97
+ // Suspending takes a member out of the organization the caller administers, so
98
+ // it needs member:suspend authority there - its own action, so a narrower role
99
+ // can manage members without it.
100
+ SuspendMember.meta = {
101
+ authority: {
102
+ scope: 'org',
103
+ permissions: {
104
+ member: [
105
+ 'suspend'
106
+ ]
107
+ }
108
+ }
109
+ };
110
+ export default SuspendMember;
@@ -0,0 +1,63 @@
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
+ // Lifts a suspension SuspendMember set: the member row is admitted again with
17
+ // the roles and attributes it kept while suspended. The flag is written false
18
+ // rather than removed; false and absent mean the same to every membership
19
+ // check.
20
+ //
21
+ // organizationId is part of the authored property surface but the step never
22
+ // resolves it: the floor resolves the target organization (defaulting to the
23
+ // pinned one), authorizes the caller there, and passes the result in.
24
+ async function UnsuspendMember({ auth, organizationId, properties }) {
25
+ const { memberId } = properties;
26
+ if (type.isNone(memberId)) {
27
+ throw new Error('UnsuspendMember requires a "memberId" property.');
28
+ }
29
+ const { adapter } = await auth.$context;
30
+ const member = await adapter.update({
31
+ model: 'member',
32
+ where: [
33
+ {
34
+ field: 'id',
35
+ value: memberId
36
+ },
37
+ {
38
+ field: 'organizationId',
39
+ value: organizationId
40
+ }
41
+ ],
42
+ update: {
43
+ suspended: false
44
+ }
45
+ });
46
+ if (type.isNone(member)) {
47
+ throw new Error(`UnsuspendMember found no member "${memberId}" in organization "${organizationId}".`);
48
+ }
49
+ return member;
50
+ }
51
+ // The authority to suspend is the authority to lift it, as BanUser and
52
+ // UnbanUser share user:ban.
53
+ UnsuspendMember.meta = {
54
+ authority: {
55
+ scope: 'org',
56
+ permissions: {
57
+ member: [
58
+ 'suspend'
59
+ ]
60
+ }
61
+ }
62
+ };
63
+ export default UnsuspendMember;
@@ -18,7 +18,6 @@
18
18
  // checked in, and rejecting it would break every non-self-service save from a
19
19
  // second admin surface.
20
20
  const allowedProperties = [
21
- 'contactId',
22
21
  'image',
23
22
  'name',
24
23
  'organizationId',
@@ -30,17 +29,18 @@ const allowedProperties = [
30
29
  // profile update is a shallow merge per top-level key onto the user's
31
30
  // existing bag - a key set to null is removed - so the row is read first;
32
31
  // the adapter's json additionalField transform handles storage on both ends.
33
- // name and image are the display copies. contactId is the link to the app's
34
- // canonical record for this person - a top-level field, so it is set outright
35
- // and never joins the profile merge. The step writes nothing else - not
36
- // email, not emailVerified, not attributes, not roles. Adapter-direct like
37
- // UpdateUserAttributes: fires NO user.update database hooks.
32
+ // name and image are the display copies. The step writes nothing else - not
33
+ // email, not emailVerified, not attributes, not roles, and not contactId: apps
34
+ // compare _user.contact_id in author and access checks, so the link is set only
35
+ // by accepting an invitation that carries it (createBeforeAcceptInvitationHook),
36
+ // never by a routine. Adapter-direct like UpdateUserAttributes: fires NO
37
+ // user.update database hooks.
38
38
  async function UpdateUserProfile({ auth, organizationId, properties }) {
39
- const { contactId, image, name, profile, userId } = properties;
39
+ const { image, name, profile, userId } = properties;
40
40
  const unknownProperties = Object.keys(properties).filter((key)=>!allowedProperties.includes(key));
41
41
  if (unknownProperties.length > 0) {
42
42
  const received = unknownProperties.map((key)=>`"${key}"`).join(', ');
43
- throw new Error(`UpdateUserProfile received unknown properties ${received}. ` + 'Allowed properties are "userId", "profile", "contactId", "name", "image", and "organizationId".');
43
+ throw new Error(`UpdateUserProfile received unknown properties ${received}. ` + 'Allowed properties are "userId", "profile", "name", "image", and "organizationId".');
44
44
  }
45
45
  if (type.isNone(userId)) {
46
46
  throw new Error('UpdateUserProfile requires a "userId" property.');
@@ -54,11 +54,8 @@ async function UpdateUserProfile({ auth, organizationId, properties }) {
54
54
  if (!type.isNone(image) && !type.isString(image)) {
55
55
  throw new Error('UpdateUserProfile "image" is not a string.');
56
56
  }
57
- if (!type.isNone(contactId) && !type.isString(contactId)) {
58
- throw new Error('UpdateUserProfile "contactId" is not a string.');
59
- }
60
- if (type.isNone(profile) && type.isNone(contactId) && type.isNone(name) && type.isNone(image)) {
61
- throw new Error('UpdateUserProfile requires at least one of "profile", "contactId", "name", or "image" to write.');
57
+ if (type.isNone(profile) && type.isNone(name) && type.isNone(image)) {
58
+ throw new Error('UpdateUserProfile requires at least one of "profile", "name", or "image" to write.');
62
59
  }
63
60
  const { adapter } = await auth.$context;
64
61
  const user = await adapter.findOne({
@@ -92,9 +89,6 @@ async function UpdateUserProfile({ auth, organizationId, properties }) {
92
89
  });
93
90
  update.profile = merged;
94
91
  }
95
- if (!type.isNone(contactId)) {
96
- update.contactId = contactId;
97
- }
98
92
  if (!type.isNone(name)) {
99
93
  update.name = name;
100
94
  }
@@ -151,12 +145,12 @@ async function UpdateUserProfile({ auth, organizationId, properties }) {
151
145
  // compared to the caller's own id, and when properties.userId is that id the
152
146
  // floor skips its check entirely - evaluated before the scope check, so a
153
147
  // person saves their own profile without any org authority and without holding
154
- // a member row in the organization the request names. Profile, contactId, name
155
- // and image are display, link and app data - no authorization check reads any
156
- // of them, so the exemption holds for contactId too. Targeting anyone else
157
- // writes the deployment-wide user row, so it needs user:update authority in an
158
- // organization the target holds a member row in - membership is the
159
- // relationship that makes that person the caller's business.
148
+ // a member row in the organization the request names. Profile, name and image
149
+ // are display and app data that no authorization check reads, which is what
150
+ // makes the exemption safe. Targeting anyone else writes the deployment-wide
151
+ // user row, so it needs user:update authority in an organization the target
152
+ // holds a member row in - membership is the relationship that makes that person
153
+ // the caller's business.
160
154
  UpdateUserProfile.meta = {
161
155
  authority: {
162
156
  scope: 'org',
package/dist/steps.js CHANGED
@@ -28,7 +28,9 @@ export { default as RevokeMcpToken } from './steps/RevokeMcpToken.js';
28
28
  export { default as RevokeOrgMcpToken } from './steps/RevokeOrgMcpToken.js';
29
29
  export { default as RevokeUserPasskeys } from './steps/RevokeUserPasskeys.js';
30
30
  export { default as RevokeUserSessions } from './steps/RevokeUserSessions.js';
31
+ export { default as SuspendMember } from './steps/SuspendMember.js';
31
32
  export { default as UnbanUser } from './steps/UnbanUser.js';
33
+ export { default as UnsuspendMember } from './steps/UnsuspendMember.js';
32
34
  export { default as UpdateMemberAttributes } from './steps/UpdateMemberAttributes.js';
33
35
  export { default as UpdateMemberOrgRole } from './steps/UpdateMemberOrgRole.js';
34
36
  export { default as UpdateMemberRoles } from './steps/UpdateMemberRoles.js';
package/dist/types.js CHANGED
@@ -74,7 +74,9 @@
74
74
  'RevokeOrgMcpToken',
75
75
  'RevokeUserPasskeys',
76
76
  'RevokeUserSessions',
77
+ 'SuspendMember',
77
78
  'UnbanUser',
79
+ 'UnsuspendMember',
78
80
  'UpdateMemberAttributes',
79
81
  'UpdateMemberOrgRole',
80
82
  'UpdateMemberRoles',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/plugin-better-auth",
3
- "version": "7.1.0",
3
+ "version": "7.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Lowdefy providers, API auth strategies, and admin steps for the BetterAuth engine.",
6
6
  "homepage": "https://lowdefy.com",
@@ -39,18 +39,15 @@
39
39
  "dist/*"
40
40
  ],
41
41
  "dependencies": {
42
- "@lowdefy/errors": "7.1.0",
43
- "@lowdefy/helpers": "7.1.0",
42
+ "@lowdefy/errors": "7.3.0",
43
+ "@lowdefy/helpers": "7.3.0",
44
44
  "better-auth": "1.7.7",
45
45
  "jose": "^6.2.3"
46
46
  },
47
47
  "devDependencies": {
48
- "@jest/globals": "28.1.3",
49
48
  "@swc/cli": "0.8.1",
50
49
  "@swc/core": "1.15.32",
51
- "@swc/jest": "0.2.39",
52
- "jest": "28.1.3",
53
- "jest-environment-node": "28.1.3"
50
+ "vitest": "4.1.12"
54
51
  },
55
52
  "publishConfig": {
56
53
  "access": "public"
@@ -58,6 +55,6 @@
58
55
  "scripts": {
59
56
  "build": "swc src --out-dir dist --config-file ../../../../.swcrc --cli-config-file ../../../../.swc-cli.json --copy-files",
60
57
  "clean": "rm -rf dist",
61
- "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
58
+ "test": "vitest run"
62
59
  }
63
60
  }