create-disposabl-app 0.9.1 → 0.10.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.
- package/dist/disposabl.js +1 -1
- package/dist/index.js +1 -1
- package/dist/templates/default/.github/workflows/pipeline.yml +1 -1
- package/dist/templates/default/bun.lock +72 -178
- package/dist/templates/default/package.json +1 -2
- package/dist/templates/default/packages/backend/README.md +3 -1
- package/dist/templates/default/packages/backend/convex/_generated/api.d.ts +6 -0
- package/dist/templates/default/packages/backend/convex/_generated/server.d.ts +0 -2
- package/dist/templates/default/packages/backend/convex/auth.config.ts +2 -10
- package/dist/templates/default/packages/backend/convex/convex.config.ts +3 -14
- package/dist/templates/default/packages/backend/convex/mcpEnterprise/README.md +42 -0
- package/dist/templates/default/packages/backend/convex/mcpEnterprise/internal.ts +153 -0
- package/dist/templates/default/packages/backend/convex/mcpEnterprise/provision.ts +102 -0
- package/dist/templates/default/packages/backend/convex/mcpEnterprise/validator.ts +35 -0
- package/dist/templates/default/packages/backend/convex/schema.ts +18 -0
- package/dist/templates/default/packages/backend/package.json +0 -1
- package/dist/templates/default/packages/disposabl-kit/package.json +4 -2
- package/dist/templates/default/packages/disposabl-kit/server/http.ts +19 -12
- package/dist/templates/default/packages/disposabl-kit/server/lib/functions.ts +12 -0
- package/dist/templates/default/packages/disposabl-kit/server/mcp/enterprise.ts +267 -0
- package/dist/templates/default/packages/disposabl-kit/server/mcp/identity.ts +33 -0
- package/dist/templates/default/vendor/README.md +30 -0
- package/dist/templates/default/vendor/convex-auth-6c0ebf3f.tgz +0 -0
- package/package.json +1 -1
- package/dist/templates/default/patches/@convex-dev%2Fauth@2.0.0-beta.0.patch +0 -310
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import {
|
|
3
|
+
internalMutation,
|
|
4
|
+
internalQuery,
|
|
5
|
+
} from "@disposabl/disposabl-kit/server/lib/functions";
|
|
6
|
+
import {
|
|
7
|
+
normalizeEmail,
|
|
8
|
+
CLAUDE_CLIENT_ID,
|
|
9
|
+
} from "@disposabl/disposabl-kit/server/mcp/identity";
|
|
10
|
+
import { internal } from "../_generated/api";
|
|
11
|
+
import { exchangeArgs, organizationFields } from "./validator";
|
|
12
|
+
|
|
13
|
+
export const organization = internalQuery({
|
|
14
|
+
args: { issuer: v.string() },
|
|
15
|
+
returns: v.union(v.null(), v.object(organizationFields)),
|
|
16
|
+
handler: async (ctx, { issuer }) => {
|
|
17
|
+
const org = await ctx.db
|
|
18
|
+
.query("mcpOrganizations")
|
|
19
|
+
.withIndex("by_issuer", (q) => q.eq("issuer", issuer))
|
|
20
|
+
.unique();
|
|
21
|
+
if (!org?.enabled) return null;
|
|
22
|
+
return {
|
|
23
|
+
tenantId: org.tenantId,
|
|
24
|
+
issuer: org.issuer,
|
|
25
|
+
enabled: org.enabled,
|
|
26
|
+
scopes: org.scopes,
|
|
27
|
+
revision: org.revision,
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// One transaction binds the subject, consumes the assertion, and issues a token.
|
|
33
|
+
export const exchange = internalMutation({
|
|
34
|
+
args: exchangeArgs,
|
|
35
|
+
returns: v.union(v.null(), v.object({ expiresIn: v.number() })),
|
|
36
|
+
handler: async (ctx, args) => {
|
|
37
|
+
const org = await ctx.db
|
|
38
|
+
.query("mcpOrganizations")
|
|
39
|
+
.withIndex("by_issuer", (q) => q.eq("issuer", args.issuer))
|
|
40
|
+
.unique();
|
|
41
|
+
if (
|
|
42
|
+
!org?.enabled ||
|
|
43
|
+
org.revision !== args.revision ||
|
|
44
|
+
args.assertionExpiresAt <= Date.now() ||
|
|
45
|
+
args.scopes.some((s) => !org.scopes.includes(s))
|
|
46
|
+
)
|
|
47
|
+
return null;
|
|
48
|
+
const replay = await ctx.db
|
|
49
|
+
.query("mcpEnterpriseTokens")
|
|
50
|
+
.withIndex("by_organizationId_jti", (q) =>
|
|
51
|
+
q.eq("organizationId", org._id).eq("jti", args.jti),
|
|
52
|
+
)
|
|
53
|
+
.unique();
|
|
54
|
+
if (replay) return null;
|
|
55
|
+
let member = await ctx.db
|
|
56
|
+
.query("mcpMembers")
|
|
57
|
+
.withIndex("by_organizationId_subject", (q) =>
|
|
58
|
+
q.eq("organizationId", org._id).eq("subject", args.subject),
|
|
59
|
+
)
|
|
60
|
+
.unique();
|
|
61
|
+
if (!member && args.email) {
|
|
62
|
+
member = await ctx.db
|
|
63
|
+
.query("mcpMembers")
|
|
64
|
+
.withIndex("by_organizationId_verifiedEmail", (q) =>
|
|
65
|
+
q
|
|
66
|
+
.eq("organizationId", org._id)
|
|
67
|
+
.eq("verifiedEmail", normalizeEmail(args.email!)),
|
|
68
|
+
)
|
|
69
|
+
.unique();
|
|
70
|
+
if (member?.subject) return null;
|
|
71
|
+
}
|
|
72
|
+
if (!member || !(await ctx.db.get("users", member.userId))) return null;
|
|
73
|
+
if (!member.subject)
|
|
74
|
+
await ctx.db.patch("mcpMembers", member._id, { subject: args.subject });
|
|
75
|
+
const expiresAt = Date.now() + 300_000;
|
|
76
|
+
const tokenId = await ctx.db.insert("mcpEnterpriseTokens", {
|
|
77
|
+
organizationId: org._id,
|
|
78
|
+
memberId: member._id,
|
|
79
|
+
revision: org.revision,
|
|
80
|
+
hash: args.hash,
|
|
81
|
+
jti: args.jti,
|
|
82
|
+
expiresAt,
|
|
83
|
+
scopes: args.scopes,
|
|
84
|
+
revoked: false,
|
|
85
|
+
});
|
|
86
|
+
// Retain consumed jti until both the assertion and token expire.
|
|
87
|
+
await ctx.scheduler.runAt(
|
|
88
|
+
Math.max(expiresAt, args.assertionExpiresAt) + 30_000,
|
|
89
|
+
internal.mcpEnterprise.internal.expire,
|
|
90
|
+
{ tokenId },
|
|
91
|
+
);
|
|
92
|
+
return { expiresIn: 300 };
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
export const verify = internalQuery({
|
|
97
|
+
args: { hash: v.string(), now: v.number() },
|
|
98
|
+
returns: v.union(
|
|
99
|
+
v.null(),
|
|
100
|
+
v.object({
|
|
101
|
+
userId: v.string(),
|
|
102
|
+
scopes: v.array(v.string()),
|
|
103
|
+
clientId: v.string(),
|
|
104
|
+
connectionId: v.string(),
|
|
105
|
+
}),
|
|
106
|
+
),
|
|
107
|
+
handler: async (ctx, { hash, now }) => {
|
|
108
|
+
const token = await ctx.db
|
|
109
|
+
.query("mcpEnterpriseTokens")
|
|
110
|
+
.withIndex("by_hash", (q) => q.eq("hash", hash))
|
|
111
|
+
.unique();
|
|
112
|
+
if (!token || token.revoked || token.expiresAt <= now) return null;
|
|
113
|
+
const org = await ctx.db.get("mcpOrganizations", token.organizationId);
|
|
114
|
+
const member = await ctx.db.get("mcpMembers", token.memberId);
|
|
115
|
+
if (
|
|
116
|
+
!org?.enabled ||
|
|
117
|
+
org.revision !== token.revision ||
|
|
118
|
+
!member ||
|
|
119
|
+
member.organizationId !== org._id ||
|
|
120
|
+
!(await ctx.db.get("users", member.userId))
|
|
121
|
+
)
|
|
122
|
+
return null;
|
|
123
|
+
return {
|
|
124
|
+
userId: member.userId,
|
|
125
|
+
scopes: token.scopes,
|
|
126
|
+
clientId: CLAUDE_CLIENT_ID,
|
|
127
|
+
connectionId: token._id,
|
|
128
|
+
};
|
|
129
|
+
},
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
export const revoke = internalMutation({
|
|
133
|
+
args: { hash: v.string() },
|
|
134
|
+
returns: v.null(),
|
|
135
|
+
handler: async (ctx, { hash }) => {
|
|
136
|
+
const token = await ctx.db
|
|
137
|
+
.query("mcpEnterpriseTokens")
|
|
138
|
+
.withIndex("by_hash", (q) => q.eq("hash", hash))
|
|
139
|
+
.unique();
|
|
140
|
+
if (token)
|
|
141
|
+
await ctx.db.patch("mcpEnterpriseTokens", token._id, { revoked: true });
|
|
142
|
+
return null;
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
export const expire = internalMutation({
|
|
147
|
+
args: { tokenId: v.id("mcpEnterpriseTokens") },
|
|
148
|
+
returns: v.null(),
|
|
149
|
+
handler: async (ctx, { tokenId }) => {
|
|
150
|
+
await ctx.db.delete("mcpEnterpriseTokens", tokenId);
|
|
151
|
+
return null;
|
|
152
|
+
},
|
|
153
|
+
});
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
import { internalMutation } from "@disposabl/disposabl-kit/server/lib/functions";
|
|
3
|
+
import {
|
|
4
|
+
claudeIssuer,
|
|
5
|
+
normalizeEmail,
|
|
6
|
+
} from "@disposabl/disposabl-kit/server/mcp/identity";
|
|
7
|
+
|
|
8
|
+
// Internal only. Call from a tenant-admin entrypoint after checking its role,
|
|
9
|
+
// or use the Convex dashboard/CLI as a deployment administrator.
|
|
10
|
+
export const configure = internalMutation({
|
|
11
|
+
args: {
|
|
12
|
+
tenantId: v.string(),
|
|
13
|
+
issuer: v.string(),
|
|
14
|
+
enabled: v.boolean(),
|
|
15
|
+
scopes: v.array(v.string()),
|
|
16
|
+
},
|
|
17
|
+
returns: v.id("mcpOrganizations"),
|
|
18
|
+
handler: async (ctx, args) => {
|
|
19
|
+
claudeIssuer(args.issuer);
|
|
20
|
+
if (
|
|
21
|
+
!args.tenantId.trim() ||
|
|
22
|
+
args.tenantId.length > 200 ||
|
|
23
|
+
args.scopes.length > 100
|
|
24
|
+
)
|
|
25
|
+
throw new Error("Invalid organization configuration.");
|
|
26
|
+
const existing = await ctx.db
|
|
27
|
+
.query("mcpOrganizations")
|
|
28
|
+
.withIndex("by_tenantId", (q) => q.eq("tenantId", args.tenantId))
|
|
29
|
+
.unique();
|
|
30
|
+
const claimed = await ctx.db
|
|
31
|
+
.query("mcpOrganizations")
|
|
32
|
+
.withIndex("by_issuer", (q) => q.eq("issuer", args.issuer))
|
|
33
|
+
.unique();
|
|
34
|
+
if (claimed && claimed._id !== existing?._id)
|
|
35
|
+
throw new Error("Issuer already belongs to another organization.");
|
|
36
|
+
// Issuer replacement needs new member bindings; never silently reuse subjects.
|
|
37
|
+
if (existing && existing.issuer !== args.issuer)
|
|
38
|
+
throw new Error(
|
|
39
|
+
"Disable the old organization and provision a new tenant ID for a new issuer.",
|
|
40
|
+
);
|
|
41
|
+
if (existing) {
|
|
42
|
+
await ctx.db.patch("mcpOrganizations", existing._id, {
|
|
43
|
+
...args,
|
|
44
|
+
revision: existing.revision + 1,
|
|
45
|
+
});
|
|
46
|
+
return existing._id;
|
|
47
|
+
}
|
|
48
|
+
return ctx.db.insert("mcpOrganizations", { ...args, revision: 1 });
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
// The email must come from a verified authentication callback or a verified
|
|
53
|
+
// directory membership. Never expose this operation with client-supplied email.
|
|
54
|
+
export const addMember = internalMutation({
|
|
55
|
+
args: {
|
|
56
|
+
organizationId: v.id("mcpOrganizations"),
|
|
57
|
+
userId: v.id("users"),
|
|
58
|
+
verifiedEmail: v.string(),
|
|
59
|
+
},
|
|
60
|
+
returns: v.id("mcpMembers"),
|
|
61
|
+
handler: async (ctx, args) => {
|
|
62
|
+
if (
|
|
63
|
+
!(await ctx.db.get("mcpOrganizations", args.organizationId)) ||
|
|
64
|
+
!(await ctx.db.get("users", args.userId))
|
|
65
|
+
)
|
|
66
|
+
throw new Error("Organization and existing user are required.");
|
|
67
|
+
const verifiedEmail = normalizeEmail(args.verifiedEmail);
|
|
68
|
+
const member = await ctx.db
|
|
69
|
+
.query("mcpMembers")
|
|
70
|
+
.withIndex("by_organizationId_userId", (q) =>
|
|
71
|
+
q.eq("organizationId", args.organizationId).eq("userId", args.userId),
|
|
72
|
+
)
|
|
73
|
+
.unique();
|
|
74
|
+
const other = await ctx.db
|
|
75
|
+
.query("mcpMembers")
|
|
76
|
+
.withIndex("by_organizationId_verifiedEmail", (q) =>
|
|
77
|
+
q
|
|
78
|
+
.eq("organizationId", args.organizationId)
|
|
79
|
+
.eq("verifiedEmail", verifiedEmail),
|
|
80
|
+
)
|
|
81
|
+
.unique();
|
|
82
|
+
if (other && other.userId !== args.userId)
|
|
83
|
+
throw new Error("Email already belongs to another member.");
|
|
84
|
+
if (member) {
|
|
85
|
+
if (member.verifiedEmail !== verifiedEmail)
|
|
86
|
+
throw new Error(
|
|
87
|
+
"Remove the old membership before changing its verified email.",
|
|
88
|
+
);
|
|
89
|
+
return member._id;
|
|
90
|
+
}
|
|
91
|
+
return ctx.db.insert("mcpMembers", { ...args, verifiedEmail });
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
export const removeMember = internalMutation({
|
|
96
|
+
args: { memberId: v.id("mcpMembers") },
|
|
97
|
+
returns: v.null(),
|
|
98
|
+
handler: async (ctx, { memberId }) => {
|
|
99
|
+
await ctx.db.delete("mcpMembers", memberId);
|
|
100
|
+
return null;
|
|
101
|
+
},
|
|
102
|
+
});
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { v } from "convex/values";
|
|
2
|
+
|
|
3
|
+
export const organizationFields = {
|
|
4
|
+
tenantId: v.string(),
|
|
5
|
+
issuer: v.string(),
|
|
6
|
+
enabled: v.boolean(),
|
|
7
|
+
scopes: v.array(v.string()),
|
|
8
|
+
revision: v.number(),
|
|
9
|
+
};
|
|
10
|
+
export const memberFields = {
|
|
11
|
+
organizationId: v.id("mcpOrganizations"),
|
|
12
|
+
userId: v.id("users"),
|
|
13
|
+
verifiedEmail: v.string(),
|
|
14
|
+
subject: v.optional(v.string()),
|
|
15
|
+
};
|
|
16
|
+
export const tokenFields = {
|
|
17
|
+
organizationId: v.id("mcpOrganizations"),
|
|
18
|
+
memberId: v.id("mcpMembers"),
|
|
19
|
+
revision: v.number(),
|
|
20
|
+
hash: v.string(),
|
|
21
|
+
jti: v.string(),
|
|
22
|
+
expiresAt: v.number(),
|
|
23
|
+
scopes: v.array(v.string()),
|
|
24
|
+
revoked: v.boolean(),
|
|
25
|
+
};
|
|
26
|
+
export const exchangeArgs = {
|
|
27
|
+
issuer: v.string(),
|
|
28
|
+
revision: v.number(),
|
|
29
|
+
subject: v.string(),
|
|
30
|
+
email: v.optional(v.string()),
|
|
31
|
+
jti: v.string(),
|
|
32
|
+
assertionExpiresAt: v.number(),
|
|
33
|
+
scopes: v.array(v.string()),
|
|
34
|
+
hash: v.string(),
|
|
35
|
+
};
|
|
@@ -1,5 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
organizationFields,
|
|
3
|
+
memberFields,
|
|
4
|
+
tokenFields,
|
|
5
|
+
} from "./mcpEnterprise/validator";
|
|
1
6
|
import { defineSchema, defineTable } from "convex/server";
|
|
2
7
|
|
|
3
8
|
export default defineSchema({
|
|
9
|
+
mcpOrganizations: defineTable(organizationFields)
|
|
10
|
+
.index("by_tenantId", ["tenantId"])
|
|
11
|
+
.index("by_issuer", ["issuer"]),
|
|
12
|
+
mcpMembers: defineTable(memberFields)
|
|
13
|
+
.index("by_organizationId_userId", ["organizationId", "userId"])
|
|
14
|
+
.index("by_organizationId_verifiedEmail", [
|
|
15
|
+
"organizationId",
|
|
16
|
+
"verifiedEmail",
|
|
17
|
+
])
|
|
18
|
+
.index("by_organizationId_subject", ["organizationId", "subject"]),
|
|
19
|
+
mcpEnterpriseTokens: defineTable(tokenFields)
|
|
20
|
+
.index("by_hash", ["hash"])
|
|
21
|
+
.index("by_organizationId_jti", ["organizationId", "jti"]),
|
|
4
22
|
users: defineTable({}),
|
|
5
23
|
});
|
|
@@ -32,7 +32,8 @@
|
|
|
32
32
|
"@convex-dev/auth": "catalog:",
|
|
33
33
|
"@convex-dev/mcp": "catalog:",
|
|
34
34
|
"@convex-dev/static-hosting": "catalog:",
|
|
35
|
-
"@tanstack/react-router": "latest"
|
|
35
|
+
"@tanstack/react-router": "latest",
|
|
36
|
+
"jose": "^6.2.15"
|
|
36
37
|
},
|
|
37
38
|
"devDependencies": {
|
|
38
39
|
"@tailwindcss/vite": "^4",
|
|
@@ -60,7 +61,8 @@
|
|
|
60
61
|
"./platforms": "./platforms.ts",
|
|
61
62
|
"./mobile": "./mobile/index.ts",
|
|
62
63
|
"./features": "./features.ts",
|
|
63
|
-
"./mobile/expo-plugin": "./mobile/expo-plugin.cjs"
|
|
64
|
+
"./mobile/expo-plugin": "./mobile/expo-plugin.cjs",
|
|
65
|
+
"./server/mcp/identity": "./server/mcp/identity.ts"
|
|
64
66
|
},
|
|
65
67
|
"peerDependencies": {
|
|
66
68
|
"expo": "~58.0.19",
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getSessionUserId } from "./lib/functions";
|
|
2
2
|
import { McpServer } from "@convex-dev/mcp";
|
|
3
|
+
import { EnterpriseMcpServer } from "./mcp/enterprise";
|
|
3
4
|
import { httpActionGeneric, httpRouter } from "convex/server";
|
|
4
5
|
import { components } from "../../backend/convex/_generated/api";
|
|
5
6
|
import { env } from "../../backend/convex/_generated/server";
|
|
@@ -27,16 +28,22 @@ if (
|
|
|
27
28
|
export const platformSpec = platforms.spec;
|
|
28
29
|
|
|
29
30
|
const enabled = validatePlatforms(config.platforms);
|
|
30
|
-
const mcp = enabled.some(
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
31
|
+
const mcp: McpServer | undefined = enabled.some(
|
|
32
|
+
(platform) => platform === "mcp" || platform === "api",
|
|
33
|
+
)
|
|
34
|
+
? new (enabled.includes("mcp") ? EnterpriseMcpServer : McpServer)(
|
|
35
|
+
components.mcp,
|
|
36
|
+
{
|
|
37
|
+
name: "disposabl",
|
|
38
|
+
title: "Disposabl",
|
|
39
|
+
version: "1.0.0",
|
|
40
|
+
siteUrl: env.CONVEX_SITE_URL,
|
|
41
|
+
consentUrl: `${env.CONVEX_SITE_URL}/consent`,
|
|
42
|
+
scopes: {},
|
|
43
|
+
clientMetadataDocumentHosts: ["claude.ai"],
|
|
44
|
+
tools: platforms.tools,
|
|
45
|
+
},
|
|
46
|
+
)
|
|
40
47
|
: undefined;
|
|
41
48
|
|
|
42
49
|
// Keep the enabled API types for consumers; disabled exports are absent at runtime.
|
|
@@ -47,7 +54,7 @@ export const {
|
|
|
47
54
|
revokeConnection,
|
|
48
55
|
createApiKey,
|
|
49
56
|
} =
|
|
50
|
-
mcp?.api({ getUserId:
|
|
57
|
+
mcp?.api({ getUserId: getSessionUserId }) ??
|
|
51
58
|
({} as ReturnType<McpServer["api"]>);
|
|
52
59
|
|
|
53
60
|
export default function createHttpRouter() {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { getAuthUserId } from "@convex-dev/auth/server";
|
|
2
|
+
import type { Auth } from "convex/server";
|
|
1
3
|
import {
|
|
2
4
|
v,
|
|
3
5
|
type GenericValidator,
|
|
@@ -35,3 +37,13 @@ const withPlatforms = <TDefinition, TResult extends object>(
|
|
|
35
37
|
export const internalQuery = withPlatforms(nativeQuery);
|
|
36
38
|
export const internalMutation = withPlatforms(nativeMutation);
|
|
37
39
|
export const internalAction = withPlatforms(nativeAction);
|
|
40
|
+
|
|
41
|
+
// The MCP alpha types its callback as auth-only; Convex Auth reboot also
|
|
42
|
+
// checks the live session via runQuery. Actual Convex function contexts have it.
|
|
43
|
+
export async function getSessionUserId(ctx: { auth: Auth }) {
|
|
44
|
+
if (!("runQuery" in ctx) || typeof ctx.runQuery !== "function")
|
|
45
|
+
throw new Error(
|
|
46
|
+
"Session authentication requires a Convex function context.",
|
|
47
|
+
);
|
|
48
|
+
return getAuthUserId(ctx as Parameters<typeof getAuthUserId>[0]);
|
|
49
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { McpServer, type McpUser, type ToolCtx } from "@convex-dev/mcp";
|
|
2
|
+
import { httpActionGeneric, httpRouter, type HttpRouter } from "convex/server";
|
|
3
|
+
import { createLocalJWKSet, decodeJwt, jwtVerify } from "jose";
|
|
4
|
+
import { internal } from "../../../backend/convex/_generated/api";
|
|
5
|
+
import {
|
|
6
|
+
claudeIssuer,
|
|
7
|
+
CLAUDE_CLIENT_ID,
|
|
8
|
+
ID_JAG_PROFILE,
|
|
9
|
+
JWT_GRANT,
|
|
10
|
+
TOKEN_PREFIX,
|
|
11
|
+
tokenHash,
|
|
12
|
+
} from "./identity";
|
|
13
|
+
|
|
14
|
+
const headers = {
|
|
15
|
+
"Cache-Control": "no-store",
|
|
16
|
+
Pragma: "no-cache",
|
|
17
|
+
"Access-Control-Allow-Origin": "*",
|
|
18
|
+
};
|
|
19
|
+
const json = (body: unknown, status = 200) =>
|
|
20
|
+
Response.json(body, { status, headers });
|
|
21
|
+
const invalid = () => json({ error: "invalid_grant" }, 400);
|
|
22
|
+
|
|
23
|
+
// Only Anthropic's identity host is fetched. Neither JWT headers nor an
|
|
24
|
+
// untrusted issuer can supply a URL, and redirects are never followed.
|
|
25
|
+
async function identityDocument(
|
|
26
|
+
address: string,
|
|
27
|
+
): Promise<Record<string, unknown>> {
|
|
28
|
+
const url = new URL(address);
|
|
29
|
+
if (
|
|
30
|
+
url.origin !== "https://identity.anthropic.com" ||
|
|
31
|
+
url.username ||
|
|
32
|
+
url.password ||
|
|
33
|
+
url.hash
|
|
34
|
+
)
|
|
35
|
+
throw new Error("Invalid identity document URL");
|
|
36
|
+
const response = await fetch(url, {
|
|
37
|
+
redirect: "error",
|
|
38
|
+
signal: AbortSignal.timeout(5000),
|
|
39
|
+
});
|
|
40
|
+
if (!response.ok || !response.body)
|
|
41
|
+
throw new Error("Identity document unavailable");
|
|
42
|
+
const reader = response.body.getReader();
|
|
43
|
+
const chunks: Uint8Array[] = [];
|
|
44
|
+
let size = 0;
|
|
45
|
+
try {
|
|
46
|
+
for (;;) {
|
|
47
|
+
const { done, value } = await reader.read();
|
|
48
|
+
if (done) break;
|
|
49
|
+
size += value.byteLength;
|
|
50
|
+
if (size > 262144) throw new Error("Identity document too large");
|
|
51
|
+
chunks.push(value);
|
|
52
|
+
}
|
|
53
|
+
} finally {
|
|
54
|
+
await reader.cancel();
|
|
55
|
+
}
|
|
56
|
+
const bytes = new Uint8Array(size);
|
|
57
|
+
let offset = 0;
|
|
58
|
+
for (const chunk of chunks) {
|
|
59
|
+
bytes.set(chunk, offset);
|
|
60
|
+
offset += chunk.length;
|
|
61
|
+
}
|
|
62
|
+
const value: unknown = JSON.parse(new TextDecoder().decode(bytes));
|
|
63
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
64
|
+
throw new Error("Invalid identity document");
|
|
65
|
+
return value as Record<string, unknown>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export class EnterpriseMcpServer extends McpServer {
|
|
69
|
+
override authorizationServerMetadata() {
|
|
70
|
+
const metadata = super.authorizationServerMetadata();
|
|
71
|
+
return {
|
|
72
|
+
...metadata,
|
|
73
|
+
grant_types_supported: [...metadata.grant_types_supported, JWT_GRANT],
|
|
74
|
+
authorization_grant_profiles_supported: [ID_JAG_PROFILE],
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
override registerRoutes(http: HttpRouter) {
|
|
79
|
+
const routes = httpRouter();
|
|
80
|
+
super.registerRoutes(routes);
|
|
81
|
+
for (const [path, method, handler] of routes.getRoutes()) {
|
|
82
|
+
// Convex's router invokes this runtime method too; its public declaration
|
|
83
|
+
// strips runtime-only members. Keep the compatibility boundary here.
|
|
84
|
+
const original = handler as typeof handler & {
|
|
85
|
+
invokeHttpAction: (request: Request) => Promise<Response>;
|
|
86
|
+
};
|
|
87
|
+
if (
|
|
88
|
+
method !== "POST" ||
|
|
89
|
+
![`${this.path}/oauth/token`, `${this.path}/oauth/revoke`].includes(
|
|
90
|
+
path,
|
|
91
|
+
)
|
|
92
|
+
) {
|
|
93
|
+
http.route({ path, method, handler });
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
http.route({
|
|
97
|
+
path,
|
|
98
|
+
method,
|
|
99
|
+
handler: httpActionGeneric(async (ctx, request) => {
|
|
100
|
+
// Parse a clone so normal OAuth/device requests retain their original body.
|
|
101
|
+
if (
|
|
102
|
+
!request.headers
|
|
103
|
+
.get("Content-Type")
|
|
104
|
+
?.startsWith("application/x-www-form-urlencoded")
|
|
105
|
+
)
|
|
106
|
+
return original.invokeHttpAction(request);
|
|
107
|
+
const text = await request.clone().text();
|
|
108
|
+
if (text.length > 32768)
|
|
109
|
+
return json({ error: "invalid_request" }, 400);
|
|
110
|
+
const form = new URLSearchParams(text);
|
|
111
|
+
if (path.endsWith("/token") && form.get("grant_type") === JWT_GRANT) {
|
|
112
|
+
for (const key of new Set(form.keys()))
|
|
113
|
+
if (form.getAll(key).length !== 1)
|
|
114
|
+
return json({ error: "invalid_request" }, 400);
|
|
115
|
+
return this.exchangeAssertion(ctx, form);
|
|
116
|
+
}
|
|
117
|
+
const token = form.get("token");
|
|
118
|
+
if (path.endsWith("/revoke") && token?.startsWith(TOKEN_PREFIX)) {
|
|
119
|
+
await ctx.runMutation(internal.mcpEnterprise.internal.revoke, {
|
|
120
|
+
hash: await tokenHash(token),
|
|
121
|
+
});
|
|
122
|
+
return json({});
|
|
123
|
+
}
|
|
124
|
+
return original.invokeHttpAction(request);
|
|
125
|
+
}),
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
override async authenticate(
|
|
131
|
+
ctx: ToolCtx,
|
|
132
|
+
request: Request,
|
|
133
|
+
): Promise<McpUser | null> {
|
|
134
|
+
const token = request.headers
|
|
135
|
+
.get("Authorization")
|
|
136
|
+
?.match(/^Bearer\s+(\S+)$/i)?.[1];
|
|
137
|
+
if (!token?.startsWith(TOKEN_PREFIX))
|
|
138
|
+
return super.authenticate(ctx, request);
|
|
139
|
+
// Enterprise grants authorize this MCP resource only, never the HTTP API.
|
|
140
|
+
if (
|
|
141
|
+
new URL(request.url).pathname !== this.path ||
|
|
142
|
+
!/^mcp_ema_[0-9a-f]{64}$/.test(token)
|
|
143
|
+
)
|
|
144
|
+
return null;
|
|
145
|
+
return ctx.runQuery(internal.mcpEnterprise.internal.verify, {
|
|
146
|
+
hash: await tokenHash(token),
|
|
147
|
+
now: Date.now(),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
private async exchangeAssertion(
|
|
152
|
+
ctx: ToolCtx,
|
|
153
|
+
form: URLSearchParams,
|
|
154
|
+
): Promise<Response> {
|
|
155
|
+
try {
|
|
156
|
+
const assertion = form.get("assertion");
|
|
157
|
+
if (
|
|
158
|
+
!assertion ||
|
|
159
|
+
assertion.length > 16384 ||
|
|
160
|
+
form.get("client_id") !== CLAUDE_CLIENT_ID ||
|
|
161
|
+
form.has("client_secret") ||
|
|
162
|
+
form.has("client_assertion")
|
|
163
|
+
)
|
|
164
|
+
return invalid();
|
|
165
|
+
if (form.has("resource") && form.get("resource") !== this.resource)
|
|
166
|
+
return invalid();
|
|
167
|
+
const issuer = claudeIssuer(decodeJwt(assertion).iss ?? "");
|
|
168
|
+
const organization = await ctx.runQuery(
|
|
169
|
+
internal.mcpEnterprise.internal.organization,
|
|
170
|
+
{ issuer },
|
|
171
|
+
);
|
|
172
|
+
if (!organization) return invalid();
|
|
173
|
+
const discovery = await identityDocument(
|
|
174
|
+
`${issuer}/.well-known/openid-configuration`,
|
|
175
|
+
);
|
|
176
|
+
if (discovery.issuer !== issuer || typeof discovery.jwks_uri !== "string")
|
|
177
|
+
return invalid();
|
|
178
|
+
const jwks = await identityDocument(discovery.jwks_uri);
|
|
179
|
+
if (!Array.isArray(jwks.keys)) return invalid();
|
|
180
|
+
const { payload } = await jwtVerify(
|
|
181
|
+
assertion,
|
|
182
|
+
createLocalJWKSet({ keys: jwks.keys }),
|
|
183
|
+
{
|
|
184
|
+
issuer,
|
|
185
|
+
audience: this.issuer,
|
|
186
|
+
typ: "oauth-id-jag+jwt",
|
|
187
|
+
algorithms: ["RS256", "ES256"],
|
|
188
|
+
requiredClaims: ["sub", "jti", "iat", "exp", "client_id"],
|
|
189
|
+
maxTokenAge: "10 minutes",
|
|
190
|
+
},
|
|
191
|
+
);
|
|
192
|
+
const now = Date.now() / 1000;
|
|
193
|
+
if (
|
|
194
|
+
payload.client_id !== CLAUDE_CLIENT_ID ||
|
|
195
|
+
!payload.sub ||
|
|
196
|
+
payload.sub.length > 512 ||
|
|
197
|
+
!payload.jti ||
|
|
198
|
+
payload.jti.length > 512 ||
|
|
199
|
+
!payload.exp ||
|
|
200
|
+
!payload.iat ||
|
|
201
|
+
payload.exp - payload.iat > 600 ||
|
|
202
|
+
payload.iat > now ||
|
|
203
|
+
payload.aud !== this.issuer
|
|
204
|
+
)
|
|
205
|
+
return invalid();
|
|
206
|
+
if (payload.resource !== undefined && payload.resource !== this.resource)
|
|
207
|
+
return invalid();
|
|
208
|
+
if (
|
|
209
|
+
payload.tenant !== undefined &&
|
|
210
|
+
payload.tenant !== organization.tenantId
|
|
211
|
+
)
|
|
212
|
+
return invalid();
|
|
213
|
+
if (payload.email !== undefined && typeof payload.email !== "string")
|
|
214
|
+
return invalid();
|
|
215
|
+
if (payload.scope !== undefined && typeof payload.scope !== "string")
|
|
216
|
+
return invalid();
|
|
217
|
+
// No default-to-all scopes. Both the signed grant and tenant policy bound access.
|
|
218
|
+
const scopes =
|
|
219
|
+
typeof payload.scope === "string"
|
|
220
|
+
? [...new Set(payload.scope.split(/\s+/).filter(Boolean))]
|
|
221
|
+
: [];
|
|
222
|
+
const requested =
|
|
223
|
+
form.get("scope")?.split(/\s+/).filter(Boolean) ?? scopes;
|
|
224
|
+
if (
|
|
225
|
+
requested.some(
|
|
226
|
+
(scope) =>
|
|
227
|
+
!scopes.includes(scope) ||
|
|
228
|
+
!organization.scopes.includes(scope) ||
|
|
229
|
+
!(scope in (this.options.scopes ?? {})),
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
return json({ error: "invalid_scope" }, 400);
|
|
233
|
+
const random = crypto.getRandomValues(new Uint8Array(32));
|
|
234
|
+
const token =
|
|
235
|
+
TOKEN_PREFIX +
|
|
236
|
+
Array.from(random, (byte) => byte.toString(16).padStart(2, "0")).join(
|
|
237
|
+
"",
|
|
238
|
+
);
|
|
239
|
+
const result = await ctx.runMutation(
|
|
240
|
+
internal.mcpEnterprise.internal.exchange,
|
|
241
|
+
{
|
|
242
|
+
issuer,
|
|
243
|
+
revision: organization.revision,
|
|
244
|
+
subject: payload.sub,
|
|
245
|
+
...(typeof payload.email === "string"
|
|
246
|
+
? { email: payload.email }
|
|
247
|
+
: {}),
|
|
248
|
+
jti: payload.jti,
|
|
249
|
+
assertionExpiresAt: payload.exp * 1000,
|
|
250
|
+
scopes: requested,
|
|
251
|
+
hash: await tokenHash(token),
|
|
252
|
+
},
|
|
253
|
+
);
|
|
254
|
+
return result
|
|
255
|
+
? json({
|
|
256
|
+
access_token: token,
|
|
257
|
+
token_type: "Bearer",
|
|
258
|
+
expires_in: result.expiresIn,
|
|
259
|
+
scope: requested.join(" "),
|
|
260
|
+
})
|
|
261
|
+
: invalid();
|
|
262
|
+
} catch {
|
|
263
|
+
// Never log assertions, emails, or tokens, or disclose membership on errors.
|
|
264
|
+
return invalid();
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|