@lowdefy/plugin-better-auth 0.0.0-experimental-20261007124348 → 0.0.0-experimental-20261009120232

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.
@@ -0,0 +1,109 @@
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 { createHash, randomBytes } from 'node:crypto';
16
+ import { type } from '@lowdefy/helpers';
17
+ import assertMcpTokenModel from './support/assertMcpTokenModel.js';
18
+ const DAY_MS = 24 * 60 * 60 * 1000;
19
+ // Creates a member token for the caller in their active organization - the
20
+ // long-lived bearer a script sends to /api/mcp to be served as that member.
21
+ // The token is returned here and nowhere else: only its SHA-256 and its first
22
+ // 12 characters are stored.
23
+ //
24
+ // Only a person signed in with a session creates one. Every other caller
25
+ // carries auth_method - an MCP caller (OAuth grant or member token) "mcp", an
26
+ // API strategy caller its strategy type - and the caller-scope floor admits
27
+ // them all. Without this check an OAuth agent could turn its grant into a
28
+ // token that outlives RevokeMcpGrant, a member token could mint a fresh one
29
+ // past the expiry its maker chose, and a read-only grant could mint a token
30
+ // with write.
31
+ //
32
+ // The token records the member row it was made for: the MCP route accepts it
33
+ // only while that row stands, so leaving, removal or deletion ends it.
34
+ async function CreateMcpToken({ acting, auth, properties }) {
35
+ if (!type.isNone(acting.user.auth_method)) {
36
+ throw new Error('CreateMcpToken only runs for a person signed in with a session - member tokens are created from a signed-in session, never by an agent, a script or another token.');
37
+ }
38
+ assertMcpTokenModel({
39
+ auth,
40
+ stepName: 'CreateMcpToken'
41
+ });
42
+ const { name, expiresInDays } = properties ?? {};
43
+ if (!type.isString(name) || name.trim() === '') {
44
+ throw new Error('CreateMcpToken requires a non-empty string "name" property.');
45
+ }
46
+ if (type.isUndefined(expiresInDays)) {
47
+ throw new Error('CreateMcpToken requires an "expiresInDays" property - a positive whole number of days, or null for a token that never expires.');
48
+ }
49
+ if (!type.isNull(expiresInDays) && !(type.isInt(expiresInDays) && expiresInDays > 0)) {
50
+ throw new Error(`CreateMcpToken "expiresInDays" must be a positive whole number of days, or null for a token that never expires. Received ${JSON.stringify(expiresInDays)}.`);
51
+ }
52
+ const createdAt = new Date();
53
+ const expiresAt = type.isNull(expiresInDays) ? null : new Date(createdAt.getTime() + expiresInDays * DAY_MS);
54
+ if (!type.isNull(expiresAt) && Number.isNaN(expiresAt.getTime())) {
55
+ throw new Error(`CreateMcpToken "expiresInDays" is past the latest date that can be stored. Received ${JSON.stringify(expiresInDays)}. Use null for a token that never expires.`);
56
+ }
57
+ const userId = acting.user.id;
58
+ const organizationId = acting.user.organization_id;
59
+ if (type.isNone(organizationId)) {
60
+ throw new Error('CreateMcpToken needs the caller to have an active organization.');
61
+ }
62
+ const { adapter } = await auth.$context;
63
+ const member = await adapter.findOne({
64
+ model: 'member',
65
+ where: [
66
+ {
67
+ field: 'userId',
68
+ value: userId
69
+ },
70
+ {
71
+ field: 'organizationId',
72
+ value: organizationId
73
+ }
74
+ ]
75
+ });
76
+ if (type.isNone(member)) {
77
+ throw new Error(`CreateMcpToken found no member row for the caller in organization "${organizationId}".`);
78
+ }
79
+ const token = `ldf_mcp_${randomBytes(32).toString('base64url')}`;
80
+ const start = token.slice(0, 12);
81
+ const row = await adapter.create({
82
+ model: 'mcpToken',
83
+ data: {
84
+ organizationId,
85
+ userId,
86
+ memberId: member.id,
87
+ name: name.trim(),
88
+ hash: createHash('sha256').update(token).digest('hex'),
89
+ start,
90
+ createdAt,
91
+ expiresAt,
92
+ lastUsedAt: null
93
+ }
94
+ });
95
+ return {
96
+ id: row.id,
97
+ token,
98
+ start,
99
+ expiresAt
100
+ };
101
+ }
102
+ // The token acts as the caller and is written for the caller's own member row,
103
+ // so it needs a caller and no organization authority.
104
+ CreateMcpToken.meta = {
105
+ authority: {
106
+ scope: 'caller'
107
+ }
108
+ };
109
+ export default CreateMcpToken;
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import callPluginEndpoint from './support/callPluginEndpoint.js';
17
+ import hasMcpTokenModel from './support/hasMcpTokenModel.js';
17
18
  // The design routes member and invitation cleanup "via the org plugin's APIs",
