@zgeoff/mcp-auth 0.2.1 → 0.2.3

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.
Files changed (32) hide show
  1. package/README.md +16 -1
  2. package/dist/index.d.ts +1 -0
  3. package/dist/service-tokens/build-service-snapshot.d.ts +11 -0
  4. package/dist/service-tokens/create-issued-tokens.d.ts +15 -0
  5. package/dist/service-tokens/create-service-state.d.ts +11 -0
  6. package/dist/service-tokens/derive-secret-digest.d.ts +1 -0
  7. package/dist/service-tokens/mint-service-secret.d.ts +4 -0
  8. package/dist/service-tokens/parse-basic-credentials.d.ts +5 -0
  9. package/dist/sign-in/route-context.d.ts +2 -0
  10. package/dist/tokens/answer-client-credentials-request.d.ts +3 -0
  11. package/dist/tokens/build-oauth-error.d.ts +1 -1
  12. package/dist/tokens/pick-client-credentials-scopes.d.ts +1 -0
  13. package/dist/types.d.ts +2 -0
  14. package/package.json +6 -6
  15. package/src/index.ts +1 -0
  16. package/src/open-mcp-auth.ts +68 -11
  17. package/src/service-tokens/build-service-snapshot.ts +26 -0
  18. package/src/service-tokens/build-service-token-verifier.ts +1 -1
  19. package/src/service-tokens/create-issued-tokens.ts +78 -0
  20. package/src/service-tokens/create-service-state.ts +29 -0
  21. package/src/service-tokens/derive-secret-digest.ts +6 -0
  22. package/src/service-tokens/mint-service-secret.ts +9 -0
  23. package/src/service-tokens/parse-basic-credentials.ts +48 -0
  24. package/src/service-tokens/parse-service-token-file.ts +40 -20
  25. package/src/sign-in/route-context.ts +2 -0
  26. package/src/tokens/answer-client-credentials-request.ts +156 -0
  27. package/src/tokens/answer-metadata-request.ts +16 -4
  28. package/src/tokens/answer-token-request.ts +19 -1
  29. package/src/tokens/build-oauth-error.ts +7 -2
  30. package/src/tokens/pick-client-credentials-scopes.ts +14 -0
  31. package/src/tokens/record-token-exchange.ts +1 -0
  32. package/src/types.ts +12 -0
