@zgeoff/mcp-auth 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +76 -2
- package/dist/admin/build-admin.d.ts +4 -0
- package/dist/admin/build-client-admin.d.ts +4 -0
- package/dist/admin/build-grant-admin.d.ts +3 -0
- package/dist/admin/build-passkey-admin.d.ts +3 -0
- package/dist/admin/check-redirect-uris.d.ts +1 -0
- package/dist/admin/create-enrollment-token.d.ts +2 -0
- package/dist/admin/read-client-name.d.ts +1 -0
- package/dist/admin/read-sign-in-grants.d.ts +3 -0
- package/dist/admin/remove-expired.d.ts +2 -0
- package/dist/admin/to-client-view.d.ts +3 -0
- package/dist/default-paths.d.ts +18 -0
- package/dist/elysia/create-mcp-http-app.d.ts +17 -0
- package/dist/elysia/find-bearer-token.d.ts +1 -0
- package/dist/elysia/index.d.ts +2 -0
- package/dist/elysia/is-beside-prefix.d.ts +1 -0
- package/dist/grants/collect-granted-scopes.d.ts +7 -0
- package/dist/grants/read-access-payload.d.ts +9 -0
- package/dist/grants/read-client-scopes.d.ts +2 -0
- package/dist/grants/verify-oauth-access.d.ts +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/mcp-auth-error.d.ts +5 -0
- package/dist/open-mcp-auth-admin.d.ts +2 -0
- package/dist/open-mcp-auth.d.ts +2 -0
- package/dist/passkeys/answer-enroll-request.d.ts +3 -0
- package/dist/passkeys/create-enrollment-state.d.ts +6 -0
- package/dist/passkeys/create-passkey.d.ts +10 -0
- package/dist/passkeys/passkey-script.d.ts +4 -0
- package/dist/passkeys/read-enrollment-token.d.ts +2 -0
- package/dist/passkeys/read-passkey-rows.d.ts +13 -0
- package/dist/passkeys/render-enroll-page.d.ts +11 -0
- package/dist/passkeys/render-login-page.d.ts +11 -0
- package/dist/passkeys/update-passkey-use.d.ts +9 -0
- package/dist/passkeys/verify-passkey-assertion.d.ts +10 -0
- package/dist/passkeys/verify-passkey-registration.d.ts +15 -0
- package/dist/passkeys/verify-session-passkey.d.ts +8 -0
- package/dist/routes/build-routes.d.ts +3 -0
- package/dist/routes/with-form-origin.d.ts +4 -0
- package/dist/service-tokens/build-service-token-verifier.d.ts +13 -0
- package/dist/service-tokens/parse-service-token-file.d.ts +7 -0
- package/dist/sign-in/answer-authorize-request.d.ts +3 -0
- package/dist/sign-in/answer-consent-request.d.ts +3 -0
- package/dist/sign-in/answer-login-request.d.ts +3 -0
- package/dist/sign-in/build-consent-binding.d.ts +1 -0
- package/dist/sign-in/create-sign-in-state.d.ts +43 -0
- package/dist/sign-in/pick-consent-choice.d.ts +8 -0
- package/dist/sign-in/pick-consent-outcome.d.ts +4 -0
- package/dist/sign-in/read-session-id.d.ts +2 -0
- package/dist/sign-in/read-stored-client-name.d.ts +3 -0
- package/dist/sign-in/read-url-field.d.ts +1 -0
- package/dist/sign-in/render-consent-page.d.ts +11 -0
- package/dist/sign-in/route-context.d.ts +17 -0
- package/dist/sign-in/verify-oauth-query.d.ts +1 -0
- package/dist/store/check-cascade-keys.d.ts +2 -0
- package/dist/store/check-foreign-keys.d.ts +2 -0
- package/dist/store/check-table-names.d.ts +2 -0
- package/dist/store/check-user-columns.d.ts +2 -0
- package/dist/store/create-auth-server.d.ts +103 -0
- package/dist/store/create-grant-plugin.d.ts +28 -0
- package/dist/store/create-owned-tables.d.ts +3 -0
- package/dist/store/open-store.d.ts +15 -0
- package/dist/store/read-table-columns.d.ts +2 -0
- package/dist/store/remove-grant-rows.d.ts +3 -0
- package/dist/store/store-schema.d.ts +63 -0
- package/dist/test-utils/authorize-test-client.d.ts +12 -0
- package/dist/test-utils/build-form-request.d.ts +1 -0
- package/dist/test-utils/build-seeder.d.ts +13 -0
- package/dist/test-utils/build-stub-authenticator.d.ts +49 -0
- package/dist/test-utils/build-stub-clock.d.ts +5 -0
- package/dist/test-utils/build-test-requester.d.ts +2 -0
- package/dist/test-utils/create-test-database.d.ts +2 -0
- package/dist/test-utils/hook-sqlite-statements.d.ts +2 -0
- package/dist/test-utils/index.d.ts +12 -0
- package/dist/test-utils/open-test-auth.d.ts +21 -0
- package/dist/test-utils/parse-passkey-page.d.ts +21 -0
- package/dist/test-utils/read-json-record.d.ts +5 -0
- package/dist/test-utils/run-sign-in-to-consent.d.ts +13 -0
- package/dist/test-utils/seed-client.d.ts +7 -0
- package/dist/test-utils/seed-enrollment-token.d.ts +2 -0
- package/dist/test-utils/seed-passkey.d.ts +7 -0
- package/dist/tokens/answer-error-request.d.ts +2 -0
- package/dist/tokens/answer-metadata-request.d.ts +2 -0
- package/dist/tokens/answer-revoke-request.d.ts +2 -0
- package/dist/tokens/answer-token-request.d.ts +3 -0
- package/dist/tokens/build-better-auth-request.d.ts +6 -0
- package/dist/tokens/build-oauth-error.d.ts +1 -0
- package/dist/tokens/read-error-code.d.ts +1 -0
- package/dist/tokens/read-error-description.d.ts +1 -0
- package/dist/tokens/record-token-exchange.d.ts +10 -0
- package/dist/tokens/remove-token-sessions.d.ts +2 -0
- package/dist/types.d.ts +185 -0
- package/dist/utils/build-page-response.d.ts +5 -0
- package/dist/utils/derive-token-hash.d.ts +1 -0
- package/dist/utils/is-allowed-redirect-uri.d.ts +1 -0
- package/dist/utils/is-loopback-host.d.ts +1 -0
- package/dist/utils/normalize-client-name.d.ts +1 -0
- package/dist/utils/parse-approved-by.d.ts +2 -0
- package/dist/utils/parse-json-strings.d.ts +1 -0
- package/dist/utils/read-body-text.d.ts +1 -0
- package/dist/utils/read-form.d.ts +2 -0
- package/dist/utils/to-html-text.d.ts +1 -0
- package/dist/utils/to-script-json.d.ts +1 -0
- package/package.json +73 -4
- package/src/admin/build-admin.ts +22 -0
- package/src/admin/build-client-admin.ts +112 -0
- package/src/admin/build-grant-admin.ts +62 -0
- package/src/admin/build-passkey-admin.ts +53 -0
- package/src/admin/check-redirect-uris.ts +17 -0
- package/src/admin/create-enrollment-token.ts +18 -0
- package/src/admin/read-client-name.ts +13 -0
- package/src/admin/read-sign-in-grants.ts +22 -0
- package/src/admin/remove-expired.ts +47 -0
- package/src/admin/to-client-view.ts +12 -0
- package/src/default-paths.ts +21 -0
- package/src/elysia/create-mcp-http-app.ts +218 -0
- package/src/elysia/find-bearer-token.ts +6 -0
- package/src/elysia/index.ts +2 -0
- package/src/elysia/is-beside-prefix.ts +7 -0
- package/src/grants/collect-granted-scopes.ts +19 -0
- package/src/grants/read-access-payload.ts +37 -0
- package/src/grants/read-client-scopes.ts +36 -0
- package/src/grants/verify-oauth-access.ts +113 -0
- package/src/index.ts +7 -0
- package/src/mcp-auth-error.ts +17 -0
- package/src/open-mcp-auth-admin.ts +14 -0
- package/src/open-mcp-auth.ts +89 -0
- package/src/passkeys/answer-enroll-request.ts +179 -0
- package/src/passkeys/create-enrollment-state.ts +54 -0
- package/src/passkeys/create-passkey.ts +39 -0
- package/src/passkeys/passkey-script.ts +48 -0
- package/src/passkeys/read-enrollment-token.ts +21 -0
- package/src/passkeys/read-passkey-rows.ts +30 -0
- package/src/passkeys/render-enroll-page.ts +58 -0
- package/src/passkeys/render-login-page.ts +59 -0
- package/src/passkeys/update-passkey-use.ts +24 -0
- package/src/passkeys/verify-passkey-assertion.ts +120 -0
- package/src/passkeys/verify-passkey-registration.ts +116 -0
- package/src/passkeys/verify-session-passkey.ts +42 -0
- package/src/routes/build-routes.ts +31 -0
- package/src/routes/with-form-origin.ts +18 -0
- package/src/service-tokens/build-service-token-verifier.ts +56 -0
- package/src/service-tokens/parse-service-token-file.ts +104 -0
- package/src/sign-in/answer-authorize-request.ts +133 -0
- package/src/sign-in/answer-consent-request.ts +220 -0
- package/src/sign-in/answer-login-request.ts +243 -0
- package/src/sign-in/build-consent-binding.ts +11 -0
- package/src/sign-in/create-sign-in-state.ts +229 -0
- package/src/sign-in/pick-consent-choice.ts +27 -0
- package/src/sign-in/pick-consent-outcome.ts +14 -0
- package/src/sign-in/read-session-id.ts +11 -0
- package/src/sign-in/read-stored-client-name.ts +15 -0
- package/src/sign-in/read-url-field.ts +12 -0
- package/src/sign-in/render-consent-page.ts +57 -0
- package/src/sign-in/route-context.ts +25 -0
- package/src/sign-in/verify-oauth-query.ts +39 -0
- package/src/store/check-cascade-keys.ts +36 -0
- package/src/store/check-foreign-keys.ts +20 -0
- package/src/store/check-table-names.ts +13 -0
- package/src/store/check-user-columns.ts +22 -0
- package/src/store/create-auth-server.ts +97 -0
- package/src/store/create-grant-plugin.ts +68 -0
- package/src/store/create-owned-tables.ts +45 -0
- package/src/store/open-store.ts +72 -0
- package/src/store/read-table-columns.ts +12 -0
- package/src/store/remove-grant-rows.ts +27 -0
- package/src/store/store-schema.ts +61 -0
- package/src/test-utils/authorize-test-client.ts +93 -0
- package/src/test-utils/build-form-request.ts +12 -0
- package/src/test-utils/build-seeder.ts +19 -0
- package/src/test-utils/build-stub-authenticator.ts +244 -0
- package/src/test-utils/build-stub-clock.ts +21 -0
- package/src/test-utils/build-test-requester.ts +5 -0
- package/src/test-utils/create-test-database.ts +7 -0
- package/src/test-utils/hook-sqlite-statements.ts +17 -0
- package/src/test-utils/index.ts +12 -0
- package/src/test-utils/open-test-auth.ts +72 -0
- package/src/test-utils/parse-passkey-page.ts +25 -0
- package/src/test-utils/read-json-record.ts +15 -0
- package/src/test-utils/run-sign-in-to-consent.ts +100 -0
- package/src/test-utils/seed-client.ts +16 -0
- package/src/test-utils/seed-enrollment-token.ts +5 -0
- package/src/test-utils/seed-passkey.ts +51 -0
- package/src/tokens/answer-error-request.ts +26 -0
- package/src/tokens/answer-metadata-request.ts +51 -0
- package/src/tokens/answer-revoke-request.ts +47 -0
- package/src/tokens/answer-token-request.ts +133 -0
- package/src/tokens/build-better-auth-request.ts +23 -0
- package/src/tokens/build-oauth-error.ts +7 -0
- package/src/tokens/read-error-code.ts +12 -0
- package/src/tokens/read-error-description.ts +11 -0
- package/src/tokens/record-token-exchange.ts +73 -0
- package/src/tokens/remove-token-sessions.ts +32 -0
- package/src/types.ts +247 -0
- package/src/utils/build-page-response.ts +24 -0
- package/src/utils/derive-token-hash.ts +5 -0
- package/src/utils/is-allowed-redirect-uri.ts +17 -0
- package/src/utils/is-loopback-host.ts +8 -0
- package/src/utils/normalize-client-name.ts +20 -0
- package/src/utils/parse-approved-by.ts +9 -0
- package/src/utils/parse-json-strings.ts +13 -0
- package/src/utils/read-body-text.ts +23 -0
- package/src/utils/read-form.ts +16 -0
- package/src/utils/to-html-text.ts +8 -0
- package/src/utils/to-script-json.ts +6 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { sql } from 'kysely';
|
|
2
|
+
import type { Store } from '../store/open-store.ts';
|
|
3
|
+
import { removeGrantRows } from '../store/remove-grant-rows.ts';
|
|
4
|
+
|
|
5
|
+
// A grant row with no live refresh token that is older than this is a sign-in
|
|
6
|
+
// that never finished, or a grant whose client stopped refreshing.
|
|
7
|
+
const UNUSED_GRANT_MS = 60 * 60_000;
|
|
8
|
+
|
|
9
|
+
export async function removeExpired(store: Store): Promise<void> {
|
|
10
|
+
const now = store.options.clock.now();
|
|
11
|
+
|
|
12
|
+
const at = new Date(now).toISOString();
|
|
13
|
+
|
|
14
|
+
const stale = await store.db
|
|
15
|
+
.selectFrom('user')
|
|
16
|
+
.select('user.id')
|
|
17
|
+
.where('user.createdAt', '<', new Date(now - UNUSED_GRANT_MS).toISOString())
|
|
18
|
+
.where((eb) =>
|
|
19
|
+
eb.not(
|
|
20
|
+
eb.exists(
|
|
21
|
+
eb
|
|
22
|
+
.selectFrom('oauthRefreshToken')
|
|
23
|
+
.select('oauthRefreshToken.id')
|
|
24
|
+
.whereRef('oauthRefreshToken.userId', '=', 'user.id')
|
|
25
|
+
.where('oauthRefreshToken.revoked', 'is', null)
|
|
26
|
+
.where('oauthRefreshToken.expiresAt', '>', at),
|
|
27
|
+
),
|
|
28
|
+
),
|
|
29
|
+
)
|
|
30
|
+
.execute();
|
|
31
|
+
|
|
32
|
+
await removeGrantRows(
|
|
33
|
+
store,
|
|
34
|
+
stale.map((row) => row.id),
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
// A rotated refresh token that has not expired stays, so a replay of it
|
|
38
|
+
// still ends its grant.
|
|
39
|
+
await store.db.deleteFrom('oauthRefreshToken').where('expiresAt', '<', at).execute();
|
|
40
|
+
await store.db.deleteFrom('oauthAccessToken').where('expiresAt', '<', at).execute();
|
|
41
|
+
await store.db.deleteFrom('session').where('expiresAt', '<', at).execute();
|
|
42
|
+
await store.db.deleteFrom('verification').where('expiresAt', '<', at).execute();
|
|
43
|
+
|
|
44
|
+
await sql`delete from ${sql.table(store.options.tables.enrollmentToken)} where expires_at < ${at}`.execute(
|
|
45
|
+
store.db,
|
|
46
|
+
);
|
|
47
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { StoreSchema } from '../store/store-schema.ts';
|
|
2
|
+
import type { ClientView } from '../types.ts';
|
|
3
|
+
import { parseJSONStrings } from '../utils/parse-json-strings.ts';
|
|
4
|
+
|
|
5
|
+
export function toClientView(row: StoreSchema['oauthClient']): ClientView {
|
|
6
|
+
return {
|
|
7
|
+
clientID: row.clientId,
|
|
8
|
+
name: row.name ?? row.clientId,
|
|
9
|
+
redirectURIs: parseJSONStrings(row.redirectUris) ?? [],
|
|
10
|
+
createdAt: row.createdAt ?? '',
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { MCPAuthPaths } from './types.ts';
|
|
2
|
+
|
|
3
|
+
// An app that serves other paths passes its own object of this shape.
|
|
4
|
+
export const DEFAULT_PATHS = {
|
|
5
|
+
browser: {
|
|
6
|
+
authorize: '/oauth2/authorize',
|
|
7
|
+
login: '/login',
|
|
8
|
+
enroll: '/enroll',
|
|
9
|
+
consent: '/consent',
|
|
10
|
+
error: '/error',
|
|
11
|
+
},
|
|
12
|
+
machine: {
|
|
13
|
+
mcp: '/mcp',
|
|
14
|
+
root: '/',
|
|
15
|
+
token: '/oauth2/token',
|
|
16
|
+
revoke: '/oauth2/revoke',
|
|
17
|
+
authorizationServerMetadata: '/.well-known/oauth-authorization-server',
|
|
18
|
+
resourceMetadata: '/.well-known/oauth-protected-resource',
|
|
19
|
+
mcpResourceMetadata: '/.well-known/oauth-protected-resource/mcp',
|
|
20
|
+
},
|
|
21
|
+
} as const satisfies MCPAuthPaths;
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { Elysia } from 'elysia';
|
|
2
|
+
import type { Access, MCPAuth, MCPAuthRouteName, Requester, SecuritySink } from '../types.ts';
|
|
3
|
+
import { findBearerToken } from './find-bearer-token.ts';
|
|
4
|
+
import { isBesidePrefix } from './is-beside-prefix.ts';
|
|
5
|
+
|
|
6
|
+
export interface MCPHTTPAppOptions<Scope extends string, Limits> {
|
|
7
|
+
readonly auth: MCPAuth<Scope, Limits>;
|
|
8
|
+
|
|
9
|
+
// The Host header values the app answers to.
|
|
10
|
+
readonly hosts: ReadonlySet<string>;
|
|
11
|
+
|
|
12
|
+
// The Origin header values a POST may carry.
|
|
13
|
+
readonly origins: ReadonlySet<string>;
|
|
14
|
+
readonly readRequester: (request: Request) => Requester;
|
|
15
|
+
readonly security: SecuritySink;
|
|
16
|
+
readonly mcp: {
|
|
17
|
+
readonly fetch: (request: Request, access: Access<Scope, Limits>) => Promise<Response>;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Paths under this prefix belong to the app. The adapter serves none of
|
|
21
|
+
// them, and checks neither their Host nor their Origin header.
|
|
22
|
+
readonly besidePrefix: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface RouteContext {
|
|
26
|
+
readonly request: Request;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type RouteMethod = 'get' | 'post';
|
|
30
|
+
|
|
31
|
+
interface RouteSpec {
|
|
32
|
+
readonly name: MCPAuthRouteName;
|
|
33
|
+
readonly path: (auth: MCPAuth<string, unknown>) => string;
|
|
34
|
+
readonly methods: readonly RouteMethod[];
|
|
35
|
+
|
|
36
|
+
// A form page refuses a POST that carries no Origin header.
|
|
37
|
+
readonly isPage: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const ROUTES: readonly RouteSpec[] = [
|
|
41
|
+
{
|
|
42
|
+
name: 'authorize',
|
|
43
|
+
path: (auth) => auth.paths.browser.authorize,
|
|
44
|
+
methods: ['get'],
|
|
45
|
+
isPage: false,
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: 'login',
|
|
49
|
+
path: (auth) => auth.paths.browser.login,
|
|
50
|
+
methods: ['get', 'post'],
|
|
51
|
+
isPage: true,
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: 'enroll',
|
|
55
|
+
path: (auth) => auth.paths.browser.enroll,
|
|
56
|
+
methods: ['get', 'post'],
|
|
57
|
+
isPage: true,
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
name: 'consent',
|
|
61
|
+
path: (auth) => auth.paths.browser.consent,
|
|
62
|
+
methods: ['get', 'post'],
|
|
63
|
+
isPage: true,
|
|
64
|
+
},
|
|
65
|
+
{ name: 'error', path: (auth) => auth.paths.browser.error, methods: ['get'], isPage: false },
|
|
66
|
+
{ name: 'token', path: (auth) => auth.paths.machine.token, methods: ['post'], isPage: false },
|
|
67
|
+
{ name: 'revoke', path: (auth) => auth.paths.machine.revoke, methods: ['post'], isPage: false },
|
|
68
|
+
{
|
|
69
|
+
name: 'authorizationServerMetadata',
|
|
70
|
+
path: (auth) => auth.paths.machine.authorizationServerMetadata,
|
|
71
|
+
methods: ['get'],
|
|
72
|
+
isPage: false,
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: 'resourceMetadata',
|
|
76
|
+
path: (auth) => auth.paths.machine.resourceMetadata,
|
|
77
|
+
methods: ['get'],
|
|
78
|
+
isPage: false,
|
|
79
|
+
},
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
export function createMCPHTTPApp<Scope extends string, Limits>(
|
|
83
|
+
options: MCPHTTPAppOptions<Scope, Limits>,
|
|
84
|
+
) {
|
|
85
|
+
const auth = options.auth;
|
|
86
|
+
|
|
87
|
+
const app = new Elysia();
|
|
88
|
+
|
|
89
|
+
const recordRefusal = (
|
|
90
|
+
request: Request,
|
|
91
|
+
kind: 'bad_host' | 'bad_origin',
|
|
92
|
+
reason: string,
|
|
93
|
+
): void => {
|
|
94
|
+
options.security.record({
|
|
95
|
+
kind,
|
|
96
|
+
outcome: 'rejected',
|
|
97
|
+
reason,
|
|
98
|
+
path: new URL(request.url).pathname,
|
|
99
|
+
requester: options.readRequester(request),
|
|
100
|
+
});
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const isForeignOrigin = (request: Request, isPage: boolean): boolean => {
|
|
104
|
+
if (request.method !== 'POST') {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const origin = request.headers.get('origin');
|
|
109
|
+
|
|
110
|
+
return origin === null ? isPage : !options.origins.has(origin);
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const guard = (request: Request, isPage: boolean): Response | null => {
|
|
114
|
+
if (isForeignOrigin(request, isPage)) {
|
|
115
|
+
recordRefusal(request, 'bad_origin', 'origin_not_allowed');
|
|
116
|
+
|
|
117
|
+
return new Response(null, { status: 403 });
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return null;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
app.onRequest((context: RouteContext): Response | undefined => {
|
|
124
|
+
const path = new URL(context.request.url).pathname;
|
|
125
|
+
|
|
126
|
+
const host = context.request.headers.get('host');
|
|
127
|
+
|
|
128
|
+
const isRefused =
|
|
129
|
+
!isBesidePrefix(path, options.besidePrefix) && (host === null || !options.hosts.has(host));
|
|
130
|
+
|
|
131
|
+
if (!isRefused) {
|
|
132
|
+
return undefined;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
recordRefusal(context.request, 'bad_host', 'host_not_allowed');
|
|
136
|
+
|
|
137
|
+
return new Response(null, { status: 403 });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
for (const spec of ROUTES) {
|
|
141
|
+
const path = spec.path(auth);
|
|
142
|
+
|
|
143
|
+
if (isBesidePrefix(path, options.besidePrefix)) {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const answer = (context: RouteContext): Response | Promise<Response> =>
|
|
148
|
+
guard(context.request, spec.isPage) ??
|
|
149
|
+
auth.routes[spec.name](context.request, options.readRequester(context.request));
|
|
150
|
+
|
|
151
|
+
if (spec.methods.includes('get')) {
|
|
152
|
+
app.get(path, answer);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (spec.methods.includes('post')) {
|
|
156
|
+
app.post(path, answer);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const metadataURL = `${auth.issuer}${auth.paths.machine.mcpResourceMetadata}`;
|
|
161
|
+
|
|
162
|
+
const answerMCP = async (request: Request): Promise<Response> => {
|
|
163
|
+
const refused = guard(request, false);
|
|
164
|
+
|
|
165
|
+
if (refused !== null) {
|
|
166
|
+
return refused;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const authorization = request.headers.get('authorization');
|
|
170
|
+
const token = findBearerToken(authorization);
|
|
171
|
+
|
|
172
|
+
if (token === null) {
|
|
173
|
+
const reason = authorization === null ? 'missing' : 'malformed';
|
|
174
|
+
|
|
175
|
+
recordBearerRefusal(request, reason);
|
|
176
|
+
|
|
177
|
+
return buildChallenge(`Bearer resource_metadata="${metadataURL}"`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const access = await auth.verify(token);
|
|
181
|
+
|
|
182
|
+
if (access === null) {
|
|
183
|
+
recordBearerRefusal(request, 'invalid_token');
|
|
184
|
+
|
|
185
|
+
return buildChallenge(`Bearer error="invalid_token", resource_metadata="${metadataURL}"`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
return options.mcp.fetch(request, access);
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const recordBearerRefusal = (request: Request, reason: string): void => {
|
|
192
|
+
options.security.record({
|
|
193
|
+
kind: 'bearer',
|
|
194
|
+
outcome: 'rejected',
|
|
195
|
+
reason,
|
|
196
|
+
path: new URL(request.url).pathname,
|
|
197
|
+
requester: options.readRequester(request),
|
|
198
|
+
});
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
for (const path of [auth.paths.machine.mcp, auth.paths.machine.root]) {
|
|
202
|
+
if (!isBesidePrefix(path, options.besidePrefix)) {
|
|
203
|
+
app.all(path, (context: RouteContext) => answerMCP(context.request));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (!isBesidePrefix(auth.paths.machine.mcpResourceMetadata, options.besidePrefix)) {
|
|
208
|
+
app.get(auth.paths.machine.mcpResourceMetadata, (context: RouteContext) =>
|
|
209
|
+
auth.routes.resourceMetadata(context.request, options.readRequester(context.request)),
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return app;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function buildChallenge(challenge: string): Response {
|
|
217
|
+
return new Response(null, { status: 401, headers: { 'www-authenticate': challenge } });
|
|
218
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
const BEARER_PATTERN = /^Bearer (?<token>\S+)$/iu;
|
|
2
|
+
|
|
3
|
+
// Null when the header is missing or holds no bearer token.
|
|
4
|
+
export function findBearerToken(authorization: string | null): string | null {
|
|
5
|
+
return BEARER_PATTERN.exec(authorization ?? '')?.groups?.['token'] ?? null;
|
|
6
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// A path is beside the prefix when it is the prefix or lies under it, so
|
|
2
|
+
// `/api` covers `/api` and `/api/x` but not `/apiary`.
|
|
3
|
+
export function isBesidePrefix(path: string, prefix: string): boolean {
|
|
4
|
+
const base = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
5
|
+
|
|
6
|
+
return path === base || path.startsWith(`${base}/`);
|
|
7
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The scopes of the server that the grant holds, that the token names, and
|
|
2
|
+
// that the app's check allows when it narrows them.
|
|
3
|
+
interface HeldScopes {
|
|
4
|
+
readonly grant: readonly string[];
|
|
5
|
+
readonly token: readonly string[];
|
|
6
|
+
readonly allowed: readonly string[] | null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function collectGrantedScopes<Scope extends string>(
|
|
10
|
+
known: readonly Scope[],
|
|
11
|
+
held: HeldScopes,
|
|
12
|
+
): Scope[] {
|
|
13
|
+
return known.filter(
|
|
14
|
+
(scope) =>
|
|
15
|
+
held.grant.includes(scope) &&
|
|
16
|
+
held.token.includes(scope) &&
|
|
17
|
+
(held.allowed === null || held.allowed.includes(scope)),
|
|
18
|
+
);
|
|
19
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { isRecord, toTagged } from '@zgeoff/std';
|
|
2
|
+
import type { GrantID, OAuthClientID } from '../types.ts';
|
|
3
|
+
|
|
4
|
+
interface AccessPayload {
|
|
5
|
+
readonly grantID: GrantID;
|
|
6
|
+
readonly clientID: OAuthClientID;
|
|
7
|
+
readonly audiences: readonly string[];
|
|
8
|
+
readonly scopes: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// A payload bound to a key (`cnf`) gives null: no route checks a proof of the
|
|
12
|
+
// key, and a stolen bound token must not pass.
|
|
13
|
+
export function readAccessPayload(payload: unknown): AccessPayload | null {
|
|
14
|
+
if (!isRecord(payload)) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (payload['cnf'] !== undefined && payload['cnf'] !== null) {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const grantID = payload['sub'];
|
|
23
|
+
const clientID = payload['client_id'];
|
|
24
|
+
const scope = payload['scope'];
|
|
25
|
+
const audience: unknown = payload['aud'];
|
|
26
|
+
|
|
27
|
+
if (typeof grantID !== 'string' || typeof clientID !== 'string' || clientID === '') {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return {
|
|
32
|
+
grantID: toTagged<GrantID>(grantID),
|
|
33
|
+
clientID: toTagged<OAuthClientID>(clientID),
|
|
34
|
+
audiences: [audience].flat().filter((item): item is string => typeof item === 'string'),
|
|
35
|
+
scopes: typeof scope === 'string' ? scope.split(' ') : [],
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { toTagged } from '@zgeoff/std';
|
|
2
|
+
import type { Store } from '../store/open-store.ts';
|
|
3
|
+
import type { OAuthClientID } from '../types.ts';
|
|
4
|
+
import { parseJSONStrings } from '../utils/parse-json-strings.ts';
|
|
5
|
+
|
|
6
|
+
// The scopes of the server that any live grant of the client holds, or null
|
|
7
|
+
// when the client holds none.
|
|
8
|
+
export async function readClientScopes<Scope extends string>(
|
|
9
|
+
store: Store,
|
|
10
|
+
known: readonly Scope[],
|
|
11
|
+
clientID: string,
|
|
12
|
+
): Promise<readonly Scope[] | null> {
|
|
13
|
+
const at = new Date(store.options.clock.now()).toISOString();
|
|
14
|
+
|
|
15
|
+
const rows = await store.db
|
|
16
|
+
.selectFrom('user')
|
|
17
|
+
.select('user.scopes')
|
|
18
|
+
.where('user.clientId', '=', toTagged<OAuthClientID>(clientID))
|
|
19
|
+
.where((eb) =>
|
|
20
|
+
eb.exists(
|
|
21
|
+
eb
|
|
22
|
+
.selectFrom('oauthRefreshToken')
|
|
23
|
+
.select('oauthRefreshToken.id')
|
|
24
|
+
.whereRef('oauthRefreshToken.userId', '=', 'user.id')
|
|
25
|
+
.where('oauthRefreshToken.revoked', 'is', null)
|
|
26
|
+
.where('oauthRefreshToken.expiresAt', '>', at),
|
|
27
|
+
),
|
|
28
|
+
)
|
|
29
|
+
.execute();
|
|
30
|
+
|
|
31
|
+
const held = new Set(rows.flatMap((row) => parseJSONStrings(row.scopes ?? '[]') ?? []));
|
|
32
|
+
|
|
33
|
+
const scopes = known.filter((scope) => held.has(scope));
|
|
34
|
+
|
|
35
|
+
return scopes.length === 0 ? null : scopes;
|
|
36
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { isAPIError } from 'better-auth/api';
|
|
2
|
+
import { readStoredClientName } from '../sign-in/read-stored-client-name.ts';
|
|
3
|
+
import type { Store } from '../store/open-store.ts';
|
|
4
|
+
import { removeGrantRows } from '../store/remove-grant-rows.ts';
|
|
5
|
+
import type { Access, GrantLimits } from '../types.ts';
|
|
6
|
+
import { parseApprovedBy } from '../utils/parse-approved-by.ts';
|
|
7
|
+
import { parseJSONStrings } from '../utils/parse-json-strings.ts';
|
|
8
|
+
import { collectGrantedScopes } from './collect-granted-scopes.ts';
|
|
9
|
+
import { readAccessPayload } from './read-access-payload.ts';
|
|
10
|
+
|
|
11
|
+
// verify stamps the grant's last use at most this often.
|
|
12
|
+
const TOUCH_MS = 60_000;
|
|
13
|
+
|
|
14
|
+
interface OAuthVerification<Scope extends string, Limits> {
|
|
15
|
+
readonly store: Store;
|
|
16
|
+
readonly resource: string;
|
|
17
|
+
readonly scopes: readonly Scope[];
|
|
18
|
+
readonly grantLimits: GrantLimits<Limits> | null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type OAuthAccess<Scope extends string, Limits> = Extract<Access<Scope, Limits>, { kind: 'oauth' }>;
|
|
22
|
+
|
|
23
|
+
// An unknown, expired or revoked token, one bound to another resource or to a
|
|
24
|
+
// key, and one whose grant the app's limits end, all read as null.
|
|
25
|
+
export async function verifyOAuthAccess<Scope extends string, Limits>(
|
|
26
|
+
deps: OAuthVerification<Scope, Limits>,
|
|
27
|
+
bearer: string,
|
|
28
|
+
): Promise<OAuthAccess<Scope, Limits> | null> {
|
|
29
|
+
let payload: unknown;
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
payload = await deps.store.auth.api.verifyAccessToken({ body: { token: bearer } });
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (isAPIError(error)) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const access = readAccessPayload(payload);
|
|
42
|
+
|
|
43
|
+
if (access === null || !access.audiences.includes(deps.resource)) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const grant = await deps.store.db
|
|
48
|
+
.selectFrom('user')
|
|
49
|
+
.selectAll()
|
|
50
|
+
.where('id', '=', access.grantID)
|
|
51
|
+
.executeTakeFirst();
|
|
52
|
+
|
|
53
|
+
const approvedBy = grant === undefined ? null : parseApprovedBy(grant.approvedBy);
|
|
54
|
+
|
|
55
|
+
if (grant === undefined || approvedBy === null) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const held = parseJSONStrings(grant.scopes ?? '[]') ?? [];
|
|
60
|
+
const createdAt = Date.parse(grant.createdAt);
|
|
61
|
+
const lastUsedAt = grant.lastUsedAt === null ? null : Date.parse(grant.lastUsedAt);
|
|
62
|
+
let limits: Limits | null = null;
|
|
63
|
+
let allowed: readonly string[] | null = null;
|
|
64
|
+
|
|
65
|
+
if (deps.grantLimits !== null) {
|
|
66
|
+
const stored: unknown = grant.limits === null ? null : JSON.parse(grant.limits);
|
|
67
|
+
|
|
68
|
+
limits = deps.grantLimits.parseStored(stored);
|
|
69
|
+
|
|
70
|
+
if (limits === null) {
|
|
71
|
+
await removeGrantRows(deps.store, [grant.id]);
|
|
72
|
+
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const check = await deps.grantLimits.check({
|
|
77
|
+
grantID: grant.id,
|
|
78
|
+
clientID: grant.clientId,
|
|
79
|
+
scopes: held,
|
|
80
|
+
approvedBy,
|
|
81
|
+
limits,
|
|
82
|
+
createdAt,
|
|
83
|
+
lastUsedAt,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
if (check.kind === 'revoke') {
|
|
87
|
+
await removeGrantRows(deps.store, [grant.id]);
|
|
88
|
+
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
allowed = check.scopes;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const now = deps.store.options.clock.now();
|
|
96
|
+
|
|
97
|
+
if (lastUsedAt === null || now - lastUsedAt >= TOUCH_MS) {
|
|
98
|
+
await deps.store.db
|
|
99
|
+
.updateTable('user')
|
|
100
|
+
.set({ lastUsedAt: new Date(now).toISOString() })
|
|
101
|
+
.where('id', '=', grant.id)
|
|
102
|
+
.execute();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
kind: 'oauth',
|
|
107
|
+
grantID: grant.id,
|
|
108
|
+
clientID: access.clientID,
|
|
109
|
+
clientName: await readStoredClientName(deps.store, access.clientID),
|
|
110
|
+
scopes: collectGrantedScopes(deps.scopes, { grant: held, token: access.scopes, allowed }),
|
|
111
|
+
limits,
|
|
112
|
+
};
|
|
113
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { DEFAULT_PATHS } from './default-paths.ts';
|
|
2
|
+
export { MCPAuthError } from './mcp-auth-error.ts';
|
|
3
|
+
export type { MCPAuthErrorCode } from './mcp-auth-error.ts';
|
|
4
|
+
export { openMCPAuth } from './open-mcp-auth.ts';
|
|
5
|
+
export { openMCPAuthAdmin } from './open-mcp-auth-admin.ts';
|
|
6
|
+
export { parseServiceTokenFile } from './service-tokens/parse-service-token-file.ts';
|
|
7
|
+
export type * from './types.ts';
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type MCPAuthErrorCode =
|
|
2
|
+
| 'conflict'
|
|
3
|
+
| 'not-found'
|
|
4
|
+
| 'invalid-client-name'
|
|
5
|
+
| 'invalid-redirect-uri'
|
|
6
|
+
| 'invalid-setup';
|
|
7
|
+
|
|
8
|
+
export class MCPAuthError extends Error {
|
|
9
|
+
readonly code: MCPAuthErrorCode;
|
|
10
|
+
|
|
11
|
+
constructor(code: MCPAuthErrorCode, message: string) {
|
|
12
|
+
super(message);
|
|
13
|
+
|
|
14
|
+
this.name = 'MCPAuthError';
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { buildAdmin } from './admin/build-admin.ts';
|
|
2
|
+
import { DEFAULT_PATHS } from './default-paths.ts';
|
|
3
|
+
import { openStore } from './store/open-store.ts';
|
|
4
|
+
import type { MCPAuthAdmin, MCPAuthAdminOptions } from './types.ts';
|
|
5
|
+
|
|
6
|
+
// An admin command opens the database with no origin, and gets only the admin
|
|
7
|
+
// calls.
|
|
8
|
+
export async function openMCPAuthAdmin<Scope extends string>(
|
|
9
|
+
options: MCPAuthAdminOptions<Scope>,
|
|
10
|
+
): Promise<MCPAuthAdmin> {
|
|
11
|
+
const store = await openStore(options, { origin: null, paths: DEFAULT_PATHS });
|
|
12
|
+
|
|
13
|
+
return buildAdmin(store, null);
|
|
14
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { buildAdmin } from './admin/build-admin.ts';
|
|
2
|
+
import { readClientScopes } from './grants/read-client-scopes.ts';
|
|
3
|
+
import { verifyOAuthAccess } from './grants/verify-oauth-access.ts';
|
|
4
|
+
import { MCPAuthError } from './mcp-auth-error.ts';
|
|
5
|
+
import { createEnrollmentState } from './passkeys/create-enrollment-state.ts';
|
|
6
|
+
import { buildRoutes } from './routes/build-routes.ts';
|
|
7
|
+
import { buildServiceTokenVerifier } from './service-tokens/build-service-token-verifier.ts';
|
|
8
|
+
import { createSignInState } from './sign-in/create-sign-in-state.ts';
|
|
9
|
+
import type { RouteContext } from './sign-in/route-context.ts';
|
|
10
|
+
import { CODE_SECONDS } from './store/create-auth-server.ts';
|
|
11
|
+
import { openStore } from './store/open-store.ts';
|
|
12
|
+
import type { MCPAuth, MCPAuthOptions } from './types.ts';
|
|
13
|
+
|
|
14
|
+
export async function openMCPAuth<Scope extends string, Limits = null>(
|
|
15
|
+
options: MCPAuthOptions<Scope, Limits>,
|
|
16
|
+
): Promise<MCPAuth<Scope, Limits>> {
|
|
17
|
+
const resource = `${options.origin}${options.paths.machine.mcp}`;
|
|
18
|
+
|
|
19
|
+
if (options.serviceTokens !== undefined && options.serviceTokens.file.resource !== resource) {
|
|
20
|
+
throw new MCPAuthError(
|
|
21
|
+
'invalid-setup',
|
|
22
|
+
`the service token file names another resource than ${resource}`,
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const store = await openStore(options, { origin: options.origin, paths: options.paths });
|
|
27
|
+
|
|
28
|
+
// A resource served under an earlier origin stays a valid token target until
|
|
29
|
+
// its row goes.
|
|
30
|
+
await store.db.deleteFrom('oauthResource').where('identifier', '!=', resource).execute();
|
|
31
|
+
|
|
32
|
+
const signIns = createSignInState(CODE_SECONDS * 1000, options.clock.now);
|
|
33
|
+
|
|
34
|
+
const routes = buildRoutes({
|
|
35
|
+
store,
|
|
36
|
+
origin: options.origin,
|
|
37
|
+
resource,
|
|
38
|
+
paths: options.paths,
|
|
39
|
+
productName: options.productName,
|
|
40
|
+
scopes: options.scopes,
|
|
41
|
+
clock: options.clock,
|
|
42
|
+
security: options.security,
|
|
43
|
+
signIns,
|
|
44
|
+
enrollments: createEnrollmentState(options.clock.now),
|
|
45
|
+
consentFields: options.grantLimits ?? null,
|
|
46
|
+
} satisfies RouteContext);
|
|
47
|
+
|
|
48
|
+
const serviceTokens =
|
|
49
|
+
options.serviceTokens === undefined
|
|
50
|
+
? null
|
|
51
|
+
: buildServiceTokenVerifier(options.serviceTokens.file);
|
|
52
|
+
|
|
53
|
+
const prefix = options.serviceTokens?.prefix ?? null;
|
|
54
|
+
const scopes = options.scopes;
|
|
55
|
+
const grantLimits = options.grantLimits ?? null;
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
...buildAdmin(store, signIns),
|
|
59
|
+
resource,
|
|
60
|
+
issuer: options.origin,
|
|
61
|
+
paths: options.paths,
|
|
62
|
+
routes,
|
|
63
|
+
|
|
64
|
+
verify: (bearer) => {
|
|
65
|
+
if (serviceTokens !== null && prefix !== null && bearer.startsWith(prefix)) {
|
|
66
|
+
return Promise.resolve(serviceTokens.verify(bearer));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return verifyOAuthAccess(
|
|
70
|
+
{
|
|
71
|
+
store,
|
|
72
|
+
resource,
|
|
73
|
+
scopes,
|
|
74
|
+
grantLimits,
|
|
75
|
+
},
|
|
76
|
+
bearer,
|
|
77
|
+
);
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
// oxlint-disable-next-line zgeoff/verb-contract -- the contract names this call findClientScopes
|
|
81
|
+
findClientScopes: (clientID) => {
|
|
82
|
+
const service = serviceTokens?.findScopes(clientID) ?? null;
|
|
83
|
+
|
|
84
|
+
return service === null
|
|
85
|
+
? readClientScopes(store, scopes, clientID)
|
|
86
|
+
: Promise.resolve(service);
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|