18
19
  // but at better-auth 1.7.0 removeMember refuses once the user row is gone (it
19
20
  // re-reads the user and 400s). The cascade therefore uses the adapter layer -
@@ -76,6 +77,21 @@ async function DeleteUser({ acting, auth, properties }) {
76
77
  ]
77
78
  });
78
79
  }
80
+ // The MCP route already refuses a token whose member row is gone - this
81
+ // second write only keeps token lists tidy.
82
+ if (hasMcpTokenModel({
83
+ auth
84
+ })) {
85
+ await adapter.deleteMany({
86
+ model: 'mcpToken',
87
+ where: [
88
+ {
89
+ field: 'userId',
90
+ value: userId
91
+ }
92
+ ]
93
+ });
94
+ }
79
95
  const invitations = await adapter.findMany({
80
96
  model: 'invitation',
81
97
  where: [
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import callPluginEndpoint from './support/callPluginEndpoint.js';
17
+ import hasMcpTokenModel from './support/hasMcpTokenModel.js';
17
18
  // Ends the caller's own membership of the named organization through the
18
19
  // organization plugin's leave endpoint, so its checks run: the caller must hold
19
20
  // a member row there, and the only owner cannot leave. A refusal throws with
@@ -31,7 +32,7 @@ async function LeaveOrganization({ acting, auth, properties }) {
31
32
  if (type.isNone(organizationId)) {
32
33
  throw new Error('LeaveOrganization requires an "organizationId" property.');
33
34
  }
34
- return callPluginEndpoint({
35
+ const member = await callPluginEndpoint({
35
36
  acting,
36
37
  auth,
37
38
  body: {
@@ -40,6 +41,23 @@ async function LeaveOrganization({ acting, auth, properties }) {
40
41
  endpointKey: 'leaveOrganization',
41
42
  pluginId: 'organization'
42
43
  });
44
+ // The MCP route already refuses a token whose member row is gone - this
45
+ // second write only keeps token lists tidy.
46
+ if (hasMcpTokenModel({
47
+ auth
48
+ })) {
49
+ const { adapter } = await auth.$context;
50
+ await adapter.deleteMany({
51
+ model: 'mcpToken',
52
+ where: [
53
+ {
54
+ field: 'memberId',
55
+ value: member.id
56
+ }
57
+ ]
58
+ });
59
+ }
60
+ return member;
43
61
  }
44
62
  // Leaving touches only the caller's own member row, which every member may
45
63
  // end, so it needs a caller and no organization authority.
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import callPluginEndpoint from './support/callPluginEndpoint.js';
17
+ import hasMcpTokenModel from './support/hasMcpTokenModel.js';
17
18
  // organizationId is part of the authored property surface but the step never
18
19
  // resolves it: the floor resolves the target organization (defaulting to the
19
20
  // pinned one), authorizes the caller there, and passes the result in.
@@ -22,7 +23,7 @@ async function RemoveMember({ acting, auth, organizationId, properties }) {
22
23
  if (type.isNone(memberIdOrEmail)) {
23
24
  throw new Error('RemoveMember requires a "memberIdOrEmail" property.');
24
25
  }
25
- return callPluginEndpoint({
26
+ const result = await callPluginEndpoint({
26
27
  acting,
27
28
  auth,
28
29
  body: {
@@ -32,6 +33,23 @@ async function RemoveMember({ acting, auth, organizationId, properties }) {
32
33
  endpointKey: 'removeMember',
33
34
  pluginId: 'organization'
34
35
  });
36
+ // The MCP route already refuses a token whose member row is gone - this
37
+ // second write only keeps token lists tidy.
38
+ if (hasMcpTokenModel({
39
+ auth
40
+ })) {
41
+ const { adapter } = await auth.$context;
42
+ await adapter.deleteMany({
43
+ model: 'mcpToken',
44
+ where: [
45
+ {
46
+ field: 'memberId',
47
+ value: result.member.id
48
+ }
49
+ ]
50
+ });
51
+ }
52
+ return result;
35
53
  }
36
54
  // Deleting a member row needs member:delete authority in the organization the
37
55
  // row belongs to.
@@ -40,6 +40,9 @@ async function RevokeMcpGrant({ acting, auth, mcp }) {
40
40
  if (type.isNone(mcp) || mcp.tokenStatus !== 'valid') {
41
41
  throw new Error('RevokeMcpGrant can only run for a caller authenticated over MCP - it revokes the grant behind the calling access token.');
42
42
  }
43
+ if (!type.isNone(mcp.tokenId)) {
44
+ throw new Error('RevokeMcpGrant cannot run for a member token caller - a member token has no OAuth grant to revoke. Switch the token off with RevokeMcpToken.');
45
+ }
43
46
  const { clientId, organizationId } = mcp;
44
47
  const userId = acting.user.id;
45
48
  const { adapter } = await auth.$context;
@@ -0,0 +1,72 @@
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 assertMcpTokenModel from './support/assertMcpTokenModel.js';
17
+ // Switches off one of the caller's own member tokens by deleting its row - the
18
+ // MCP route refuses it on its next call. A token that is someone else's and a
19
+ // token that does not exist get the same not-found error, so the step never
20
+ // confirms the id of another member's token.
21
+ async function RevokeMcpToken({ acting, auth, properties }) {
22
+ assertMcpTokenModel({
23
+ auth,
24
+ stepName: 'RevokeMcpToken'
25
+ });
26
+ const { id } = properties ?? {};
27
+ if (!type.isString(id)) {
28
+ throw new Error(`RevokeMcpToken requires a string "id" property. Received ${JSON.stringify(id)}.`);
29
+ }
30
+ const { adapter } = await auth.$context;
31
+ const row = await adapter.findOne({
32
+ model: 'mcpToken',
33
+ where: [
34
+ {
35
+ field: 'id',
36
+ value: id
37
+ },
38
+ {
39
+ field: 'userId',
40
+ value: acting.user.id
41
+ }
42
+ ]
43
+ });
44
+ if (type.isNone(row)) {
45
+ throw new Error(`RevokeMcpToken found no token with id "${id}".`);
46
+ }
47
+ await adapter.delete({
48
+ model: 'mcpToken',
49
+ where: [
50
+ {
51
+ field: 'id',
52
+ value: row.id
53
+ }
54
+ ]
55
+ });
56
+ // Returned so routines can write audit events - never the hash.
57
+ return {
58
+ id: row.id,
59
+ userId: row.userId,
60
+ memberId: row.memberId,
61
+ name: row.name,
62
+ start: row.start
63
+ };
64
+ }
65
+ // The step deletes only a token the caller owns, so it needs a caller and no
66
+ // organization authority.
67
+ RevokeMcpToken.meta = {
68
+ authority: {
69
+ scope: 'caller'
70
+ }
71
+ };
72
+ export default RevokeMcpToken;
@@ -0,0 +1,76 @@
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 assertMcpTokenModel from './support/assertMcpTokenModel.js';
17
+ // Switches off any member token in the organization the floor authorized - an
18
+ // owner or admin overseeing the organization's tokens. The token must belong
19
+ // to that organization; one in another organization is not found, the same as
20
+ // one that does not exist.
21
+ async function RevokeOrgMcpToken({ auth, organizationId, properties }) {
22
+ assertMcpTokenModel({
23
+ auth,
24
+ stepName: 'RevokeOrgMcpToken'
25
+ });
26
+ const { id } = properties ?? {};
27
+ if (!type.isString(id)) {
28
+ throw new Error(`RevokeOrgMcpToken requires a string "id" property. Received ${JSON.stringify(id)}.`);
29
+ }
30
+ const { adapter } = await auth.$context;
31
+ const row = await adapter.findOne({
32
+ model: 'mcpToken',
33
+ where: [
34
+ {
35
+ field: 'id',
36
+ value: id
37
+ },
38
+ {
39
+ field: 'organizationId',
40
+ value: organizationId
41
+ }
42
+ ]
43
+ });
44
+ if (type.isNone(row)) {
45
+ throw new Error(`RevokeOrgMcpToken found no token with id "${id}" in this organization.`);
46
+ }
47
+ await adapter.delete({
48
+ model: 'mcpToken',
49
+ where: [
50
+ {
51
+ field: 'id',
52
+ value: row.id
53
+ }
54
+ ]
55
+ });
56
+ // Returned so routines can log whose token was switched off - never the hash.
57
+ return {
58
+ id: row.id,
59
+ userId: row.userId,
60
+ memberId: row.memberId,
61
+ name: row.name,
62
+ start: row.start
63
+ };
64
+ }
65
+ // Overseeing members is member:update authority - owners and admins by default.
66
+ RevokeOrgMcpToken.meta = {
67
+ authority: {
68
+ scope: 'org',
69
+ permissions: {
70
+ member: [
71
+ 'update'
72
+ ]
73
+ }
74
+ }
75
+ };
76
+ export default RevokeOrgMcpToken;
@@ -0,0 +1,23 @@
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 hasMcpTokenModel from './hasMcpTokenModel.js';
16
+ function assertMcpTokenModel({ auth, stepName }) {
17
+ if (!hasMcpTokenModel({
18
+ auth
19
+ })) {
20
+ throw new Error(`${stepName} needs the MCP authorization server - set "auth.oauthProvider". Without it the MCP route authenticates nobody, so member tokens reach nothing.`);
21
+ }
22
+ }
23
+ export default assertMcpTokenModel;
@@ -0,0 +1,24 @@
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
+ // The mcpToken model is declared only beside the MCP authorization server -
17
+ // getBetterAuthConfig registers it with auth.oauthProvider. Without the AS the
18
+ // MCP route authenticates nobody, so a token would reach nothing, and there is
19
+ // no model for the adapter to read or write. Keyed on the model name every
20
+ // adapter call already uses, not on the declaring plugin's id.
21
+ function hasMcpTokenModel({ auth }) {
22
+ return (auth.options?.plugins ?? []).some((plugin)=>!type.isNone(plugin?.schema?.mcpToken));
23
+ }
24
+ export default hasMcpTokenModel;
package/dist/steps.js CHANGED
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ export { default as BanUser } from './steps/BanUser.js';
16
16
  export { default as CancelInvitation } from './steps/CancelInvitation.js';
17
+ export { default as CreateMcpToken } from './steps/CreateMcpToken.js';
17
18
  export { default as CreateOrganization } from './steps/CreateOrganization.js';
18
19
  export { default as DeleteUser } from './steps/DeleteUser.js';
19
20
  export { default as InviteMember } from './steps/InviteMember.js';
@@ -23,6 +24,8 @@ export { default as ListUsers } from './steps/ListUsers.js';
23
24
  export { default as RemoveMember } from './steps/RemoveMember.js';
24
25
  export { default as ResetUserTwoFactor } from './steps/ResetUserTwoFactor.js';
25
26
  export { default as RevokeMcpGrant } from './steps/RevokeMcpGrant.js';
27
+ export { default as RevokeMcpToken } from './steps/RevokeMcpToken.js';
28
+ export { default as RevokeOrgMcpToken } from './steps/RevokeOrgMcpToken.js';
26
29
  export { default as RevokeUserPasskeys } from './steps/RevokeUserPasskeys.js';
27
30
  export { default as RevokeUserSessions } from './steps/RevokeUserSessions.js';
28
31
  export { default as UnbanUser } from './steps/UnbanUser.js';
package/dist/types.js CHANGED
@@ -60,6 +60,7 @@
60
60
  steps: [
61
61
  'BanUser',
62
62
  'CancelInvitation',
63
+ 'CreateMcpToken',
63
64
  'CreateOrganization',
64
65
  'DeleteUser',
65
66
  'InviteMember',
@@ -69,6 +70,8 @@
69
70
  'RemoveMember',
70
71
  'ResetUserTwoFactor',
71
72
  'RevokeMcpGrant',
73
+ 'RevokeMcpToken',
74
+ 'RevokeOrgMcpToken',
72
75
  'RevokeUserPasskeys',
73
76
  'RevokeUserSessions',
74
77
  'UnbanUser',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/plugin-better-auth",
3
- "version": "0.0.0-experimental-20261007124348",
3
+ "version": "0.0.0-experimental-20261009120232",
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,8 +39,8 @@
39
39
  "dist/*"
40
40
  ],
41
41
  "dependencies": {
42
- "@lowdefy/errors": "0.0.0-experimental-20261007124348",
43
- "@lowdefy/helpers": "0.0.0-experimental-20261007124348",
42
+ "@lowdefy/errors": "0.0.0-experimental-20261009120232",
43
+ "@lowdefy/helpers": "0.0.0-experimental-20261009120232",
44
44
  "better-auth": "1.7.7",
45
45
  "jose": "^6.2.3"
46
46
  },