@shivaedev/mcp 0.3.0 → 0.5.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/CHANGELOG.md +23 -0
- package/README.md +10 -15
- package/dist/adapters/betterAuth.d.ts +17 -10
- package/dist/adapters/betterAuth.d.ts.map +1 -1
- package/dist/adapters/betterAuth.js +13 -16
- package/dist/adapters/betterAuth.js.map +1 -1
- package/package.json +9 -13
- package/src/adapters/betterAuth.ts +20 -23
- package/dist/adapters/oauthGrants.d.ts +0 -32
- package/dist/adapters/oauthGrants.d.ts.map +0 -1
- package/dist/adapters/oauthGrants.js +0 -43
- package/dist/adapters/oauthGrants.js.map +0 -1
- package/src/adapters/oauthGrants.ts +0 -56
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0 - 2026-11-02
|
|
4
|
+
|
|
5
|
+
### Breaking
|
|
6
|
+
|
|
7
|
+
- MCP no longer returns `revokeClient` or `revokeAllClients` from `betterAuthMcp`. Read `OauthGrants` from `@shivaedev/identity/server/oauthGrants.ts` in an Effect and call those methods on the service. Provide `betterAuthOauthGrants({ auth: mounted.auth, admitsUser: mounted.admitsUser })` to that Effect and to `betterAuthMcp`; remove the latter's `admitsUser` option. Applications continue to authorize grant management operations.
|
|
8
|
+
|
|
9
|
+
## 0.4.0 - 2026-11-02
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Identity mounts expose `admitsUser(userId)` to check the current sign-in policy for authenticated users on other transports, without caching rule verdicts.
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- Serve OAuth discovery at the configured issuer's discovery path, including custom and root issuers.
|
|
18
|
+
- Keep OAuth metadata rejections in the typed `AuthUnavailable` channel and retain the original cause of configuration, metadata and grant failures.
|
|
19
|
+
- Accept case-insensitive bearer authorization schemes.
|
|
20
|
+
- Identity checks with a zero recheck interval start an independent rule lookup even while another check for the same account is pending.
|
|
21
|
+
|
|
22
|
+
### Breaking
|
|
23
|
+
|
|
24
|
+
- MCP's `betterAuthMcp` requires `admitsUser`. Pass `admitsUser: mounted.admitsUser` from `betterAuthMount` alongside `auth: mounted.auth`. Each MCP request refuses users denied by the identity sign-in policy; existing tokens follow admission changes on the next request.
|
|
25
|
+
|
|
3
26
|
## 0.3.0 - 2026-11-01
|
|
4
27
|
|
|
5
28
|
### Changed
|
package/README.md
CHANGED
|
@@ -72,8 +72,9 @@ The Better Auth adapter is an optional edge module. Add its provider to the auth
|
|
|
72
72
|
import { admin, jwt } from "better-auth/plugins";
|
|
73
73
|
import { Effect, Layer } from "effect";
|
|
74
74
|
import { HttpRouter } from "effect/http";
|
|
75
|
-
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/mount.ts";
|
|
76
|
-
import {
|
|
75
|
+
import { betterAuthMount } from "@shivaedev/identity/server/better-auth/adapters/mount.ts";
|
|
76
|
+
import { betterAuthOauthGrants } from "@shivaedev/identity/server/better-auth/adapters/oauthGrants.ts";
|
|
77
|
+
import { trustedOrigins } from "@shivaedev/identity/server/adapters/trustedOrigins.ts";
|
|
77
78
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
78
79
|
import { betterAuthMcp, mcpProvider } from "@shivaedev/mcp/adapters/betterAuth.ts";
|
|
79
80
|
import { mcpRoutes } from "@shivaedev/mcp/routes.ts";
|
|
@@ -99,7 +100,8 @@ const application = Effect.gen(function* () {
|
|
|
99
100
|
{ roles: Roles },
|
|
100
101
|
);
|
|
101
102
|
const origin = trustedOrigins({ allow: ["https://app.example.com"], missing: "allow" });
|
|
102
|
-
const
|
|
103
|
+
const grants = betterAuthOauthGrants({ auth: mounted.auth, admitsUser: mounted.admitsUser });
|
|
104
|
+
const oauth = yield* betterAuthMcp({ auth: mounted.auth, resource, origin, roles: Roles }).pipe(Effect.provide(grants));
|
|
103
105
|
return appHost({
|
|
104
106
|
group: Api,
|
|
105
107
|
handlers: Handlers,
|
|
@@ -121,18 +123,11 @@ const application = Effect.gen(function* () {
|
|
|
121
123
|
|
|
122
124
|
`authPool`, `Api` and `Handlers` are the application's existing auth database, RPC group and handlers. Run the Better Auth migrations with the OAuth and JWT plugins included. For existing role management, keep the application's existing role plugin and `RoleSet` in this configuration.
|
|
123
125
|
|
|
124
|
-
The edge adapter verifies access-token signatures, issuer, endpoint audience and `mcp` scope, then loads the current user and the token
|
|
126
|
+
The edge adapter verifies access-token signatures, issuer, endpoint audience and `mcp` scope, then asks identity's `OauthGrants` service to resolve the subject. The identity Better Auth Layer loads the current user and consent and checks `mounted.admitsUser` afresh on every request. Admission changes apply to the next request with the same token. A failed admission lookup answers `503` without an OAuth challenge. Denied or banned users and clients without consent receive the same unauthorized response as invalid tokens. Identity resolves the stored role on each request. An invalid token receives `401` with a `WWW-Authenticate` protected-resource metadata pointer. The metadata names the authorization server and its discovery endpoint, so a client can start OAuth. MCP bearer credentials are separate from browser session cookies. Provide the OAuth policy Layer to the MCP routes before merging them with a cookie-authenticated host.
|
|
125
127
|
|
|
126
|
-
###
|
|
128
|
+
### Manage client grants
|
|
127
129
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
```ts
|
|
131
|
-
yield* oauth.revokeClient(userId, clientId);
|
|
132
|
-
yield* oauth.revokeAllClients(userId);
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
Deleting consent through Better Auth also refuses MCP access immediately. Use these revocation methods to delete refresh tokens as well.
|
|
130
|
+
Identity owns grant listing and revocation through its [`OauthGrants` service](https://github.com/ShivaeDev/platform/tree/main/packages/identity#oauth-grants). Provide `betterAuthOauthGrants({ auth: mounted.auth, admitsUser: mounted.admitsUser })` to Effects that use that service. The application authorizes grant management operations.
|
|
136
131
|
|
|
137
132
|
### Dynamic origins and local keys
|
|
138
133
|
|
|
@@ -147,7 +142,7 @@ const oauth = yield* betterAuthMcp({
|
|
|
147
142
|
origin,
|
|
148
143
|
roles: Roles,
|
|
149
144
|
jwks: () => mounted.auth.api.getJwks(),
|
|
150
|
-
});
|
|
145
|
+
}).pipe(Effect.provide(grants));
|
|
151
146
|
```
|
|
152
147
|
|
|
153
148
|
The callback returns the public JWK set from the JWT plugin. Signature, issuer, audience and `mcp` scope checks still apply. Signing keys stay with the auth instance.
|
|
@@ -159,6 +154,6 @@ pnpm add @shivaedev/mcp effect
|
|
|
159
154
|
pnpm add better-auth @better-auth/oauth-provider
|
|
160
155
|
```
|
|
161
156
|
|
|
162
|
-
|
|
157
|
+
Better Auth is an optional peer of MCP. Identity owns the optional `@better-auth/oauth-provider` peer and its edge exports; MCP's Better Auth adapter uses those exports for provider configuration and discovery. Core `routes.ts` reads identity's `SessionPolicy` from the Effect environment with the same identity and permission semantics. Provide the adapter's `sessions` Layer once through the host, or supply another `SessionPolicy` Layer.
|
|
163
158
|
|
|
164
159
|
The endpoint uses Effect's request-scoped Streamable HTTP transport and MCP `2026-07-28`. Clients must support that protocol; earlier session-based versions and subscription streams are outside this adapter. Endpoint requests do not share registries, identities or MCP sessions.
|
|
@@ -1,26 +1,33 @@
|
|
|
1
|
-
import { type OAuthOptions, oauthProvider, type Scope } from "@better-auth/oauth-provider";
|
|
2
1
|
import { Effect, Layer } from "effect";
|
|
3
2
|
import { HttpRouter } from "effect/http";
|
|
4
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
5
4
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
5
|
+
import { betterAuthOauthProvider, type OauthResourceOptions } from "@shivaedev/identity/server/better-auth/adapters/oauthProvider.ts";
|
|
6
|
+
import { OauthGrants } from "@shivaedev/identity/server/oauthGrants.ts";
|
|
6
7
|
import type { OriginPolicy } from "@shivaedev/identity/server/origin.ts";
|
|
7
8
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
8
9
|
import { type JwksSource } from "./bearer.ts";
|
|
9
|
-
|
|
10
|
-
export declare function mcpProvider({ resource, scopes, ...options }: Omit<OAuthOptions<Scope[]>, "resources" | "clientRegistrationDefaultResources"> & {
|
|
11
|
-
readonly resource: string;
|
|
12
|
-
}): ReturnType<typeof oauthProvider>;
|
|
10
|
+
export declare function mcpProvider({ scopes, ...options }: OauthResourceOptions): ReturnType<typeof betterAuthOauthProvider>;
|
|
13
11
|
export declare const betterAuthMcp: (options: {
|
|
14
|
-
readonly auth:
|
|
12
|
+
readonly auth: {
|
|
13
|
+
readonly api: {
|
|
14
|
+
readonly "getOAuthServerConfig": () => Promise<{
|
|
15
|
+
readonly issuer: string;
|
|
16
|
+
readonly "jwks_uri"?: string;
|
|
17
|
+
}>;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
15
20
|
readonly resource: string;
|
|
16
21
|
readonly jwks?: JwksSource;
|
|
17
22
|
readonly origin: OriginPolicy;
|
|
18
23
|
readonly roles?: RoleSet;
|
|
19
24
|
}) => Effect.Effect<{
|
|
20
|
-
revokeAllClients: (userId: string) => Effect.Effect<void, AuthUnavailable, never>;
|
|
21
|
-
revokeClient: (userId: string, clientId: string) => Effect.Effect<void, AuthUnavailable, never>;
|
|
22
25
|
resourceMetadataUrl: string;
|
|
23
|
-
routes: Layer.Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Error", import("effect/http/HttpServerError").InternalError> | HttpRouter.Request<"Error", import("effect/http/HttpServerError").RequestParseError> | HttpRouter.Request<"Error", import("effect/http/HttpServerError").RouteNotFound
|
|
26
|
+
routes: Layer.Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Error", import("effect/http/HttpServerError").InternalError> | HttpRouter.Request<"Error", import("effect/http/HttpServerError").RequestParseError> | HttpRouter.Request<"Error", import("effect/http/HttpServerError").RouteNotFound> | HttpRouter.Request<"Error", AuthUnavailable & {
|
|
27
|
+
cause: unknown;
|
|
28
|
+
}>>;
|
|
24
29
|
sessions: Layer.Layer<SessionPolicy, never, never>;
|
|
25
|
-
}, AuthUnavailable
|
|
30
|
+
}, AuthUnavailable & {
|
|
31
|
+
cause: unknown;
|
|
32
|
+
}, OauthGrants>;
|
|
26
33
|
//# sourceMappingURL=betterAuth.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/adapters/betterAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"betterAuth.d.ts","sourceRoot":"","sources":["../../src/adapters/betterAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAU,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAyC,MAAM,aAAa,CAAC;AAChF,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EACN,uBAAuB,EACvB,KAAK,oBAAoB,EAEzB,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAC;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sCAAsC,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;AAC5E,OAAO,EAAU,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAEtD,wBAAgB,WAAW,CAAC,EAAE,MAAgB,EAAE,GAAG,OAAO,EAAE,EAAE,oBAAoB,GAAG,UAAU,CAAC,OAAO,uBAAuB,CAAC,CAE9H;AAED,eAAO,MAAM,aAAa;mBACV;QACd,QAAQ,CAAC,GAAG,EAAE;YAAE,QAAQ,CAAC,sBAAsB,EAAE,MAAM,OAAO,CAAC;gBAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;gBAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;aAAE,CAAC,CAAA;SAAE,CAAC;KAC5H;uBACkB,MAAM;oBACT,UAAU;qBACT,YAAY;qBACZ,OAAO;;;;;;;;;eA6CvB,CAAC"}
|
|
@@ -1,22 +1,24 @@
|
|
|
1
|
-
import { oauthProvider, oauthProviderAuthServerMetadata } from "@better-auth/oauth-provider";
|
|
2
1
|
import { Effect, Layer, Option } from "effect";
|
|
3
2
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
4
3
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
4
|
+
import { betterAuthOauthProvider, oauthAuthorizationMetadata, } from "@shivaedev/identity/server/better-auth/adapters/oauthProvider.ts";
|
|
5
|
+
import { OauthGrants } from "@shivaedev/identity/server/oauthGrants.ts";
|
|
5
6
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
6
7
|
import { bearer } from "./bearer.js";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return oauthProvider({ ...options, clientRegistrationDefaultResources: [resource], resources: [resource], scopes });
|
|
8
|
+
export function mcpProvider({ scopes = ["mcp"], ...options }) {
|
|
9
|
+
return betterAuthOauthProvider({ ...options, scopes });
|
|
10
10
|
}
|
|
11
11
|
export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options) {
|
|
12
12
|
const config = yield* Effect.tryPromise({
|
|
13
|
-
catch: () => new AuthUnavailable({ message: "OAuth provider configuration failed" }),
|
|
13
|
+
catch: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth provider configuration failed" }), { cause }),
|
|
14
14
|
try: () => options.auth.api.getOAuthServerConfig(),
|
|
15
15
|
});
|
|
16
|
+
const grants = yield* OauthGrants;
|
|
16
17
|
const { auth, resource } = options;
|
|
17
18
|
const url = new URL(resource);
|
|
18
19
|
const metadataPath = `/.well-known/oauth-protected-resource${url.pathname}`;
|
|
19
20
|
const resourceMetadataUrl = new URL(metadataPath, url).href;
|
|
21
|
+
const authorizationMetadataPath = `/.well-known/oauth-authorization-server${new URL(config.issuer).pathname.replace(/\/$/u, "")}`;
|
|
20
22
|
const verify = bearer(options.jwks ?? config.jwks_uri ?? new URL("/api/auth/jwks", url).href, resource, config.issuer);
|
|
21
23
|
const sessions = Layer.succeed(SessionPolicy, {
|
|
22
24
|
origin: options.origin,
|
|
@@ -24,29 +26,24 @@ export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options)
|
|
|
24
26
|
provider: {
|
|
25
27
|
get: (headers) => Effect.gen(function* () {
|
|
26
28
|
const authorization = headers.authorization;
|
|
27
|
-
const token = authorization?.
|
|
29
|
+
const token = authorization?.match(/^Bearer (?<token>.+)$/iu)?.groups?.token;
|
|
28
30
|
const claims = yield* verify(token);
|
|
29
31
|
if (Option.isNone(claims) || typeof claims.value.sub !== "string" || typeof claims.value.client_id !== "string") {
|
|
30
32
|
return Option.none();
|
|
31
33
|
}
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
return Option.none();
|
|
35
|
-
}
|
|
36
|
-
const role = Reflect.get(user, "role");
|
|
37
|
-
return Option.some({ user: { email: user.email, id: user.id, name: user.name, ...(typeof role === "string" ? { role } : {}) } });
|
|
34
|
+
const subject = yield* grants.resolveSubject(claims.value.sub, claims.value.client_id);
|
|
35
|
+
return Option.map(subject, (user) => ({ user }));
|
|
38
36
|
}),
|
|
39
37
|
},
|
|
40
38
|
});
|
|
41
|
-
const metadata = oauthProviderAuthServerMetadata(auth);
|
|
42
39
|
const authorizationMetadata = Effect.fn("Mcp.authorizationMetadata")(function* (request) {
|
|
43
40
|
const web = yield* HttpServerRequest.toWeb(request);
|
|
44
|
-
return HttpServerResponse.fromWeb(yield*
|
|
41
|
+
return HttpServerResponse.fromWeb(yield* oauthAuthorizationMetadata(auth, web));
|
|
45
42
|
});
|
|
46
43
|
const routes = HttpRouter.use((router) => Effect.gen(function* () {
|
|
47
44
|
yield* router.add("GET", metadataPath, HttpServerResponse.jsonUnsafe({ "authorization_servers": [config.issuer], resource, "scopes_supported": ["mcp"] }));
|
|
48
|
-
yield* router.add("GET",
|
|
45
|
+
yield* router.add("GET", authorizationMetadataPath, authorizationMetadata);
|
|
49
46
|
}));
|
|
50
|
-
return {
|
|
47
|
+
return { resourceMetadataUrl, routes, sessions };
|
|
51
48
|
});
|
|
52
49
|
//# sourceMappingURL=betterAuth.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"betterAuth.js","sourceRoot":"","sources":["../../src/adapters/betterAuth.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"betterAuth.js","sourceRoot":"","sources":["../../src/adapters/betterAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEhF,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EACN,uBAAuB,EAEvB,0BAA0B,GAC1B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,2CAA2C,CAAC;AAExE,OAAO,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;AAC5E,OAAO,EAAE,MAAM,EAAmB,MAAM,aAAa,CAAC;AAEtD,MAAM,UAAU,WAAW,CAAC,EAAE,MAAM,GAAG,CAAC,KAAK,CAAC,EAAE,GAAG,OAAO,EAAwB;IACjF,OAAO,uBAAuB,CAAC,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,EAAE,CAAC,mBAAmB,CAAC,CAAC,QAAQ,CAAC,EAAE,OAQtE;IACA,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;QACvC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,eAAe,CAAC,EAAE,OAAO,EA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,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,kBAAkB,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAClH,CAAC;QACF,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,yBAAyB,EAAE,qBAAqB,CAAC,CAAC;IAC5E,CAAC,CAAC,CACF,CAAC;IACF,OAAO,EAAE,mBAAmB,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AAClD,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shivaedev/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Identity-aware Effect MCP tools mounted on the application host",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"effect"
|
|
@@ -43,18 +43,18 @@
|
|
|
43
43
|
"README.md"
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@shivaedev/access": "0.3.
|
|
47
|
-
"@shivaedev/errors": "0.
|
|
48
|
-
"@shivaedev/identity": "0.
|
|
46
|
+
"@shivaedev/access": "0.3.6",
|
|
47
|
+
"@shivaedev/errors": "0.5.0",
|
|
48
|
+
"@shivaedev/identity": "0.19.0"
|
|
49
49
|
},
|
|
50
50
|
"devDependencies": {
|
|
51
|
-
"@better-auth/oauth-provider": "1.7.12",
|
|
52
51
|
"@effect/platform-node": "4.0.6",
|
|
53
52
|
"@effect/sql-pg": "4.0.6",
|
|
54
|
-
"@shivaedev/quality": "0.
|
|
55
|
-
"@shivaedev/
|
|
56
|
-
"@shivaedev/
|
|
57
|
-
"@shivaedev/test-
|
|
53
|
+
"@shivaedev/quality": "0.56.0",
|
|
54
|
+
"@shivaedev/rate-limit": "0.2.1",
|
|
55
|
+
"@shivaedev/server": "0.19.0",
|
|
56
|
+
"@shivaedev/test-sql": "0.16.2",
|
|
57
|
+
"@shivaedev/test-story": "0.34.0",
|
|
58
58
|
"@types/node": "24.19.2",
|
|
59
59
|
"better-auth": "1.7.12",
|
|
60
60
|
"effect": "4.0.6",
|
|
@@ -62,14 +62,10 @@
|
|
|
62
62
|
"vitest": "5.0.5"
|
|
63
63
|
},
|
|
64
64
|
"peerDependencies": {
|
|
65
|
-
"@better-auth/oauth-provider": "1.7.12",
|
|
66
65
|
"better-auth": "1.7.12",
|
|
67
66
|
"effect": "4.0.6"
|
|
68
67
|
},
|
|
69
68
|
"peerDependenciesMeta": {
|
|
70
|
-
"@better-auth/oauth-provider": {
|
|
71
|
-
"optional": true
|
|
72
|
-
},
|
|
73
69
|
"better-auth": {
|
|
74
70
|
"optional": true
|
|
75
71
|
}
|
|
@@ -1,38 +1,40 @@
|
|
|
1
|
-
import { type OAuthOptions, oauthProvider, oauthProviderAuthServerMetadata, type Scope } from "@better-auth/oauth-provider";
|
|
2
1
|
import { Effect, Layer, Option } from "effect";
|
|
3
2
|
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
|
|
4
3
|
import type { RoleSet } from "@shivaedev/access/roleSet.ts";
|
|
5
4
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
5
|
+
import {
|
|
6
|
+
betterAuthOauthProvider,
|
|
7
|
+
type OauthResourceOptions,
|
|
8
|
+
oauthAuthorizationMetadata,
|
|
9
|
+
} from "@shivaedev/identity/server/better-auth/adapters/oauthProvider.ts";
|
|
10
|
+
import { OauthGrants } from "@shivaedev/identity/server/oauthGrants.ts";
|
|
6
11
|
import type { OriginPolicy } from "@shivaedev/identity/server/origin.ts";
|
|
7
12
|
import { SessionPolicy } from "@shivaedev/identity/server/SessionPolicy.ts";
|
|
8
13
|
import { bearer, type JwksSource } from "./bearer.ts";
|
|
9
|
-
import { grantedUser, type OauthAuth, oauthGrants } from "./oauthGrants.ts";
|
|
10
14
|
|
|
11
|
-
export function mcpProvider({
|
|
12
|
-
|
|
13
|
-
scopes = ["mcp"],
|
|
14
|
-
...options
|
|
15
|
-
}: Omit<OAuthOptions<Scope[]>, "resources" | "clientRegistrationDefaultResources"> & { readonly resource: string }): ReturnType<
|
|
16
|
-
typeof oauthProvider
|
|
17
|
-
> {
|
|
18
|
-
return oauthProvider({ ...options, clientRegistrationDefaultResources: [resource], resources: [resource], scopes });
|
|
15
|
+
export function mcpProvider({ scopes = ["mcp"], ...options }: OauthResourceOptions): ReturnType<typeof betterAuthOauthProvider> {
|
|
16
|
+
return betterAuthOauthProvider({ ...options, scopes });
|
|
19
17
|
}
|
|
20
18
|
|
|
21
19
|
export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options: {
|
|
22
|
-
readonly auth:
|
|
20
|
+
readonly auth: {
|
|
21
|
+
readonly api: { readonly "getOAuthServerConfig": () => Promise<{ readonly issuer: string; readonly "jwks_uri"?: string }> };
|
|
22
|
+
};
|
|
23
23
|
readonly resource: string;
|
|
24
24
|
readonly jwks?: JwksSource;
|
|
25
25
|
readonly origin: OriginPolicy;
|
|
26
26
|
readonly roles?: RoleSet;
|
|
27
27
|
}) {
|
|
28
28
|
const config = yield* Effect.tryPromise({
|
|
29
|
-
catch: () => new AuthUnavailable({ message: "OAuth provider configuration failed" }),
|
|
29
|
+
catch: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth provider configuration failed" }), { cause }),
|
|
30
30
|
try: () => options.auth.api.getOAuthServerConfig(),
|
|
31
31
|
});
|
|
32
|
+
const grants = yield* OauthGrants;
|
|
32
33
|
const { auth, resource } = options;
|
|
33
34
|
const url = new URL(resource);
|
|
34
35
|
const metadataPath = `/.well-known/oauth-protected-resource${url.pathname}` as const;
|
|
35
36
|
const resourceMetadataUrl = new URL(metadataPath, url).href;
|
|
37
|
+
const authorizationMetadataPath = `/.well-known/oauth-authorization-server${new URL(config.issuer).pathname.replace(/\/$/u, "")}` as const;
|
|
36
38
|
const verify = bearer(options.jwks ?? config.jwks_uri ?? new URL("/api/auth/jwks", url).href, resource, config.issuer);
|
|
37
39
|
const sessions = Layer.succeed(SessionPolicy, {
|
|
38
40
|
origin: options.origin,
|
|
@@ -41,24 +43,19 @@ export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options:
|
|
|
41
43
|
get: (headers) =>
|
|
42
44
|
Effect.gen(function* () {
|
|
43
45
|
const authorization = headers.authorization;
|
|
44
|
-
const token = authorization?.
|
|
46
|
+
const token = authorization?.match(/^Bearer (?<token>.+)$/iu)?.groups?.token;
|
|
45
47
|
const claims = yield* verify(token);
|
|
46
48
|
if (Option.isNone(claims) || typeof claims.value.sub !== "string" || typeof claims.value.client_id !== "string") {
|
|
47
49
|
return Option.none();
|
|
48
50
|
}
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
return Option.none();
|
|
52
|
-
}
|
|
53
|
-
const role: unknown = Reflect.get(user, "role");
|
|
54
|
-
return Option.some({ user: { email: user.email, id: user.id, name: user.name, ...(typeof role === "string" ? { role } : {}) } });
|
|
51
|
+
const subject = yield* grants.resolveSubject(claims.value.sub, claims.value.client_id);
|
|
52
|
+
return Option.map(subject, (user) => ({ user }));
|
|
55
53
|
}),
|
|
56
54
|
},
|
|
57
55
|
});
|
|
58
|
-
const metadata = oauthProviderAuthServerMetadata(auth);
|
|
59
56
|
const authorizationMetadata = Effect.fn("Mcp.authorizationMetadata")(function* (request: HttpServerRequest.HttpServerRequest) {
|
|
60
57
|
const web = yield* HttpServerRequest.toWeb(request);
|
|
61
|
-
return HttpServerResponse.fromWeb(yield*
|
|
58
|
+
return HttpServerResponse.fromWeb(yield* oauthAuthorizationMetadata(auth, web));
|
|
62
59
|
});
|
|
63
60
|
const routes = HttpRouter.use((router) =>
|
|
64
61
|
Effect.gen(function* () {
|
|
@@ -67,8 +64,8 @@ export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options:
|
|
|
67
64
|
metadataPath,
|
|
68
65
|
HttpServerResponse.jsonUnsafe({ "authorization_servers": [config.issuer], resource, "scopes_supported": ["mcp"] }),
|
|
69
66
|
);
|
|
70
|
-
yield* router.add("GET",
|
|
67
|
+
yield* router.add("GET", authorizationMetadataPath, authorizationMetadata);
|
|
71
68
|
}),
|
|
72
69
|
);
|
|
73
|
-
return {
|
|
70
|
+
return { resourceMetadataUrl, routes, sessions };
|
|
74
71
|
});
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
import type { AuthContext, BetterAuthOptions } from "better-auth";
|
|
2
|
-
import { Effect } from "effect";
|
|
3
|
-
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
4
|
-
export interface OauthAuth {
|
|
5
|
-
readonly $context: Promise<{
|
|
6
|
-
readonly adapter: Pick<AuthContext["adapter"], "findOne"> & {
|
|
7
|
-
readonly transaction: <A>(run: (adapter: Pick<AuthContext["adapter"], "deleteMany">) => Promise<A>) => Promise<A>;
|
|
8
|
-
};
|
|
9
|
-
readonly internalAdapter: Pick<AuthContext["internalAdapter"], "findUserById">;
|
|
10
|
-
}>;
|
|
11
|
-
readonly api: {
|
|
12
|
-
readonly "getOAuthServerConfig": () => Promise<{
|
|
13
|
-
readonly issuer: string;
|
|
14
|
-
readonly "jwks_uri"?: string;
|
|
15
|
-
}>;
|
|
16
|
-
};
|
|
17
|
-
readonly options: BetterAuthOptions;
|
|
18
|
-
}
|
|
19
|
-
export declare function oauthGrants(auth: OauthAuth): {
|
|
20
|
-
revokeAllClients: (userId: string) => Effect.Effect<void, AuthUnavailable, never>;
|
|
21
|
-
revokeClient: (userId: string, clientId: string) => Effect.Effect<void, AuthUnavailable, never>;
|
|
22
|
-
};
|
|
23
|
-
export declare const grantedUser: (auth: OauthAuth, userId: string, clientId: string) => Effect.Effect<{
|
|
24
|
-
id: string;
|
|
25
|
-
createdAt: Date;
|
|
26
|
-
updatedAt: Date;
|
|
27
|
-
email: string;
|
|
28
|
-
emailVerified: boolean;
|
|
29
|
-
name: string;
|
|
30
|
-
image?: string | null | undefined;
|
|
31
|
-
} | null, AuthUnavailable, never>;
|
|
32
|
-
//# sourceMappingUR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@@
|
|
|
1
|
-
import { Effect } from "effect";
|
|
2
|
-
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
3
|
-
export function oauthGrants(auth) {
|
|
4
|
-
const revoke = Effect.fn("Mcp.revoke")(function* (userId, clientId) {
|
|
5
|
-
yield* Effect.tryPromise({
|
|
6
|
-
catch: () => new AuthUnavailable({ message: "OAuth grant revocation failed" }),
|
|
7
|
-
try: async () => {
|
|
8
|
-
const { adapter } = await auth.$context;
|
|
9
|
-
const where = [{ field: "userId", value: userId }, ...(clientId === undefined ? [] : [{ field: "clientId", value: clientId }])];
|
|
10
|
-
await adapter.transaction(async (transaction) => {
|
|
11
|
-
for (const model of ["oauthConsent", "oauthAccessToken", "oauthRefreshToken"]) {
|
|
12
|
-
await transaction.deleteMany({ model, where });
|
|
13
|
-
}
|
|
14
|
-
});
|
|
15
|
-
},
|
|
16
|
-
});
|
|
17
|
-
});
|
|
18
|
-
return {
|
|
19
|
-
revokeAllClients: (userId) => revoke(userId),
|
|
20
|
-
revokeClient: (userId, clientId) => revoke(userId, clientId),
|
|
21
|
-
};
|
|
22
|
-
}
|
|
23
|
-
export const grantedUser = Effect.fn("Mcp.grantedUser")(function* (auth, userId, clientId) {
|
|
24
|
-
return yield* Effect.tryPromise({
|
|
25
|
-
catch: () => new AuthUnavailable({ message: "OAuth grant lookup failed" }),
|
|
26
|
-
try: async () => {
|
|
27
|
-
const { adapter, internalAdapter } = await auth.$context;
|
|
28
|
-
const user = await internalAdapter.findUserById(userId);
|
|
29
|
-
if (user === null || Reflect.get(user, "banned") === true) {
|
|
30
|
-
return null;
|
|
31
|
-
}
|
|
32
|
-
const consent = await adapter.findOne({
|
|
33
|
-
model: "oauthConsent",
|
|
34
|
-
where: [
|
|
35
|
-
{ field: "userId", value: userId },
|
|
36
|
-
{ field: "clientId", value: clientId },
|
|
37
|
-
],
|
|
38
|
-
});
|
|
39
|
-
return consent === null ? null : user;
|
|
40
|
-
},
|
|
41
|
-
});
|
|
42
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
import type { AuthContext, BetterAuthOptions } from "better-auth";
|
|
2
|
-
import { Effect } from "effect";
|
|
3
|
-
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
4
|
-
|
|
5
|
-
export interface OauthAuth {
|
|
6
|
-
readonly $context: Promise<{
|
|
7
|
-
readonly adapter: Pick<AuthContext["adapter"], "findOne"> & {
|
|
8
|
-
readonly transaction: <A>(run: (adapter: Pick<AuthContext["adapter"], "deleteMany">) => Promise<A>) => Promise<A>;
|
|
9
|
-
};
|
|
10
|
-
readonly internalAdapter: Pick<AuthContext["internalAdapter"], "findUserById">;
|
|
11
|
-
}>;
|
|
12
|
-
readonly api: { readonly "getOAuthServerConfig": () => Promise<{ readonly issuer: string; readonly "jwks_uri"?: string }> };
|
|
13
|
-
readonly options: BetterAuthOptions;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export function oauthGrants(auth: OauthAuth) {
|
|
17
|
-
const revoke = Effect.fn("Mcp.revoke")(function* (userId: string, clientId?: string) {
|
|
18
|
-
yield* Effect.tryPromise({
|
|
19
|
-
catch: () => new AuthUnavailable({ message: "OAuth grant revocation failed" }),
|
|
20
|
-
try: async () => {
|
|
21
|
-
const { adapter } = await auth.$context;
|
|
22
|
-
const where = [{ field: "userId", value: userId }, ...(clientId === undefined ? [] : [{ field: "clientId", value: clientId }])];
|
|
23
|
-
await adapter.transaction(async (transaction) => {
|
|
24
|
-
for (const model of ["oauthConsent", "oauthAccessToken", "oauthRefreshToken"]) {
|
|
25
|
-
await transaction.deleteMany({ model, where });
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
},
|
|
29
|
-
});
|
|
30
|
-
});
|
|
31
|
-
return {
|
|
32
|
-
revokeAllClients: (userId: string) => revoke(userId),
|
|
33
|
-
revokeClient: (userId: string, clientId: string) => revoke(userId, clientId),
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export const grantedUser = Effect.fn("Mcp.grantedUser")(function* (auth: OauthAuth, userId: string, clientId: string) {
|
|
38
|
-
return yield* Effect.tryPromise({
|
|
39
|
-
catch: () => new AuthUnavailable({ message: "OAuth grant lookup failed" }),
|
|
40
|
-
try: async () => {
|
|
41
|
-
const { adapter, internalAdapter } = await auth.$context;
|
|
42
|
-
const user = await internalAdapter.findUserById(userId);
|
|
43
|
-
if (user === null || Reflect.get(user, "banned") === true) {
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
const consent = await adapter.findOne({
|
|
47
|
-
model: "oauthConsent",
|
|
48
|
-
where: [
|
|
49
|
-
{ field: "userId", value: userId },
|
|
50
|
-
{ field: "clientId", value: clientId },
|
|
51
|
-
],
|
|
52
|
-
});
|
|
53
|
-
return consent === null ? null : user;
|
|
54
|
-
},
|
|
55
|
-
});
|
|
56
|
-
});
|