@lowdefy/plugin-better-auth 7.0.0 → 7.2.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
@@ -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;
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.0.0",
3
+ "version": "7.2.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.0.0",
43
- "@lowdefy/helpers": "7.0.0",
42
+ "@lowdefy/errors": "7.2.0",
43
+ "@lowdefy/helpers": "7.2.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
  }