@shivaedev/mcp 0.4.0 → 0.6.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 +15 -15
- package/dist/adapters/InvalidTokenClaim.d.ts +10 -0
- package/dist/adapters/InvalidTokenClaim.d.ts.map +1 -0
- package/dist/adapters/InvalidTokenClaim.js +7 -0
- package/dist/adapters/InvalidTokenClaim.js.map +1 -0
- package/dist/adapters/bearer.d.ts +12 -1
- package/dist/adapters/bearer.d.ts.map +1 -1
- package/dist/adapters/bearer.js +25 -4
- package/dist/adapters/bearer.js.map +1 -1
- package/dist/adapters/betterAuth.d.ts +36 -15
- package/dist/adapters/betterAuth.d.ts.map +1 -1
- package/dist/adapters/betterAuth.js +18 -24
- package/dist/adapters/betterAuth.js.map +1 -1
- package/package.json +11 -15
- package/src/adapters/InvalidTokenClaim.ts +9 -0
- package/src/adapters/bearer.ts +29 -5
- package/src/adapters/betterAuth.ts +27 -34
- package/dist/adapters/oauthGrants.d.ts +0 -38
- 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.6.0 - 2026-11-03
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Expose `authenticate` from `betterAuthMcp` so applications can distinguish an `InvalidTokenClaim` failure, with its claim name, from a refused OAuth grant. Missing or malformed required claims produce a claim diagnostic; MCP HTTP requests keep their unauthorized resource challenge.
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- Admit a member's MCP client once their temporary ban expires, including before they sign in on the web again.
|
|
12
|
+
- Revoked MCP tokens stay refused after new consent. Removing `mcp` from a live grant’s scopes refuses its tokens on the next request.
|
|
13
|
+
|
|
14
|
+
### Breaking
|
|
15
|
+
|
|
16
|
+
- The MCP OAuth session policy refuses requests carrying a Cookie header, including those with a valid bearer token. Send MCP bearer credentials without cookies; keep browser cookies on cookie-authenticated RPC routes.
|
|
17
|
+
- The exported `bearer` verifier now fails with `InvalidTokenClaim` for missing or invalid claims instead of returning `Option.none()`. Consumers of this verifier must handle the typed failure and can read its `claim` field. The session Layer continues to answer these tokens with the unauthorized resource challenge.
|
|
18
|
+
- MCP tokens now carry a `grant_id` that references the exact Better Auth `oauthConsent` row. Tokens issued before this change lack that reference and are refused; clients must authorize again to obtain new access tokens. Existing refresh tokens can obtain grant-bound access tokens while their consent remains live.
|
|
19
|
+
|
|
20
|
+
## 0.5.0 - 2026-11-02
|
|
21
|
+
|
|
22
|
+
### Breaking
|
|
23
|
+
|
|
24
|
+
- 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.
|
|
25
|
+
|
|
3
26
|
## 0.4.0 - 2026-11-02
|
|
4
27
|
|
|
5
28
|
### Added
|
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,17 @@ 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 `
|
|
126
|
+
The edge adapter verifies access-token signatures, issuer, endpoint audience, `mcp` scope and the `grant_id` reference, then asks identity’s `OauthGrants` service to resolve that exact grant. The identity Better Auth Layer loads the current user and referenced consent, requires `mcp` in the consent’s current scopes 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 the referenced 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. The OAuth session policy refuses requests carrying a Cookie header, including requests that also carry a valid bearer token. Provide the OAuth policy Layer to the MCP routes before merging them with a cookie-authenticated host.
|
|
125
127
|
|
|
126
|
-
###
|
|
128
|
+
### Diagnose token refusals
|
|
127
129
|
|
|
128
|
-
|
|
130
|
+
`betterAuthMcp` returns `authenticate(token)` alongside its route and session Layers. It verifies the token and resolves its current OAuth grant. A successful authentication returns `Option.some({ user })`; a refused grant returns `Option.none()`. Missing or malformed `iss`, `aud`, `sub`, `client_id` or `scope` claims fail with `InvalidTokenClaim` from `@shivaedev/mcp/adapters/InvalidTokenClaim.ts`. The failure names `claim`, and the adapter logs a warning with that name. Claims and token values stay out of this diagnostic. Blank subjects and client identifiers are invalid too.
|
|
129
131
|
|
|
130
|
-
|
|
131
|
-
yield* oauth.revokeClient(userId, clientId);
|
|
132
|
-
yield* oauth.revokeAllClients(userId);
|
|
133
|
-
```
|
|
132
|
+
Use `authenticate` in application stories to distinguish invalid claims from refused grants. HTTP sessions translate `InvalidTokenClaim` into the ordinary `401` resource challenge. A token with an invalid signature still receives that challenge; verification infrastructure failures remain `AuthUnavailable` and answer `503`.
|
|
134
133
|
|
|
135
|
-
|
|
134
|
+
### Manage client grants
|
|
135
|
+
|
|
136
|
+
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
137
|
|
|
137
138
|
### Dynamic origins and local keys
|
|
138
139
|
|
|
@@ -142,13 +143,12 @@ By default verification fetches the authorization server's JWKS URL. Pass `jwks`
|
|
|
142
143
|
|
|
143
144
|
```ts
|
|
144
145
|
const oauth = yield* betterAuthMcp({
|
|
145
|
-
admitsUser: mounted.admitsUser,
|
|
146
146
|
auth: mounted.auth,
|
|
147
147
|
resource,
|
|
148
148
|
origin,
|
|
149
149
|
roles: Roles,
|
|
150
150
|
jwks: () => mounted.auth.api.getJwks(),
|
|
151
|
-
});
|
|
151
|
+
}).pipe(Effect.provide(grants));
|
|
152
152
|
```
|
|
153
153
|
|
|
154
154
|
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.
|
|
@@ -160,6 +160,6 @@ pnpm add @shivaedev/mcp effect
|
|
|
160
160
|
pnpm add better-auth @better-auth/oauth-provider
|
|
161
161
|
```
|
|
162
162
|
|
|
163
|
-
|
|
163
|
+
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; it runs without either OAuth peer installed. Provide the adapter's `sessions` Layer once through the host, or supply another `SessionPolicy` Layer.
|
|
164
164
|
|
|
165
|
-
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.
|
|
165
|
+
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. For browser clients, both the session policy's `origin` and the route's `allowedOrigins` must accept the Origin; non-browser clients can omit Origin when the session policy allows it.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
declare const InvalidTokenClaim_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
2
|
+
readonly _tag: "InvalidTokenClaim";
|
|
3
|
+
} & Readonly<A>;
|
|
4
|
+
export declare class InvalidTokenClaim extends InvalidTokenClaim_base<{
|
|
5
|
+
readonly claim: string;
|
|
6
|
+
}> {
|
|
7
|
+
get message(): string;
|
|
8
|
+
}
|
|
9
|
+
export {};
|
|
10
|
+
//# sourceMappingURL=InvalidTokenClaim.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InvalidTokenClaim.d.ts","sourceRoot":"","sources":["../../src/adapters/InvalidTokenClaim.ts"],"names":[],"mappings":";;;AAEA,qBAAa,iBAAkB,SAAQ,uBAAsC;IAC5E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB,CAAC;IACD,IAAa,OAAO,WAEnB;CACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InvalidTokenClaim.js","sourceRoot":"","sources":["../../src/adapters/InvalidTokenClaim.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAE9B,MAAM,OAAO,iBAAkB,SAAQ,IAAI,CAAC,WAAW,CAAC,mBAAmB,CAEzE;IACD,IAAa,OAAO;QACnB,OAAO,6CAA6C,IAAI,CAAC,KAAK,QAAQ,CAAC;IACxE,CAAC;CACD"}
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
2
2
|
import { Effect, Option } from "effect";
|
|
3
3
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
4
|
+
import { InvalidTokenClaim } from "./InvalidTokenClaim.ts";
|
|
4
5
|
export type JwksSource = Parameters<typeof verifyJwsAccessToken>[1]["jwksFetch"];
|
|
5
|
-
export declare function bearer(jwks: JwksSource, audience: string, issuer: string): (token: string | undefined) => Effect.Effect<Option.Option<never> | Option.Option<
|
|
6
|
+
export declare function bearer(jwks: JwksSource, audience: string, issuer: string): (token: string | undefined) => Effect.Effect<Option.Option<never> | Option.Option<{
|
|
7
|
+
iss?: string;
|
|
8
|
+
aud?: string | string[];
|
|
9
|
+
jti?: string;
|
|
10
|
+
nbf?: number;
|
|
11
|
+
exp?: number;
|
|
12
|
+
iat?: number;
|
|
13
|
+
client_id: string;
|
|
14
|
+
grant_id: string;
|
|
15
|
+
sub: string;
|
|
16
|
+
}>, AuthUnavailable | InvalidTokenClaim, never>;
|
|
6
17
|
//# sourceMappingURL=bearer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bearer.d.ts","sourceRoot":"","sources":["../../src/adapters/bearer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"bearer.d.ts","sourceRoot":"","sources":["../../src/adapters/bearer.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE3D,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC;AA0CjF,wBAAgB,MAAM,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,WACzD,MAAM,GAAG,SAAS;;;;;;;;;;gDAqBjC"}
|
package/dist/adapters/bearer.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isAPIError } from "better-auth/api";
|
|
2
2
|
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
3
3
|
import { Effect, Option } from "effect";
|
|
4
4
|
import { redact } from "@shivaedev/errors/redact.ts";
|
|
5
5
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
6
|
+
import { InvalidTokenClaim } from "./InvalidTokenClaim.js";
|
|
6
7
|
const INVALID_TOKEN_ERRORS = new Set([
|
|
7
8
|
"ERR_JWT_EXPIRED",
|
|
8
9
|
"ERR_JWT_CLAIM_VALIDATION_FAILED",
|
|
@@ -14,12 +15,26 @@ const INVALID_TOKEN_ERRORS = new Set([
|
|
|
14
15
|
"ERR_JOSE_NOT_SUPPORTED",
|
|
15
16
|
]);
|
|
16
17
|
function bearerFailure(cause) {
|
|
18
|
+
const claim = cause instanceof Error ? Reflect.get(cause, "claim") : undefined;
|
|
19
|
+
if (cause instanceof InvalidTokenClaim
|
|
20
|
+
|| (cause instanceof Error
|
|
21
|
+
&& ["ERR_JWT_CLAIM_VALIDATION_FAILED", "ERR_JWT_EXPIRED"].includes(String(Reflect.get(cause, "code")))
|
|
22
|
+
&& typeof claim === "string")) {
|
|
23
|
+
const failure = cause instanceof InvalidTokenClaim ? cause : new InvalidTokenClaim({ claim });
|
|
24
|
+
return Effect.logWarning(failure.message).pipe(Effect.andThen(Effect.fail(failure)));
|
|
25
|
+
}
|
|
17
26
|
if ((isAPIError(cause) && (cause.status === "UNAUTHORIZED" || cause.status === "FORBIDDEN"))
|
|
18
27
|
|| (cause instanceof Error && INVALID_TOKEN_ERRORS.has(String(Reflect.get(cause, "code"))))) {
|
|
19
28
|
return Effect.succeed(Option.none());
|
|
20
29
|
}
|
|
21
30
|
return Effect.logError("MCP authentication verification failed", redact(cause)).pipe(Effect.andThen(Effect.fail(new AuthUnavailable({ message: "Authentication is temporarily unavailable" }))));
|
|
22
31
|
}
|
|
32
|
+
function requiredClaim(value, claim) {
|
|
33
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
34
|
+
throw new InvalidTokenClaim({ claim });
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
23
38
|
export function bearer(jwks, audience, issuer) {
|
|
24
39
|
return (token) => {
|
|
25
40
|
if (!token) {
|
|
@@ -27,10 +42,16 @@ export function bearer(jwks, audience, issuer) {
|
|
|
27
42
|
}
|
|
28
43
|
return Effect.tryPromise(async () => {
|
|
29
44
|
const claims = await verifyJwsAccessToken(token, { jwksFetch: jwks, verifyOptions: { audience, issuer } });
|
|
30
|
-
|
|
31
|
-
|
|
45
|
+
const sub = requiredClaim(claims.sub, "sub");
|
|
46
|
+
const clientId = requiredClaim(claims.client_id, "client_id");
|
|
47
|
+
const grantId = requiredClaim(claims.grant_id, "grant_id");
|
|
48
|
+
if (typeof claims.scope !== "string" || !claims.scope.split(" ").includes("mcp")) {
|
|
49
|
+
throw new InvalidTokenClaim({ claim: "scope" });
|
|
50
|
+
}
|
|
51
|
+
if (claims.cnf !== undefined) {
|
|
52
|
+
throw new InvalidTokenClaim({ claim: "cnf" });
|
|
32
53
|
}
|
|
33
|
-
return claims;
|
|
54
|
+
return { ...claims, "client_id": clientId, "grant_id": grantId, sub };
|
|
34
55
|
}).pipe(Effect.map(Option.some), Effect.catch(({ cause }) => bearerFailure(cause)));
|
|
35
56
|
};
|
|
36
57
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bearer.js","sourceRoot":"","sources":["../../src/adapters/bearer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"bearer.js","sourceRoot":"","sources":["../../src/adapters/bearer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,6BAA6B,CAAC;AACrD,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAI3D,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACpC,iBAAiB;IACjB,iCAAiC;IACjC,iBAAiB;IACjB,iBAAiB;IACjB,uCAAuC;IACvC,0BAA0B;IAC1B,0BAA0B;IAC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OAAO,EAAE,CAAC,CAAC;YACjD,CAAC;YACD,IAAI,MAAM,CAAC,GAAG,KAAK,SAAS,EAAE,CAAC;gBAC9B,MAAM,IAAI,iBAAiB,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;YAC/C,CAAC;YACD,OAAO,EAAE,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC;QACvE,CAAC,CAAC,CAAC,IAAI,CACN,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EACvB,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CACjD,CAAC;IACH,CAAC,CAAC;AACH,CAAC"}
|
|
@@ -1,29 +1,50 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { Effect, Layer } from "effect";
|
|
1
|
+
import { Effect, Layer, Option } 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
|
|
15
|
-
|
|
12
|
+
readonly auth: {
|
|
13
|
+
readonly api: {
|
|
14
|
+
readonly "getOAuthServerConfig": () => Promise<{
|
|
15
|
+
readonly issuer: string;
|
|
16
|
+
readonly "jwks_uri"?: string;
|
|
17
|
+
}>;
|
|
18
|
+
};
|
|
19
|
+
};
|
|
16
20
|
readonly resource: string;
|
|
17
21
|
readonly jwks?: JwksSource;
|
|
18
22
|
readonly origin: OriginPolicy;
|
|
19
23
|
readonly roles?: RoleSet;
|
|
20
24
|
}) => Effect.Effect<{
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
authenticate: (token: string | undefined) => Effect.Effect<Option.None<{
|
|
26
|
+
user: {
|
|
27
|
+
readonly email: string;
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly name: string;
|
|
30
|
+
readonly permissions?: readonly {
|
|
31
|
+
readonly name: string;
|
|
32
|
+
readonly strength: "any" | "own";
|
|
33
|
+
}[];
|
|
34
|
+
readonly role?: string | null | undefined;
|
|
35
|
+
};
|
|
36
|
+
}> | Option.Some<{
|
|
37
|
+
user: {
|
|
38
|
+
readonly email: string;
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly name: string;
|
|
41
|
+
readonly permissions?: readonly {
|
|
42
|
+
readonly name: string;
|
|
43
|
+
readonly strength: "any" | "own";
|
|
44
|
+
}[];
|
|
45
|
+
readonly role?: string | null | undefined;
|
|
46
|
+
};
|
|
47
|
+
}>, AuthUnavailable | import("./InvalidTokenClaim.ts").InvalidTokenClaim, never>;
|
|
27
48
|
resourceMetadataUrl: string;
|
|
28
49
|
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 & {
|
|
29
50
|
cause: unknown;
|
|
@@ -31,5 +52,5 @@ export declare const betterAuthMcp: (options: {
|
|
|
31
52
|
sessions: Layer.Layer<SessionPolicy, never, never>;
|
|
32
53
|
}, AuthUnavailable & {
|
|
33
54
|
cause: unknown;
|
|
34
|
-
},
|
|
55
|
+
}, OauthGrants>;
|
|
35
56
|
//# 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,EAAE,MAAM,EAAE,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;eAgDvB,CAAC"}
|
|
@@ -1,56 +1,50 @@
|
|
|
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
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;
|
|
20
21
|
const authorizationMetadataPath = `/.well-known/oauth-authorization-server${new URL(config.issuer).pathname.replace(/\/$/u, "")}`;
|
|
21
22
|
const verify = bearer(options.jwks ?? config.jwks_uri ?? new URL("/api/auth/jwks", url).href, resource, config.issuer);
|
|
23
|
+
const authenticate = Effect.fn("Mcp.authenticate")(function* (token) {
|
|
24
|
+
const claims = yield* verify(token);
|
|
25
|
+
if (Option.isNone(claims)) {
|
|
26
|
+
return Option.none();
|
|
27
|
+
}
|
|
28
|
+
const grant = yield* grants.resolveGrant(claims.value.grant_id, claims.value.sub, claims.value.client_id);
|
|
29
|
+
return Option.filter(grant, (live) => live.scopes.includes("mcp")).pipe(Option.map(({ user }) => ({ user })));
|
|
30
|
+
});
|
|
22
31
|
const sessions = Layer.succeed(SessionPolicy, {
|
|
23
32
|
origin: options.origin,
|
|
24
33
|
...(options.roles === undefined ? {} : { roles: options.roles }),
|
|
25
34
|
provider: {
|
|
26
|
-
get: (headers) =>
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
const claims = yield* verify(token);
|
|
30
|
-
if (Option.isNone(claims) || typeof claims.value.sub !== "string" || typeof claims.value.client_id !== "string") {
|
|
31
|
-
return Option.none();
|
|
32
|
-
}
|
|
33
|
-
const user = yield* grantedUser(auth, claims.value.sub, claims.value.client_id);
|
|
34
|
-
if (user === null || !(yield* options.admitsUser(user.id))) {
|
|
35
|
-
return Option.none();
|
|
36
|
-
}
|
|
37
|
-
const role = Reflect.get(user, "role");
|
|
38
|
-
return Option.some({ user: { email: user.email, id: user.id, name: user.name, ...(typeof role === "string" ? { role } : {}) } });
|
|
39
|
-
}),
|
|
35
|
+
get: (headers) => headers.cookie === undefined
|
|
36
|
+
? authenticate(headers.authorization?.match(/^Bearer (?<token>.+)$/iu)?.groups?.token).pipe(Effect.catchTag("InvalidTokenClaim", () => Effect.succeed(Option.none())))
|
|
37
|
+
: Effect.succeed(Option.none()),
|
|
40
38
|
},
|
|
41
39
|
});
|
|
42
|
-
const metadata = oauthProviderAuthServerMetadata(auth);
|
|
43
40
|
const authorizationMetadata = Effect.fn("Mcp.authorizationMetadata")(function* (request) {
|
|
44
41
|
const web = yield* HttpServerRequest.toWeb(request);
|
|
45
|
-
return HttpServerResponse.fromWeb(yield*
|
|
46
|
-
catch: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth server metadata failed" }), { cause }),
|
|
47
|
-
try: () => metadata(web),
|
|
48
|
-
}));
|
|
42
|
+
return HttpServerResponse.fromWeb(yield* oauthAuthorizationMetadata(auth, web));
|
|
49
43
|
});
|
|
50
44
|
const routes = HttpRouter.use((router) => Effect.gen(function* () {
|
|
51
45
|
yield* router.add("GET", metadataPath, HttpServerResponse.jsonUnsafe({ "authorization_servers": [config.issuer], resource, "scopes_supported": ["mcp"] }));
|
|
52
46
|
yield* router.add("GET", authorizationMetadataPath, authorizationMetadata);
|
|
53
47
|
}));
|
|
54
|
-
return {
|
|
48
|
+
return { authenticate, resourceMetadataUrl, routes, sessions };
|
|
55
49
|
});
|
|
56
50
|
//# 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,kEAAk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E,MAAM,EAAE,QAAQ,EAAE,CAAC;AAChE,CAAC,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shivaedev/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Identity-aware Effect MCP tools mounted on the application host",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"effect"
|
|
@@ -43,33 +43,29 @@
|
|
|
43
43
|
"README.md"
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@shivaedev/access": "0.
|
|
47
|
-
"@shivaedev/errors": "0.
|
|
48
|
-
"@shivaedev/identity": "0.
|
|
46
|
+
"@shivaedev/access": "0.4.0",
|
|
47
|
+
"@shivaedev/errors": "0.6.0",
|
|
48
|
+
"@shivaedev/identity": "0.20.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.57.0",
|
|
54
|
+
"@shivaedev/rate-limit": "0.3.0",
|
|
55
|
+
"@shivaedev/server": "0.20.0",
|
|
56
|
+
"@shivaedev/test-sql": "0.17.0",
|
|
57
|
+
"@shivaedev/test-story": "0.35.0",
|
|
58
58
|
"@types/node": "24.19.2",
|
|
59
|
-
"better-auth": "1.7.
|
|
59
|
+
"better-auth": "1.7.14",
|
|
60
60
|
"effect": "4.0.6",
|
|
61
61
|
"typescript": "7.0.2",
|
|
62
62
|
"vitest": "5.0.5"
|
|
63
63
|
},
|
|
64
64
|
"peerDependencies": {
|
|
65
|
-
"
|
|
66
|
-
"better-auth": "1.7.12",
|
|
65
|
+
"better-auth": "1.7.14",
|
|
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
|
}
|
package/src/adapters/bearer.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isAPIError } from "better-auth/api";
|
|
2
2
|
import { verifyJwsAccessToken } from "better-auth/oauth2";
|
|
3
3
|
import { Effect, Option } from "effect";
|
|
4
4
|
import { redact } from "@shivaedev/errors/redact.ts";
|
|
5
5
|
import { AuthUnavailable } from "@shivaedev/errors/taxonomy.ts";
|
|
6
|
+
import { InvalidTokenClaim } from "./InvalidTokenClaim.ts";
|
|
6
7
|
|
|
7
8
|
export type JwksSource = Parameters<typeof verifyJwsAccessToken>[1]["jwksFetch"];
|
|
8
9
|
|
|
@@ -17,7 +18,17 @@ const INVALID_TOKEN_ERRORS = new Set([
|
|
|
17
18
|
"ERR_JOSE_NOT_SUPPORTED",
|
|
18
19
|
]);
|
|
19
20
|
|
|
20
|
-
function bearerFailure(cause: unknown) {
|
|
21
|
+
function bearerFailure(cause: unknown): Effect.Effect<Option.Option<never>, AuthUnavailable | InvalidTokenClaim> {
|
|
22
|
+
const claim = cause instanceof Error ? Reflect.get(cause, "claim") : undefined;
|
|
23
|
+
if (
|
|
24
|
+
cause instanceof InvalidTokenClaim
|
|
25
|
+
|| (cause instanceof Error
|
|
26
|
+
&& ["ERR_JWT_CLAIM_VALIDATION_FAILED", "ERR_JWT_EXPIRED"].includes(String(Reflect.get(cause, "code")))
|
|
27
|
+
&& typeof claim === "string")
|
|
28
|
+
) {
|
|
29
|
+
const failure = cause instanceof InvalidTokenClaim ? cause : new InvalidTokenClaim({ claim });
|
|
30
|
+
return Effect.logWarning(failure.message).pipe(Effect.andThen(Effect.fail(failure)));
|
|
31
|
+
}
|
|
21
32
|
if (
|
|
22
33
|
(isAPIError(cause) && (cause.status === "UNAUTHORIZED" || cause.status === "FORBIDDEN"))
|
|
23
34
|
|| (cause instanceof Error && INVALID_TOKEN_ERRORS.has(String(Reflect.get(cause, "code"))))
|
|
@@ -29,6 +40,13 @@ function bearerFailure(cause: unknown) {
|
|
|
29
40
|
);
|
|
30
41
|
}
|
|
31
42
|
|
|
43
|
+
function requiredClaim(value: unknown, claim: string) {
|
|
44
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
45
|
+
throw new InvalidTokenClaim({ claim });
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
|
|
32
50
|
export function bearer(jwks: JwksSource, audience: string, issuer: string) {
|
|
33
51
|
return (token: string | undefined) => {
|
|
34
52
|
if (!token) {
|
|
@@ -36,10 +54,16 @@ export function bearer(jwks: JwksSource, audience: string, issuer: string) {
|
|
|
36
54
|
}
|
|
37
55
|
return Effect.tryPromise(async () => {
|
|
38
56
|
const claims = await verifyJwsAccessToken(token, { jwksFetch: jwks, verifyOptions: { audience, issuer } });
|
|
39
|
-
|
|
40
|
-
|
|
57
|
+
const sub = requiredClaim(claims.sub, "sub");
|
|
58
|
+
const clientId = requiredClaim(claims.client_id, "client_id");
|
|
59
|
+
const grantId = requiredClaim(claims.grant_id, "grant_id");
|
|
60
|
+
if (typeof claims.scope !== "string" || !claims.scope.split(" ").includes("mcp")) {
|
|
61
|
+
throw new InvalidTokenClaim({ claim: "scope" });
|
|
62
|
+
}
|
|
63
|
+
if (claims.cnf !== undefined) {
|
|
64
|
+
throw new InvalidTokenClaim({ claim: "cnf" });
|
|
41
65
|
}
|
|
42
|
-
return claims;
|
|
66
|
+
return { ...claims, "client_id": clientId, "grant_id": grantId, sub };
|
|
43
67
|
}).pipe(
|
|
44
68
|
Effect.map(Option.some),
|
|
45
69
|
Effect.catch(({ cause }) => bearerFailure(cause)),
|
|
@@ -1,26 +1,25 @@
|
|
|
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
|
|
23
|
-
|
|
20
|
+
readonly auth: {
|
|
21
|
+
readonly api: { readonly "getOAuthServerConfig": () => Promise<{ readonly issuer: string; readonly "jwks_uri"?: string }> };
|
|
22
|
+
};
|
|
24
23
|
readonly resource: string;
|
|
25
24
|
readonly jwks?: JwksSource;
|
|
26
25
|
readonly origin: OriginPolicy;
|
|
@@ -30,42 +29,36 @@ export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options:
|
|
|
30
29
|
catch: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth provider configuration failed" }), { cause }),
|
|
31
30
|
try: () => options.auth.api.getOAuthServerConfig(),
|
|
32
31
|
});
|
|
32
|
+
const grants = yield* OauthGrants;
|
|
33
33
|
const { auth, resource } = options;
|
|
34
34
|
const url = new URL(resource);
|
|
35
35
|
const metadataPath = `/.well-known/oauth-protected-resource${url.pathname}` as const;
|
|
36
36
|
const resourceMetadataUrl = new URL(metadataPath, url).href;
|
|
37
37
|
const authorizationMetadataPath = `/.well-known/oauth-authorization-server${new URL(config.issuer).pathname.replace(/\/$/u, "")}` as const;
|
|
38
38
|
const verify = bearer(options.jwks ?? config.jwks_uri ?? new URL("/api/auth/jwks", url).href, resource, config.issuer);
|
|
39
|
+
const authenticate = Effect.fn("Mcp.authenticate")(function* (token: string | undefined) {
|
|
40
|
+
const claims = yield* verify(token);
|
|
41
|
+
if (Option.isNone(claims)) {
|
|
42
|
+
return Option.none();
|
|
43
|
+
}
|
|
44
|
+
const grant = yield* grants.resolveGrant(claims.value.grant_id, claims.value.sub, claims.value.client_id);
|
|
45
|
+
return Option.filter(grant, (live) => live.scopes.includes("mcp")).pipe(Option.map(({ user }) => ({ user })));
|
|
46
|
+
});
|
|
39
47
|
const sessions = Layer.succeed(SessionPolicy, {
|
|
40
48
|
origin: options.origin,
|
|
41
49
|
...(options.roles === undefined ? {} : { roles: options.roles }),
|
|
42
50
|
provider: {
|
|
43
51
|
get: (headers) =>
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
return Option.none();
|
|
50
|
-
}
|
|
51
|
-
const user = yield* grantedUser(auth, claims.value.sub, claims.value.client_id);
|
|
52
|
-
if (user === null || !(yield* options.admitsUser(user.id))) {
|
|
53
|
-
return Option.none();
|
|
54
|
-
}
|
|
55
|
-
const role: unknown = Reflect.get(user, "role");
|
|
56
|
-
return Option.some({ user: { email: user.email, id: user.id, name: user.name, ...(typeof role === "string" ? { role } : {}) } });
|
|
57
|
-
}),
|
|
52
|
+
headers.cookie === undefined
|
|
53
|
+
? authenticate(headers.authorization?.match(/^Bearer (?<token>.+)$/iu)?.groups?.token).pipe(
|
|
54
|
+
Effect.catchTag("InvalidTokenClaim", () => Effect.succeed(Option.none())),
|
|
55
|
+
)
|
|
56
|
+
: Effect.succeed(Option.none()),
|
|
58
57
|
},
|
|
59
58
|
});
|
|
60
|
-
const metadata = oauthProviderAuthServerMetadata(auth);
|
|
61
59
|
const authorizationMetadata = Effect.fn("Mcp.authorizationMetadata")(function* (request: HttpServerRequest.HttpServerRequest) {
|
|
62
60
|
const web = yield* HttpServerRequest.toWeb(request);
|
|
63
|
-
return HttpServerResponse.fromWeb(
|
|
64
|
-
yield* Effect.tryPromise({
|
|
65
|
-
catch: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth server metadata failed" }), { cause }),
|
|
66
|
-
try: () => metadata(web),
|
|
67
|
-
}),
|
|
68
|
-
);
|
|
61
|
+
return HttpServerResponse.fromWeb(yield* oauthAuthorizationMetadata(auth, web));
|
|
69
62
|
});
|
|
70
63
|
const routes = HttpRouter.use((router) =>
|
|
71
64
|
Effect.gen(function* () {
|
|
@@ -77,5 +70,5 @@ export const betterAuthMcp = Effect.fn("Mcp.betterAuthMcp")(function* (options:
|
|
|
77
70
|
yield* router.add("GET", authorizationMetadataPath, authorizationMetadata);
|
|
78
71
|
}),
|
|
79
72
|
);
|
|
80
|
-
return {
|
|
73
|
+
return { authenticate, resourceMetadataUrl, routes, sessions };
|
|
81
74
|
});
|
|
@@ -1,38 +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 & {
|
|
21
|
-
cause: unknown;
|
|
22
|
-
}, never>;
|
|
23
|
-
revokeClient: (userId: string, clientId: string) => Effect.Effect<void, AuthUnavailable & {
|
|
24
|
-
cause: unknown;
|
|
25
|
-
}, never>;
|
|
26
|
-
};
|
|
27
|
-
export declare const grantedUser: (auth: OauthAuth, userId: string, clientId: string) => Effect.Effect<{
|
|
28
|
-
id: string;
|
|
29
|
-
createdAt: Date;
|
|
30
|
-
updatedAt: Date;
|
|
31
|
-
email: string;
|
|
32
|
-
emailVerified: boolean;
|
|
33
|
-
name: string;
|
|
34
|
-
image?: string | null | undefined;
|
|
35
|
-
} | null, AuthUnavailable & {
|
|
36
|
-
cause: unknown;
|
|
37
|
-
}, never>;
|
|
38
|
-
//# sourceMappingURL=oauthGrants.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"oauthGrants.d.ts","sourceRoot":"","s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
3
|
-
export function oauthGrants(auth) {
|
|
4
|
-
const revoke = Effect.fn("Mcp.revoke")(function* (userId, clientId) {
|
|
5
|
-
yield* Effect.tryPromise({
|
|
6
|
-
catch: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth grant revocation failed" }), { cause }),
|
|
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: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth grant lookup failed" }), { cause }),
|
|
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
|
-
});
|
|
43
|
-
//# sourceMappingURL=oauthGrants.js.map
|
|
@@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,CAAC,CAAC;AACJ,CAAC,CAAC,CAAC"}
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
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: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth grant revocation failed" }), { cause }),
|
|
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: (cause) => Object.assign(new AuthUnavailable({ message: "OAuth grant lookup failed" }), { cause }),
|
|
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
|
-
});
|