package/README.md CHANGED
@@ -63,6 +63,21 @@ app.use(
63
63
 
64
64
  A command that only manages clients, grants and passkeys calls `openMCPAuthAdmin`, with no origin.
65
65
 
66
+ ## Service clients
67
+
68
+ A client with no browser, such as a CI job, gets a service client in the service-token file, with
69
+ static tokens, `secretDigests`, or both. A client with a digest uses the `client_credentials` grant:
70
+ it sends its ID, `service:<name>`, and its secret in a `client_secret_basic` header to the token
71
+ route, and gets a 600-second access token capped to its scopes. `verify` gives that token the same
72
+ `service` access that a static token gets.
73
+
74
+ `mintServiceSecret()` returns `{ secret, digest }`. Show the secret once, and put only the digest in
75
+ the file. A client holds 1 or 2 digests, so a rotation adds the new one, then drops the old one.
76
+
77
+ An app reloads the file on `SIGHUP` and calls `auth.replaceServiceTokens(file)` with the parsed
78
+ result. The next token request and the next `verify` read the new file, and a file that fails to
79
+ parse leaves the old one in place.
80
+
66
81
  ## Features
67
82
 
68
83
  - OAuth authorization code flow with PKCE for clients the owner adds by name.
@@ -70,7 +85,7 @@ A command that only manages clients, grants and passkeys calls `openMCPAuthAdmin
70
85
  - Refresh tokens that rotate, and a grant that ends when a client replays a replaced token.
71
86
  - A revoke that ends every token of a grant with one delete, even in the middle of a refresh.
72
87
  - Bearer tokens only: the token route drops DPoP, and `verify` refuses a token bound to a key.
73
- - Service tokens for clients that cannot run the browser flow.
88
+ - Service tokens, and the `client_credentials` grant, for clients that cannot run the browser flow.
74
89
  - An Elysia adapter that checks Host, Origin and the bearer token of each MCP request.
75
90
  - Test helpers: `openTestAuth`, `authorizeTestClient`, and seeds for clients and passkeys.
76
91
 
package/dist/index.d.ts CHANGED
@@ -4,5 +4,6 @@ export type { MCPAuthErrorCode } from './mcp-auth-error.ts';
4
4
  export { openMCPAuth } from './open-mcp-auth.ts';
5
5
  export { openMCPAuthAdmin } from './open-mcp-auth-admin.ts';
6
6
  export { normalizeClientName } from './utils/normalize-client-name.ts';
7
+ export { mintServiceSecret } from './service-tokens/mint-service-secret.ts';
7
8
  export { parseServiceTokenFile } from './service-tokens/parse-service-token-file.ts';
8
9
  export type * from './types.ts';
@@ -0,0 +1,11 @@
1
+ import type { ServiceTokenFile } from '../types.ts';
2
+ import type { ServiceTokenVerifier } from './build-service-token-verifier.ts';
3
+ export interface ServiceSnapshot<Scope extends string> {
4
+ readonly file: ServiceTokenFile<Scope>;
5
+ readonly verifier: ServiceTokenVerifier<Scope>;
6
+ readonly secrets: readonly {
7
+ readonly digest: Buffer;
8
+ readonly clientID: string;
9
+ }[];
10
+ }
11
+ export declare function buildServiceSnapshot<Scope extends string>(file: ServiceTokenFile<Scope>): ServiceSnapshot<Scope>;
@@ -0,0 +1,15 @@
1
+ import type { Clock } from '../types.ts';
2
+ export declare const ISSUED_TOKEN_PREFIX = "svca_";
3
+ export declare const ISSUED_TOKEN_SECONDS = 600;
4
+ export declare const ISSUED_TOKEN_CAP = 1000;
5
+ export interface IssuedToken {
6
+ readonly clientName: string;
7
+ readonly scopes: readonly string[];
8
+ readonly expiresAtMs: number;
9
+ }
10
+ export interface IssuedTokens {
11
+ readonly writeToken: (clientName: string, scopes: readonly string[]) => string | null;
12
+ readonly findToken: (token: string) => IssuedToken | null;
13
+ readonly removeToken: (token: string) => void;
14
+ }
15
+ export declare function createIssuedTokens(clock: Clock): IssuedTokens;
@@ -0,0 +1,11 @@
1
+ import type { Clock, ServiceTokenFile } from '../types.ts';
2
+ import type { ServiceSnapshot } from './build-service-snapshot.ts';
3
+ import type { IssuedTokens } from './create-issued-tokens.ts';
4
+ export interface ServiceState<Scope extends string> {
5
+ readonly findSnapshot: () => ServiceSnapshot<Scope> | null;
6
+ readonly issued: IssuedTokens;
7
+ }
8
+ export declare function createServiceState<Scope extends string>(file: ServiceTokenFile<Scope> | null, clock: Clock): {
9
+ readonly state: ServiceState<Scope>;
10
+ readonly replace: (file: ServiceTokenFile<Scope>) => void;
11
+ };
@@ -0,0 +1 @@
1
+ export declare function deriveSecretDigest(secret: string): string;
@@ -0,0 +1,4 @@
1
+ export declare function mintServiceSecret(): {
2
+ readonly secret: string;
3
+ readonly digest: string;
4
+ };
@@ -0,0 +1,5 @@
1
+ export interface BasicCredentials {
2
+ readonly clientID: string;
3
+ readonly secret: string;
4
+ }
5
+ export declare function parseBasicCredentials(header: string | null): BasicCredentials | null;
@@ -1,4 +1,5 @@
1
1
  import type { EnrollmentState } from '../passkeys/create-enrollment-state.ts';
2
+ import type { ServiceState } from '../service-tokens/create-service-state.ts';
2
3
  import type { Store } from '../store/open-store.ts';
3
4
  import type { Clock, GrantLimits, MCPAuthPaths, SecuritySink } from '../types.ts';
4
5
  import type { SignInState } from './create-sign-in-state.ts';
@@ -11,6 +12,7 @@ export interface RouteContext {
11
12
  readonly scopes: readonly string[];
12
13
  readonly clock: Clock;
13
14
  readonly security: SecuritySink;
15
+ readonly services: ServiceState<string>;
14
16
  readonly signIns: SignInState;
15
17
  readonly enrollments: EnrollmentState;
16
18
  readonly consentFields: Pick<GrantLimits<unknown>, 'renderConsentFields' | 'parseConsentFields'> | null;
@@ -0,0 +1,3 @@
1
+ import type { RouteContext } from '../sign-in/route-context.ts';
2
+ import type { Requester } from '../types.ts';
3
+ export declare function answerClientCredentialsRequest(ctx: RouteContext, request: Request, form: Readonly<URLSearchParams>, requester: Requester): Response;
@@ -1 +1 @@
1
- export declare function buildOAuthError(status: number, error: string, description: string): Response;
1
+ export declare function buildOAuthError(status: number, error: string, description: string, headers?: Readonly<Record<string, string>>): Response;
@@ -0,0 +1 @@
1
+ export declare function pickClientCredentialsScopes(requested: string | null, clientScopes: readonly string[]): readonly string[] | null;
package/dist/types.d.ts CHANGED
@@ -65,6 +65,7 @@ export interface ServiceClient<Scope extends string> {
65
65
  readonly name: string;
66
66
  readonly scopes: readonly Scope[];
67
67
  readonly tokens: readonly string[];
68
+ readonly secretDigests?: readonly string[];
68
69
  }
69
70
  export interface ServiceTokenFile<Scope extends string> {
70
71
  readonly resource: string;
@@ -151,6 +152,7 @@ export interface MCPAuth<Scope extends string, Limits = null> extends MCPAuthAdm
151
152
  readonly routes: MCPAuthRoutes;
152
153
  readonly verify: (bearer: string) => Promise<Access<Scope, Limits> | null>;
153
154
  readonly findClientScopes: (clientID: string) => Promise<readonly Scope[] | null>;
155
+ replaceServiceTokens(file: ServiceTokenFile<Scope>): void;
154
156
  }
155
157
  export interface ConsentRequest {
156
158
  readonly clientID: OAuthClientID;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/mcp-auth",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "A shared OAuth server for the MCP route of an app, built on better-auth, with passkey sign-in for the owner",
5
5
  "keywords": [
6
6
  "better-auth",
@@ -39,14 +39,14 @@
39
39
  },
40
40
  "scripts": {
41
41
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
42
- "typecheck": "tsrs"
42
+ "typecheck": "tsrs --fast"
43
43
  },
44
44
  "dependencies": {
45
45
  "@better-auth/mcp": "1.7.15",
46
46
  "@better-auth/oauth-provider": "1.7.15",
47
- "@simplewebauthn/server": "14.0.3",
48
- "@zgeoff/kysely-bun-sqlite": "0.3.2",
49
- "@zgeoff/std": "0.4.3",
47
+ "@simplewebauthn/server": "14.1.0",
48
+ "@zgeoff/kysely-bun-sqlite": "0.3.3",
49
+ "@zgeoff/std": "0.4.4",
50
50
  "better-auth": "1.7.15",
51
51
  "reflect-metadata": "0.2.2",
52
52
  "ts-pattern": "5.9.2",
@@ -58,7 +58,7 @@
58
58
  "elysia": "2.0.0-rc.3",
59
59
  "kysely": "0.29.8",
60
60
  "tiny-invariant": "1.3.3",
61
- "tsrs": "0.18.0-ts7.1.0-dev.20260929",
61
+ "tsrs": "0.25.0-ts7.1.0-beta",
62
62
  "typescript": "7.0.2"
63
63
  },
64
64
  "peerDependencies": {
package/src/index.ts CHANGED
@@ -4,5 +4,6 @@ export type { MCPAuthErrorCode } from './mcp-auth-error.ts';
4
4
  export { openMCPAuth } from './open-mcp-auth.ts';
5
5
  export { openMCPAuthAdmin } from './open-mcp-auth-admin.ts';
6
6
  export { normalizeClientName } from './utils/normalize-client-name.ts';
7
+ export { mintServiceSecret } from './service-tokens/mint-service-secret.ts';
7
8
  export { parseServiceTokenFile } from './service-tokens/parse-service-token-file.ts';
8
9
  export type * from './types.ts';
@@ -4,12 +4,15 @@ import { verifyOAuthAccess } from './grants/verify-oauth-access.ts';
4
4
  import { MCPAuthError } from './mcp-auth-error.ts';
5
5
  import { createEnrollmentState } from './passkeys/create-enrollment-state.ts';
6
6
  import { buildRoutes } from './routes/build-routes.ts';
7
- import { buildServiceTokenVerifier } from './service-tokens/build-service-token-verifier.ts';
7
+ import type { ServiceSnapshot } from './service-tokens/build-service-snapshot.ts';
8
+ import { ISSUED_TOKEN_PREFIX } from './service-tokens/create-issued-tokens.ts';
9
+ import { createServiceState } from './service-tokens/create-service-state.ts';
10
+ import type { ServiceState } from './service-tokens/create-service-state.ts';
8
11
  import { createSignInState } from './sign-in/create-sign-in-state.ts';
9
12
  import type { RouteContext } from './sign-in/route-context.ts';
10
13
  import { CODE_SECONDS } from './store/create-auth-server.ts';
11
14
  import { openStore } from './store/open-store.ts';
12
- import type { MCPAuth, MCPAuthOptions } from './types.ts';
15
+ import type { Access, MCPAuth, MCPAuthOptions } from './types.ts';
13
16
 
14
17
  export async function openMCPAuth<Scope extends string, Limits = null>(
15
18
  options: MCPAuthOptions<Scope, Limits>,
@@ -23,12 +26,25 @@ export async function openMCPAuth<Scope extends string, Limits = null>(
23
26
  );
24
27
  }
25
28
 
29
+ const prefix = options.serviceTokens?.prefix ?? null;
30
+
31
+ if (
32
+ prefix !== null &&
33
+ (prefix.startsWith(ISSUED_TOKEN_PREFIX) || ISSUED_TOKEN_PREFIX.startsWith(prefix))
34
+ ) {
35
+ throw new MCPAuthError(
36
+ 'invalid-setup',
37
+ `the service token prefix and ${ISSUED_TOKEN_PREFIX} must not start with one another`,
38
+ );
39
+ }
40
+
26
41
  const store = await openStore(options, { origin: options.origin, paths: options.paths });
27
42
 
28
43
  // A resource served under an earlier origin stays a valid token target until
29
44
  // its row goes.
30
45
  await store.db.deleteFrom('oauthResource').where('identifier', '!=', resource).execute();
31
46
 
47
+ const services = createServiceState(options.serviceTokens?.file ?? null, options.clock);
32
48
  const signIns = createSignInState(CODE_SECONDS * 1000, options.clock.now);
33
49
 
34
50
  const routes = buildRoutes({
@@ -40,17 +56,12 @@ export async function openMCPAuth<Scope extends string, Limits = null>(
40
56
  scopes: options.scopes,
41
57
  clock: options.clock,
42
58
  security: options.security,
59
+ services: services.state,
43
60
  signIns,
44
61
  enrollments: createEnrollmentState(options.clock.now),
45
62
  consentFields: options.grantLimits ?? null,
46
63
  } satisfies RouteContext);
47
64
 
48
- const serviceTokens =
49
- options.serviceTokens === undefined
50
- ? null
51
- : buildServiceTokenVerifier(options.serviceTokens.file);
52
-
53
- const prefix = options.serviceTokens?.prefix ?? null;
54
65
  const scopes = options.scopes;
55
66
  const grantLimits = options.grantLimits ?? null;
56
67
 
@@ -62,8 +73,14 @@ export async function openMCPAuth<Scope extends string, Limits = null>(
62
73
  routes,
63
74
 
64
75
  verify: (bearer) => {
65
- if (serviceTokens !== null && prefix !== null && bearer.startsWith(prefix)) {
66
- return Promise.resolve(serviceTokens.verify(bearer));
76
+ const snapshot = services.state.findSnapshot();
77
+
78
+ if (snapshot !== null && bearer.startsWith(ISSUED_TOKEN_PREFIX)) {
79
+ return Promise.resolve(verifyIssuedToken(services.state, snapshot, bearer));
80
+ }
81
+
82
+ if (snapshot !== null && prefix !== null && bearer.startsWith(prefix)) {
83
+ return Promise.resolve(snapshot.verifier.verify(bearer));
67
84
  }
68
85
 
69
86
  return verifyOAuthAccess(
@@ -79,11 +96,51 @@ export async function openMCPAuth<Scope extends string, Limits = null>(
79
96
 
80
97
  // oxlint-disable-next-line zgeoff/verb-contract -- the contract names this call findClientScopes
81
98
  findClientScopes: (clientID) => {
82
- const service = serviceTokens?.findScopes(clientID) ?? null;
99
+ const service = services.state.findSnapshot()?.verifier.findScopes(clientID) ?? null;
83
100
 
84
101
  return service === null
85
102
  ? readClientScopes(store, scopes, clientID)
86
103
  : Promise.resolve(service);
87
104
  },
105
+
106
+ replaceServiceTokens: (file) => {
107
+ if (services.state.findSnapshot() === null) {
108
+ throw new MCPAuthError('invalid-setup', 'the server was opened with no service tokens');
109
+ }
110
+
111
+ if (file.resource !== resource) {
112
+ throw new MCPAuthError(
113
+ 'invalid-setup',
114
+ `the service token file names another resource than ${resource}`,
115
+ );
116
+ }
117
+
118
+ services.replace(file);
119
+ },
88
120
  };
89
121
  }
122
+
123
+ // The client's current scopes, cut to the scopes the token was issued with.
124
+ function verifyIssuedToken<Scope extends string>(
125
+ state: ServiceState<Scope>,
126
+ snapshot: ServiceSnapshot<Scope>,
127
+ bearer: string,
128
+ ): Access<Scope, never> | null {
129
+ const entry = state.issued.findToken(bearer);
130
+
131
+ if (entry === null) {
132
+ return null;
133
+ }
134
+
135
+ const clientID: `service:${string}` = `service:${entry.clientName}`;
136
+ const current = snapshot.verifier.findScopes(clientID);
137
+ const scopes = current?.filter((scope) => entry.scopes.includes(scope)) ?? [];
138
+
139
+ if (scopes.length === 0) {
140
+ state.issued.removeToken(bearer);
141
+
142
+ return null;
143
+ }
144
+
145
+ return { kind: 'service', clientID, clientName: clientID, scopes };
146
+ }
@@ -0,0 +1,26 @@
1
+ import type { ServiceTokenFile } from '../types.ts';
2
+ import { buildServiceTokenVerifier } from './build-service-token-verifier.ts';
3
+ import type { ServiceTokenVerifier } from './build-service-token-verifier.ts';
4
+
5
+ export interface ServiceSnapshot<Scope extends string> {
6
+ readonly file: ServiceTokenFile<Scope>;
7
+ readonly verifier: ServiceTokenVerifier<Scope>;
8
+
9
+ // Every secret digest of every client, as bytes.
10
+ readonly secrets: readonly { readonly digest: Buffer; readonly clientID: string }[];
11
+ }
12
+
13
+ export function buildServiceSnapshot<Scope extends string>(
14
+ file: ServiceTokenFile<Scope>,
15
+ ): ServiceSnapshot<Scope> {
16
+ return {
17
+ file,
18
+ verifier: buildServiceTokenVerifier(file),
19
+ secrets: file.clients.flatMap((client) =>
20
+ (client.secretDigests ?? []).map((digest) => ({
21
+ digest: Buffer.from(digest, 'hex'),
22
+ clientID: `service:${client.name}`,
23
+ })),
24
+ ),
25
+ };
26
+ }
@@ -47,7 +47,7 @@ export function buildServiceTokenVerifier<Scope extends string>(
47
47
  return match;
48
48
  },
49
49
  findScopes: (clientID) =>
50
- stored.find((entry) => entry.access.clientID === clientID)?.access.scopes ?? null,
50
+ file.clients.find((client) => `service:${client.name}` === clientID)?.scopes ?? null,
51
51
  };
52
52
  }
53
53
 
@@ -0,0 +1,78 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import type { Clock } from '../types.ts';
3
+ import { deriveSecretDigest } from './derive-secret-digest.ts';
4
+
5
+ export const ISSUED_TOKEN_PREFIX = 'svca_';
6
+ export const ISSUED_TOKEN_SECONDS = 600;
7
+ export const ISSUED_TOKEN_CAP = 1000;
8
+
9
+ export interface IssuedToken {
10
+ readonly clientName: string;
11
+ readonly scopes: readonly string[];
12
+ readonly expiresAtMs: number;
13
+ }
14
+
15
+ export interface IssuedTokens {
16
+ // The new token, or null at the cap once the expired tokens are gone.
17
+ readonly writeToken: (clientName: string, scopes: readonly string[]) => string | null;
18
+
19
+ // Null for an unknown or expired token.
20
+ readonly findToken: (token: string) => IssuedToken | null;
21
+ readonly removeToken: (token: string) => void;
22
+ }
23
+
24
+ // Only the digest of each token stays in memory, and a restart empties the map.
25
+ export function createIssuedTokens(clock: Clock): IssuedTokens {
26
+ const issued = new Map<string, IssuedToken>();
27
+
28
+ const removeExpired = (): void => {
29
+ const now = clock.now();
30
+
31
+ for (const [key, entry] of issued) {
32
+ if (entry.expiresAtMs <= now) {
33
+ issued.delete(key);
34
+ }
35
+ }
36
+ };
37
+
38
+ return {
39
+ writeToken: (clientName, scopes) => {
40
+ if (issued.size >= ISSUED_TOKEN_CAP) {
41
+ removeExpired();
42
+ }
43
+
44
+ if (issued.size >= ISSUED_TOKEN_CAP) {
45
+ return null;
46
+ }
47
+
48
+ const token = `${ISSUED_TOKEN_PREFIX}${randomBytes(32).toString('base64url')}`;
49
+
50
+ issued.set(deriveSecretDigest(token), {
51
+ clientName,
52
+ scopes,
53
+ expiresAtMs: clock.now() + ISSUED_TOKEN_SECONDS * 1000,
54
+ });
55
+
56
+ return token;
57
+ },
58
+ findToken: (token) => {
59
+ const key = deriveSecretDigest(token);
60
+ const entry = issued.get(key);
61
+
62
+ if (entry === undefined) {
63
+ return null;
64
+ }
65
+
66
+ if (entry.expiresAtMs <= clock.now()) {
67
+ issued.delete(key);
68
+
69
+ return null;
70
+ }
71
+
72
+ return entry;
73
+ },
74
+ removeToken: (token) => {
75
+ issued.delete(deriveSecretDigest(token));
76
+ },
77
+ };
78
+ }
@@ -0,0 +1,29 @@
1
+ import type { Clock, ServiceTokenFile } from '../types.ts';
2
+ import { buildServiceSnapshot } from './build-service-snapshot.ts';
3
+ import type { ServiceSnapshot } from './build-service-snapshot.ts';
4
+ import { createIssuedTokens } from './create-issued-tokens.ts';
5
+ import type { IssuedTokens } from './create-issued-tokens.ts';
6
+
7
+ // What the token route and `verify` read on each call.
8
+ export interface ServiceState<Scope extends string> {
9
+ // Null when the app passed no service tokens.
10
+ readonly findSnapshot: () => ServiceSnapshot<Scope> | null;
11
+ readonly issued: IssuedTokens;
12
+ }
13
+
14
+ export function createServiceState<Scope extends string>(
15
+ file: ServiceTokenFile<Scope> | null,
16
+ clock: Clock,
17
+ ): {
18
+ readonly state: ServiceState<Scope>;
19
+ readonly replace: (file: ServiceTokenFile<Scope>) => void;
20
+ } {
21
+ let snapshot = file === null ? null : buildServiceSnapshot(file);
22
+
23
+ return {
24
+ state: { findSnapshot: () => snapshot, issued: createIssuedTokens(clock) },
25
+ replace: (next) => {
26
+ snapshot = buildServiceSnapshot(next);
27
+ },
28
+ };
29
+ }
@@ -0,0 +1,6 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ // The sha256 of the whole secret, as lowercase hex.
4
+ export function deriveSecretDigest(secret: string): string {
5
+ return createHash('sha256').update(secret).digest('hex');
6
+ }
@@ -0,0 +1,9 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { deriveSecretDigest } from './derive-secret-digest.ts';
3
+
4
+ // The secret is shown once; the service-token file holds only its digest.
5
+ export function mintServiceSecret(): { readonly secret: string; readonly digest: string } {
6
+ const secret = `svcs_${randomBytes(32).toString('base64url')}`;
7
+
8
+ return { secret, digest: deriveSecretDigest(secret) };
9
+ }
@@ -0,0 +1,48 @@
1
+ export interface BasicCredentials {
2
+ readonly clientID: string;
3
+ readonly secret: string;
4
+ }
5
+
6
+ const BASIC_PATTERN = /^basic +(?<encoded>[A-Za-z0-9+/]+={0,2})$/iu;
7
+
8
+ // RFC 6749 section 2.3.1 form-encodes both parts, and the MCP SDK's client
9
+ // sends the ID raw, so both parse. The split is at the last colon, because the
10
+ // secret holds none.
11
+ export function parseBasicCredentials(header: string | null): BasicCredentials | null {
12
+ const encoded = header === null ? undefined : BASIC_PATTERN.exec(header)?.groups?.['encoded'];
13
+
14
+ if (encoded === undefined) {
15
+ return null;
16
+ }
17
+
18
+ let decoded: string;
19
+
20
+ try {
21
+ decoded = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(encoded, 'base64'));
22
+ } catch {
23
+ return null;
24
+ }
25
+
26
+ const colon = decoded.lastIndexOf(':');
27
+
28
+ if (colon === -1) {
29
+ return null;
30
+ }
31
+
32
+ const clientID = decodeFormValue(decoded.slice(0, colon));
33
+ const secret = decodeFormValue(decoded.slice(colon + 1));
34
+
35
+ if (clientID === null || secret === null || clientID === '' || secret === '') {
36
+ return null;
37
+ }
38
+
39
+ return { clientID, secret };
40
+ }
41
+
42
+ function decodeFormValue(value: string): string | null {
43
+ try {
44
+ return decodeURIComponent(value.replaceAll('+', ' '));
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
@@ -12,6 +12,8 @@ interface ServiceTokenRules<Scope extends string> {
12
12
  // file may be a token.
13
13
  const NAME_MESSAGE = 'a client name must match [a-z][a-z0-9-]{0,31}';
14
14
  const NameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/u, NAME_MESSAGE);
15
+ const DIGEST_PATTERN = /^[0-9a-f]{64}$/u;
16
+ const DIGEST_MESSAGE = 'a secret digest must be 64 lowercase hex characters';
15
17
 
16
18
  export function parseServiceTokenFile<Scope extends string>(
17
19
  text: string,
@@ -30,21 +32,31 @@ export function parseServiceTokenFile<Scope extends string>(
30
32
 
31
33
  const tokenPattern = new RegExp(`^${escapePattern(rules.prefix)}[A-Za-z0-9_-]{32,}$`, 'u');
32
34
 
33
- const ClientSchema = z.strictObject({
34
- scopes: z
35
- .array(
36
- z
37
- .string()
38
- .refine((scope): scope is Scope => rules.scopes.some((known) => known === scope), {
39
- message: 'a scope must be one the server knows',
40
- }),
41
- )
42
- .min(1, 'must name at least one scope'),
43
- tokens: z
44
- .array(z.string().regex(tokenPattern, tokenMessage))
45
- .min(1, 'must hold 1 or 2 tokens')
46
- .max(2, 'must hold 1 or 2 tokens'),
47
- });
35
+ const ClientSchema = z
36
+ .strictObject({
37
+ scopes: z
38
+ .array(
39
+ z
40
+ .string()
41
+ .refine((scope): scope is Scope => rules.scopes.some((known) => known === scope), {
42
+ message: 'a scope must be one the server knows',
43
+ }),
44
+ )
45
+ .min(1, 'must name at least one scope'),
46
+ tokens: z
47
+ .array(z.string().regex(tokenPattern, tokenMessage))
48
+ .max(2, 'must hold 1 or 2 tokens')
49
+ .default([]),
50
+ secretDigests: z
51
+ .array(z.string().regex(DIGEST_PATTERN, DIGEST_MESSAGE))
52
+ .min(1, 'must hold 1 or 2 secret digests')
53
+ .max(2, 'must hold 1 or 2 secret digests')
54
+ .optional(),
55
+ })
56
+ .refine(
57
+ (client) => client.tokens.length > 0 || client.secretDigests !== undefined,
58
+ 'must hold 1 or 2 tokens, or 1 or 2 secret digests',
59
+ );
48
60
 
49
61
  const FileSchema = z.strictObject({
50
62
  resource: z.string().min(1, 'must be the resource URL the server serves'),
@@ -59,11 +71,13 @@ export function parseServiceTokenFile<Scope extends string>(
59
71
  return { ok: false, reason: parsed.error.issues.map((issue) => formatIssue(issue)).join('; ') };
60
72
  }
61
73
 
62
- const clients = Object.entries(parsed.data.clients).map(([name, client]) => ({
63
- name,
64
- scopes: [...new Set(client.scopes)],
65
- tokens: client.tokens,
66
- }));
74
+ const clients = Object.entries(parsed.data.clients).map(([name, client]) => {
75
+ const scopes = [...new Set(client.scopes)];
76
+
77
+ return client.secretDigests === undefined
78
+ ? { name, scopes, tokens: client.tokens }
79
+ : { name, scopes, tokens: client.tokens, secretDigests: client.secretDigests };
80
+ });
67
81
 
68
82
  const tokens = clients.flatMap((client) => client.tokens);
69
83
 
@@ -71,6 +85,12 @@ export function parseServiceTokenFile<Scope extends string>(
71
85
  return { ok: false, reason: 'the same token appears more than once' };
72
86
  }
73
87
 
88
+ const digests = clients.flatMap((client) => client.secretDigests ?? []);
89
+
90
+ if (new Set(digests).size !== digests.length) {
91
+ return { ok: false, reason: 'the same secret digest appears more than once' };
92
+ }
93
+
74
94
  return { ok: true, file: { resource: parsed.data.resource, clients } };
75
95
  }
76
96
 
@@ -1,4 +1,5 @@
1
1
  import type { EnrollmentState } from '../passkeys/create-enrollment-state.ts';
2
+ import type { ServiceState } from '../service-tokens/create-service-state.ts';
2
3
  import type { Store } from '../store/open-store.ts';
3
4
  import type { Clock, GrantLimits, MCPAuthPaths, SecuritySink } from '../types.ts';
4
5
  import type { SignInState } from './create-sign-in-state.ts';
@@ -16,6 +17,7 @@ export interface RouteContext {
16
17
  readonly scopes: readonly string[];
17
18
  readonly clock: Clock;
18
19
  readonly security: SecuritySink;
20
+ readonly services: ServiceState<string>;
19
21
  readonly signIns: SignInState;
20
22
  readonly enrollments: EnrollmentState;
21
23
  readonly consentFields: Pick<
@@ -0,0 +1,156 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { toTagged } from '@zgeoff/std';
3
+ import type { ServiceSnapshot } from '../service-tokens/build-service-snapshot.ts';
4
+ import { ISSUED_TOKEN_SECONDS } from '../service-tokens/create-issued-tokens.ts';
5
+ import { parseBasicCredentials } from '../service-tokens/parse-basic-credentials.ts';
6
+ import type { BasicCredentials } from '../service-tokens/parse-basic-credentials.ts';
7
+ import type { RouteContext } from '../sign-in/route-context.ts';
8
+ import type { OAuthClientID, Requester } from '../types.ts';
9
+ import { buildOAuthError } from './build-oauth-error.ts';
10
+ import { pickClientCredentialsScopes } from './pick-client-credentials-scopes.ts';
11
+
12
+ // The client_credentials grant, answered here and never by better-auth, whose
13
+ // own grant keeps one secret per client in its tables.
14
+ export function answerClientCredentialsRequest(
15
+ ctx: RouteContext,
16
+ request: Request,
17
+ form: Readonly<URLSearchParams>,
18
+ requester: Requester,
19
+ ): Response {
20
+ const snapshot = ctx.services.findSnapshot();
21
+ const claimed = parseBasicCredentials(request.headers.get('authorization'));
22
+ const outcome = decideOutcome(ctx, snapshot, claimed, form);
23
+
24
+ const claimedClient =
25
+ snapshot === null || claimed === null
26
+ ? undefined
27
+ : snapshot.file.clients.find((client) => `service:${client.name}` === claimed.clientID);
28
+
29
+ const client =
30
+ claimedClient === undefined
31
+ ? {}
32
+ : {
33
+ client: {
34
+ id: toTagged<OAuthClientID>(`service:${claimedClient.name}`),
35
+ name: `service:${claimedClient.name}`,
36
+ },
37
+ };
38
+
39
+ ctx.security.record({
40
+ kind: 'token_exchange',
41
+ ...(outcome.error === null
42
+ ? { outcome: 'succeeded' as const }
43
+ : { outcome: 'rejected' as const, reason: outcome.error }),
44
+ path: new URL(request.url).pathname,
45
+ requester,
46
+ ...client,
47
+ });
48
+
49
+ return outcome.response;
50
+ }
51
+
52
+ interface Outcome {
53
+ readonly response: Response;
54
+
55
+ // Null for a success.
56
+ readonly error: string | null;
57
+ }
58
+
59
+ function decideOutcome(
60
+ ctx: RouteContext,
61
+ snapshot: ServiceSnapshot<string> | null,
62
+ claimed: BasicCredentials | null,
63
+ form: Readonly<URLSearchParams>,
64
+ ): Outcome {
65
+ if (snapshot === null || snapshot.secrets.length === 0) {
66
+ return refuse(400, 'unsupported_grant_type', 'the server has no service clients with secrets');
67
+ }
68
+
69
+ const authenticated = readAuthenticatedClient(ctx, snapshot, claimed, form);
70
+
71
+ if ('response' in authenticated) {
72
+ return authenticated;
73
+ }
74
+
75
+ const scopes = pickClientCredentialsScopes(form.get('scope'), authenticated.scopes);
76
+
77
+ if (scopes === null) {
78
+ return refuse(400, 'invalid_scope', 'the client does not hold a requested scope');
79
+ }
80
+
81
+ const resources = form.getAll('resource');
82
+
83
+ if (resources.length > 1 || (resources[0] !== undefined && resources[0] !== ctx.resource)) {
84
+ return refuse(400, 'invalid_target', `the only resource is ${ctx.resource}`);
85
+ }
86
+
87
+ const token = ctx.services.issued.writeToken(authenticated.name, scopes);
88
+
89
+ if (token === null) {
90
+ return refuse(503, 'temporarily_unavailable', 'too many access tokens are live; retry later');
91
+ }
92
+
93
+ return {
94
+ error: null,
95
+ response: Response.json(
96
+ {
97
+ access_token: token,
98
+ token_type: 'Bearer',
99
+ expires_in: ISSUED_TOKEN_SECONDS,
100
+ scope: scopes.join(' '),
101
+ },
102
+ { headers: { 'cache-control': 'no-store' } },
103
+ ),
104
+ };
105
+ }
106
+
107
+ function refuse(
108
+ status: number,
109
+ error: string,
110
+ description: string,
111
+ headers: Readonly<Record<string, string>> = {},
112
+ ): Outcome {
113
+ return { error, response: buildOAuthError(status, error, description, headers) };
114
+ }
115
+
116
+ function readAuthenticatedClient(
117
+ ctx: RouteContext,
118
+ snapshot: ServiceSnapshot<string>,
119
+ claimed: BasicCredentials | null,
120
+ form: Readonly<URLSearchParams>,
121
+ ): Outcome | { readonly name: string; readonly scopes: readonly string[] } {
122
+ const refusal = refuseClient(ctx, 'the client did not authenticate with client_secret_basic');
123
+
124
+ if (
125
+ claimed === null ||
126
+ form.has('client_secret') ||
127
+ form.has('client_assertion') ||
128
+ form.has('client_assertion_type') ||
129
+ (form.has('client_id') && form.get('client_id') !== claimed.clientID)
130
+ ) {
131
+ return refusal;
132
+ }
133
+
134
+ const presented = createHash('sha256').update(claimed.secret).digest();
135
+ let isMatch = false;
136
+
137
+ // Every stored digest is compared, so the time taken does not say which one
138
+ // matched.
139
+ for (const entry of snapshot.secrets) {
140
+ const isEqual = timingSafeEqual(presented, entry.digest);
141
+
142
+ isMatch ||= isEqual && entry.clientID === claimed.clientID;
143
+ }
144
+
145
+ const client = snapshot.file.clients.find(
146
+ (candidate) => `service:${candidate.name}` === claimed.clientID,
147
+ );
148
+
149
+ return isMatch && client !== undefined ? client : refusal;
150
+ }
151
+
152
+ function refuseClient(ctx: RouteContext, description: string): Outcome {
153
+ return refuse(401, 'invalid_client', description, {
154
+ 'www-authenticate': `Basic realm="${ctx.origin}"`,
155
+ });
156
+ }
@@ -3,9 +3,9 @@ import type { RouteContext } from '../sign-in/route-context.ts';
3
3
 
4
4
  const METADATA_HEADERS = { 'cache-control': 'no-store' };
5
5
 
6
- // The metadata advertises only what the core's clients can use: public clients
7
- // with no client authentication, no introspection endpoint, and bearer tokens
8
- // alone, so nothing about DPoP.
6
+ // The metadata advertises only what the core's clients can use: public clients,
7
+ // client_secret_basic and client_credentials only while a service client holds
8
+ // a secret, no introspection endpoint, and no DPoP.
9
9
  export async function answerMetadataRequest(
10
10
  ctx: RouteContext,
11
11
  kind: 'authorization-server' | 'resource',
@@ -35,15 +35,27 @@ export async function answerMetadataRequest(
35
35
  );
36
36
  }
37
37
 
38
+ const hasSecrets = (ctx.services.findSnapshot()?.secrets.length ?? 0) > 0;
39
+ const advertisedGrants: unknown = advertised['grant_types_supported'];
40
+
41
+ const grantTypes = Array.isArray(advertisedGrants)
42
+ ? advertisedGrants.filter((grant): grant is string => typeof grant === 'string')
43
+ : [];
44
+
38
45
  // better-auth serves its endpoints at fixed paths, and an app may serve
39
46
  // them at others.
40
47
  return Response.json(
41
48
  {
42
49
  ...advertised,
50
+ ...(hasSecrets
51
+ ? { grant_types_supported: [...new Set([...grantTypes, 'client_credentials'])] }
52
+ : {}),
43
53
  authorization_endpoint: `${ctx.origin}${ctx.paths.browser.authorize}`,
44
54
  token_endpoint: `${ctx.origin}${ctx.paths.machine.token}`,
45
55
  revocation_endpoint: `${ctx.origin}${ctx.paths.machine.revoke}`,
46
- token_endpoint_auth_methods_supported: ['none'],
56
+ token_endpoint_auth_methods_supported: hasSecrets
57
+ ? ['none', 'client_secret_basic']
58
+ : ['none'],
47
59
  revocation_endpoint_auth_methods_supported: ['none'],
48
60
  },
49
61
  { headers: METADATA_HEADERS },
@@ -4,6 +4,7 @@ import type { GrantID, Requester } from '../types.ts';
4
4
  import { deriveTokenHash } from '../utils/derive-token-hash.ts';
5
5
  import { readBodyText } from '../utils/read-body-text.ts';
6
6
  import { MAX_FORM_BYTES } from '../utils/read-form.ts';
7
+ import { answerClientCredentialsRequest } from './answer-client-credentials-request.ts';
7
8
  import { buildBetterAuthRequest } from './build-better-auth-request.ts';
8
9
  import { buildOAuthError } from './build-oauth-error.ts';
9
10
  import { readErrorCode } from './read-error-code.ts';
@@ -18,11 +19,28 @@ export async function answerTokenRequest(
18
19
  const body = await readBodyText(request, MAX_FORM_BYTES);
19
20
 
20
21
  if (body === null) {
21
- return buildOAuthError(400, 'invalid_request', 'the request body is missing or too large');
22
+ const refused = buildOAuthError(
23
+ 400,
24
+ 'invalid_request',
25
+ 'the request body is missing or too large',
26
+ );
27
+
28
+ await recordTokenExchange(ctx, {
29
+ form: new URLSearchParams(),
30
+ response: refused,
31
+ path: new URL(request.url).pathname,
32
+ requester,
33
+ });
34
+
35
+ return refused;
22
36
  }
23
37
 
24
38
  const form = new URLSearchParams(body);
25
39
 
40
+ if (form.get('grant_type') === 'client_credentials') {
41
+ return answerClientCredentialsRequest(ctx, request, form, requester);
42
+ }
43
+
26
44
  const refreshing = await readRefreshToken(ctx, form);
27
45
 
28
46
  // A refresh token that its own client presents after the core replaced it
@@ -1,7 +1,12 @@
1
1
  // An OAuth error answer (RFC 6749 section 5.2).
2
- export function buildOAuthError(status: number, error: string, description: string): Response {
2
+ export function buildOAuthError(
3
+ status: number,
4
+ error: string,
5
+ description: string,
6
+ headers: Readonly<Record<string, string>> = {},
7
+ ): Response {
3
8
  return Response.json(
4
9
  { error, error_description: description },
5
- { status, headers: { 'cache-control': 'no-store' } },
10
+ { status, headers: { 'cache-control': 'no-store', ...headers } },
6
11
  );
7
12
  }
@@ -0,0 +1,14 @@
1
+ // The scopes a token request gets: every scope of the client when the request
2
+ // names none, otherwise the requested ones, which the client must all hold.
3
+ export function pickClientCredentialsScopes(
4
+ requested: string | null,
5
+ clientScopes: readonly string[],
6
+ ): readonly string[] | null {
7
+ const names = [...new Set((requested ?? '').split(/\s+/u).filter((name) => name !== ''))];
8
+
9
+ if (names.length === 0) {
10
+ return clientScopes;
11
+ }
12
+
13
+ return names.every((name) => clientScopes.includes(name)) ? names : null;
14
+ }
@@ -22,6 +22,7 @@ const TOKEN_EXCHANGE_ERRORS: ReadonlySet<string> = new Set([
22
22
  'unsupported_grant_type',
23
23
  'invalid_scope',
24
24
  'invalid_target',
25
+ 'temporarily_unavailable',
25
26
  ]);
26
27
 
27
28
  // The event holds an error code from the fixed list, and the client's id and
package/src/types.ts CHANGED
@@ -90,10 +90,16 @@ export interface MCPAuthAdminOptions<Scope extends string> {
90
90
  readonly onGrantRevoked: (grantID: GrantID) => void;
91
91
  }
92
92
 
93
+ // A client holds static tokens, secret digests, or both.
93
94
  export interface ServiceClient<Scope extends string> {
95
+ // The client ID is `service:${name}`.
94
96
  readonly name: string;
95
97
  readonly scopes: readonly Scope[];
96
98
  readonly tokens: readonly string[];
99
+
100
+ // sha256 hex digests of the client's secrets. Two entries allow a rotation
101
+ // with no gap.
102
+ readonly secretDigests?: readonly string[];
97
103
  }
98
104
 
99
105
  export interface ServiceTokenFile<Scope extends string> {
@@ -223,6 +229,12 @@ export interface MCPAuth<Scope extends string, Limits = null> extends MCPAuthAdm
223
229
 
224
230
  // The scopes a client holds now, or null when it holds none.
225
231
  readonly findClientScopes: (clientID: string) => Promise<readonly Scope[] | null>;
232
+
233
+ // Swaps the service clients that the token route and `verify` read. Throws,
234
+ // and keeps the old ones, when `serviceTokens` was not passed or the file
235
+ // names another resource.
236
+ // oxlint-disable-next-line typescript/method-signature-style -- a method is bivariant, so an MCPAuth of known scopes still passes where any scope goes
237
+ replaceServiceTokens(file: ServiceTokenFile<Scope>): void;
226
238
  }
227
239
 
228
240
  export interface ConsentRequest {