@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,27 @@
|
|
|
1
|
+
// `scope` is what better-auth is asked to grant, null when the choice denies.
|
|
2
|
+
// `noneTicked` is an allow sent with no scope ticked, which denies.
|
|
3
|
+
interface ConsentChoice {
|
|
4
|
+
readonly accept: boolean;
|
|
5
|
+
readonly scopes: readonly string[];
|
|
6
|
+
readonly scope: string | null;
|
|
7
|
+
readonly noneTicked: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// The owner's answer on the consent form, from the scopes it ticked and its
|
|
11
|
+
// decision. A ticked value that is no scope of the server counts for nothing.
|
|
12
|
+
export function pickConsentChoice(
|
|
13
|
+
known: readonly string[],
|
|
14
|
+
ticked: readonly string[],
|
|
15
|
+
decision: string | null,
|
|
16
|
+
): ConsentChoice {
|
|
17
|
+
const scopes = known.filter((scope) => ticked.includes(scope));
|
|
18
|
+
const allow = decision === 'approve';
|
|
19
|
+
const accept = allow && scopes.length > 0;
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
accept,
|
|
23
|
+
scopes: accept ? scopes : [],
|
|
24
|
+
scope: accept ? [...scopes, 'offline_access'].join(' ') : null,
|
|
25
|
+
noneTicked: allow && !accept,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SecurityEvent } from '../types.ts';
|
|
2
|
+
|
|
3
|
+
type ConsentOutcome = Pick<SecurityEvent, 'kind' | 'outcome' | 'reason'>;
|
|
4
|
+
|
|
5
|
+
// `noneTicked` is an allow sent with no scope ticked, which denies.
|
|
6
|
+
export function pickConsentOutcome(issuedCode: boolean, noneTicked: boolean): ConsentOutcome {
|
|
7
|
+
if (issuedCode) {
|
|
8
|
+
return { kind: 'consent', outcome: 'allowed' };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return noneTicked
|
|
12
|
+
? { kind: 'consent', outcome: 'denied', reason: 'none_ticked' }
|
|
13
|
+
: { kind: 'consent', outcome: 'denied' };
|
|
14
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Store } from '../store/open-store.ts';
|
|
2
|
+
|
|
3
|
+
export async function readSessionID(store: Store, cookie: string | null): Promise<string | null> {
|
|
4
|
+
if (cookie === null || cookie === '') {
|
|
5
|
+
return null;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
const found = await store.auth.api.getSession({ headers: new Headers({ cookie }) });
|
|
9
|
+
|
|
10
|
+
return found === null ? null : found.session.id;
|
|
11
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Store } from '../store/open-store.ts';
|
|
2
|
+
import type { OAuthClientID } from '../types.ts';
|
|
3
|
+
import { normalizeClientName } from '../utils/normalize-client-name.ts';
|
|
4
|
+
|
|
5
|
+
// The name the owner gave the client, cleaned for a page or an event, or the
|
|
6
|
+
// client's ID when the core holds no such client.
|
|
7
|
+
export async function readStoredClientName(store: Store, clientID: OAuthClientID): Promise<string> {
|
|
8
|
+
const row = await store.db
|
|
9
|
+
.selectFrom('oauthClient')
|
|
10
|
+
.select('name')
|
|
11
|
+
.where('clientId', '=', clientID)
|
|
12
|
+
.executeTakeFirst();
|
|
13
|
+
|
|
14
|
+
return normalizeClientName(row?.name, clientID);
|
|
15
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { isRecord } from '@zgeoff/std';
|
|
2
|
+
|
|
3
|
+
// The URL better-auth tells the browser to go to next, or null.
|
|
4
|
+
export function readURLField(body: unknown): string | null {
|
|
5
|
+
if (!isRecord(body)) {
|
|
6
|
+
return null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const next = body['url'] ?? body['redirect_uri'];
|
|
10
|
+
|
|
11
|
+
return typeof next === 'string' ? next : null;
|
|
12
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { toHTMLText } from '../utils/to-html-text.ts';
|
|
2
|
+
|
|
3
|
+
interface ConsentPageView {
|
|
4
|
+
readonly consentPath: string;
|
|
5
|
+
|
|
6
|
+
// The signed authorization query the page posts back.
|
|
7
|
+
readonly oauthQuery: string;
|
|
8
|
+
readonly clientName: string;
|
|
9
|
+
readonly redirectURI: string;
|
|
10
|
+
readonly scopes: readonly string[];
|
|
11
|
+
|
|
12
|
+
// The app's own form fields, as HTML it has escaped.
|
|
13
|
+
readonly extraFields: string;
|
|
14
|
+
readonly error: string | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function renderConsentPage(view: ConsentPageView): string {
|
|
18
|
+
const scopeRows = view.scopes
|
|
19
|
+
.map(
|
|
20
|
+
(scope) =>
|
|
21
|
+
`<label><input type="checkbox" name="scope" value="${toHTMLText(scope)}"> ${toHTMLText(scope)}</label>`,
|
|
22
|
+
)
|
|
23
|
+
.join('\n');
|
|
24
|
+
|
|
25
|
+
const error = view.error === null ? '' : `<p class="error">${toHTMLText(view.error)}</p>`;
|
|
26
|
+
|
|
27
|
+
return `<!doctype html>
|
|
28
|
+
<html lang="en">
|
|
29
|
+
<head>
|
|
30
|
+
<meta charset="utf-8">
|
|
31
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
32
|
+
<title>Choose what to allow</title>
|
|
33
|
+
<style>
|
|
34
|
+
body { font-family: system-ui, sans-serif; max-width: 32rem; margin: 3rem auto; padding: 0 1rem; line-height: 1.5; }
|
|
35
|
+
label { display: block; margin: 0.25rem 0; }
|
|
36
|
+
.error { color: #b00020; }
|
|
37
|
+
code { word-break: break-all; }
|
|
38
|
+
button { font: inherit; margin-right: 0.5rem; }
|
|
39
|
+
</style>
|
|
40
|
+
</head>
|
|
41
|
+
<body>
|
|
42
|
+
<h1>Choose what to allow</h1>
|
|
43
|
+
<p><strong>${toHTMLText(view.clientName)}</strong> returns to <code>${toHTMLText(view.redirectURI)}</code> with the access you allow here.</p>
|
|
44
|
+
${error}
|
|
45
|
+
<form method="post" action="${toHTMLText(view.consentPath)}">
|
|
46
|
+
<input type="hidden" name="oauth_query" value="${toHTMLText(view.oauthQuery)}">
|
|
47
|
+
<fieldset>
|
|
48
|
+
<legend>Allow it to use these scopes</legend>
|
|
49
|
+
${scopeRows}
|
|
50
|
+
</fieldset>
|
|
51
|
+
${view.extraFields}
|
|
52
|
+
<p><button type="submit" name="decision" value="approve">Allow</button><button type="submit" name="decision" value="deny">Deny</button></p>
|
|
53
|
+
</form>
|
|
54
|
+
</body>
|
|
55
|
+
</html>
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { EnrollmentState } from '../passkeys/create-enrollment-state.ts';
|
|
2
|
+
import type { Store } from '../store/open-store.ts';
|
|
3
|
+
import type { Clock, GrantLimits, MCPAuthPaths, SecuritySink } from '../types.ts';
|
|
4
|
+
import type { SignInState } from './create-sign-in-state.ts';
|
|
5
|
+
|
|
6
|
+
// What every route reads: the server's identity, the sign-ins waiting for the
|
|
7
|
+
// owner, and the passkey enrollments in progress.
|
|
8
|
+
export interface RouteContext {
|
|
9
|
+
readonly store: Store;
|
|
10
|
+
readonly origin: string;
|
|
11
|
+
|
|
12
|
+
// The one resource every token is bound to.
|
|
13
|
+
readonly resource: string;
|
|
14
|
+
readonly paths: MCPAuthPaths;
|
|
15
|
+
readonly productName: string;
|
|
16
|
+
readonly scopes: readonly string[];
|
|
17
|
+
readonly clock: Clock;
|
|
18
|
+
readonly security: SecuritySink;
|
|
19
|
+
readonly signIns: SignInState;
|
|
20
|
+
readonly enrollments: EnrollmentState;
|
|
21
|
+
readonly consentFields: Pick<
|
|
22
|
+
GrantLimits<unknown>,
|
|
23
|
+
'renderConsentFields' | 'parseConsentFields'
|
|
24
|
+
> | null;
|
|
25
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { constantTimeEqual, makeSignature } from 'better-auth/crypto';
|
|
2
|
+
|
|
3
|
+
export async function verifyOAuthQuery(
|
|
4
|
+
oauthQuery: string,
|
|
5
|
+
secret: string,
|
|
6
|
+
now: number,
|
|
7
|
+
): Promise<boolean> {
|
|
8
|
+
const params = new URLSearchParams(oauthQuery);
|
|
9
|
+
|
|
10
|
+
const signatures = params.getAll('sig');
|
|
11
|
+
const [signature] = signatures;
|
|
12
|
+
const expiresAt = Number(params.get('exp')) * 1000;
|
|
13
|
+
|
|
14
|
+
if (signatures.length !== 1 || signature === undefined || signature === '') {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
params.delete('sig');
|
|
19
|
+
|
|
20
|
+
// Ordered by name, then by value, comparing code units as better-auth does
|
|
21
|
+
// when it signs; the NUL separator sorts a name before any longer name it
|
|
22
|
+
// prefixes.
|
|
23
|
+
const canonical = new URLSearchParams(
|
|
24
|
+
[...params].toSorted(([keyA, valueA], [keyB, valueB]) => {
|
|
25
|
+
const pairA = `${keyA}\u0000${valueA}`;
|
|
26
|
+
const pairB = `${keyB}\u0000${valueB}`;
|
|
27
|
+
|
|
28
|
+
if (pairA === pairB) {
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return pairA < pairB ? -1 : 1;
|
|
33
|
+
}),
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
const expected = await makeSignature(canonical.toString(), secret);
|
|
37
|
+
|
|
38
|
+
return constantTimeEqual(signature, expected) && Number.isFinite(expiresAt) && expiresAt >= now;
|
|
39
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { MCPAuthError } from '../mcp-auth-error.ts';
|
|
4
|
+
|
|
5
|
+
const CASCADING_TABLES = ['oauthAccessToken', 'oauthRefreshToken', 'session'] as const;
|
|
6
|
+
|
|
7
|
+
const KeyRowSchema = z.object({
|
|
8
|
+
table: z.string(),
|
|
9
|
+
from: z.string(),
|
|
10
|
+
to: z.string(),
|
|
11
|
+
on_delete: z.string(),
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export function checkCascadeKeys(sqlite: Database): void {
|
|
15
|
+
for (const table of CASCADING_TABLES) {
|
|
16
|
+
const keys = sqlite
|
|
17
|
+
.query(`PRAGMA foreign_key_list("${table}")`)
|
|
18
|
+
.all()
|
|
19
|
+
.map((row) => KeyRowSchema.parse(row));
|
|
20
|
+
|
|
21
|
+
const isCascading = keys.some(
|
|
22
|
+
(key) =>
|
|
23
|
+
key.table === 'user' &&
|
|
24
|
+
key.from === 'userId' &&
|
|
25
|
+
key.to === 'id' &&
|
|
26
|
+
key.on_delete === 'CASCADE',
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
if (!isCascading) {
|
|
30
|
+
throw new MCPAuthError(
|
|
31
|
+
'invalid-setup',
|
|
32
|
+
`${table}.userId must reference user(id) on delete cascade`,
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { MCPAuthError } from '../mcp-auth-error.ts';
|
|
4
|
+
|
|
5
|
+
const PragmaRowSchema = z.object({ foreign_keys: z.number() });
|
|
6
|
+
|
|
7
|
+
// A pragma inside a transaction does nothing, so the core reads the setting
|
|
8
|
+
// back instead of trusting the statement.
|
|
9
|
+
export function checkForeignKeys(sqlite: Database): void {
|
|
10
|
+
sqlite.run('PRAGMA foreign_keys = ON');
|
|
11
|
+
|
|
12
|
+
const row = PragmaRowSchema.parse(sqlite.query('PRAGMA foreign_keys').get());
|
|
13
|
+
|
|
14
|
+
if (row.foreign_keys === 0) {
|
|
15
|
+
throw new MCPAuthError(
|
|
16
|
+
'invalid-setup',
|
|
17
|
+
'foreign keys are off on the connection, so a revoke would not end the tokens of a grant',
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { MCPAuthError } from '../mcp-auth-error.ts';
|
|
2
|
+
import type { MCPAuthTables } from '../types.ts';
|
|
3
|
+
|
|
4
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
5
|
+
|
|
6
|
+
// The names go into DDL statements, so each is a plain identifier.
|
|
7
|
+
export function checkTableNames(tables: MCPAuthTables): void {
|
|
8
|
+
for (const name of [tables.passkey, tables.enrollmentToken]) {
|
|
9
|
+
if (!IDENTIFIER.test(name)) {
|
|
10
|
+
throw new MCPAuthError('invalid-setup', `${name} is not a plain table name`);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { MCPAuthError } from '../mcp-auth-error.ts';
|
|
3
|
+
import { readTableColumns } from './read-table-columns.ts';
|
|
4
|
+
|
|
5
|
+
// A user table from before the grant columns cannot take them as new required
|
|
6
|
+
// columns, so the app's migration comes first.
|
|
7
|
+
export function checkUserColumns(sqlite: Database): void {
|
|
8
|
+
const columns = readTableColumns(sqlite, 'user');
|
|
9
|
+
|
|
10
|
+
if (columns.length === 0) {
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
for (const required of ['clientId', 'approvedBy']) {
|
|
15
|
+
if (!columns.includes(required)) {
|
|
16
|
+
throw new MCPAuthError(
|
|
17
|
+
'invalid-setup',
|
|
18
|
+
`the user table lacks the ${required} column; run the grant migration first`,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { mcp } from '@better-auth/mcp';
|
|
3
|
+
import { oauthProvider } from '@better-auth/oauth-provider';
|
|
4
|
+
import type { OAuthOptions, Scope as ProviderScope } from '@better-auth/oauth-provider';
|
|
5
|
+
import { betterAuth } from 'better-auth';
|
|
6
|
+
import type { BetterAuthPlugin } from 'better-auth';
|
|
7
|
+
import type { Kysely } from 'kysely';
|
|
8
|
+
import type { MCPAuthPaths } from '../types.ts';
|
|
9
|
+
import { deriveTokenHash } from '../utils/derive-token-hash.ts';
|
|
10
|
+
import { createGrantPlugin } from './create-grant-plugin.ts';
|
|
11
|
+
import type { StoreSchema } from './store-schema.ts';
|
|
12
|
+
|
|
13
|
+
export const ACCESS_TOKEN_SECONDS = 15 * 60;
|
|
14
|
+
export const REFRESH_TOKEN_SECONDS = 30 * 24 * 60 * 60;
|
|
15
|
+
export const CODE_SECONDS = 10 * 60;
|
|
16
|
+
export const SESSION_SECONDS = 30 * 60;
|
|
17
|
+
|
|
18
|
+
// A host with no origin, such as an admin command, builds a server that only
|
|
19
|
+
// shares the schema.
|
|
20
|
+
const SCHEMA_ORIGIN = 'http://127.0.0.1';
|
|
21
|
+
|
|
22
|
+
interface AuthServerOptions {
|
|
23
|
+
readonly db: Kysely<StoreSchema>;
|
|
24
|
+
readonly origin: string | null;
|
|
25
|
+
readonly paths: MCPAuthPaths;
|
|
26
|
+
readonly scopes: readonly string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function createAuthServer(options: AuthServerOptions) {
|
|
30
|
+
// better-auth reads these when it builds its context; an empty endpoint
|
|
31
|
+
// turns its telemetry into a no-op.
|
|
32
|
+
process.env['BETTER_AUTH_TELEMETRY'] = '0';
|
|
33
|
+
process.env['BETTER_AUTH_TELEMETRY_ENDPOINT'] = '';
|
|
34
|
+
|
|
35
|
+
const origin = options.origin ?? SCHEMA_ORIGIN;
|
|
36
|
+
|
|
37
|
+
const providerOptions: OAuthOptions<ProviderScope[]> = {
|
|
38
|
+
loginPage: options.paths.browser.login,
|
|
39
|
+
consentPage: options.paths.browser.consent,
|
|
40
|
+
scopes: [...options.scopes, 'offline_access'],
|
|
41
|
+
disableJwtPlugin: true,
|
|
42
|
+
allowDynamicClientRegistration: false,
|
|
43
|
+
grantTypes: ['authorization_code', 'refresh_token'],
|
|
44
|
+
|
|
45
|
+
// The server holds one resource, so every client may request it.
|
|
46
|
+
enforcePerClientResources: false,
|
|
47
|
+
accessTokenExpiresIn: ACCESS_TOKEN_SECONDS,
|
|
48
|
+
refreshTokenExpiresIn: REFRESH_TOKEN_SECONDS,
|
|
49
|
+
codeExpiresIn: CODE_SECONDS,
|
|
50
|
+
refreshTokenReuseInterval: 0,
|
|
51
|
+
storeTokens: { hash: (token: string) => Promise.resolve(deriveTokenHash(token)) },
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const provider =
|
|
55
|
+
options.origin === null
|
|
56
|
+
? oauthProvider(providerOptions)
|
|
57
|
+
: mcp({ ...providerOptions, resource: `${origin}${options.paths.machine.mcp}` });
|
|
58
|
+
|
|
59
|
+
return betterAuth({
|
|
60
|
+
baseURL: origin,
|
|
61
|
+
basePath: '/',
|
|
62
|
+
|
|
63
|
+
// Drawn at each open, so a restart ends the sign-ins in progress.
|
|
64
|
+
secret: randomBytes(32).toString('base64url'),
|
|
65
|
+
database: { db: options.db, type: 'sqlite' },
|
|
66
|
+
telemetry: { enabled: false },
|
|
67
|
+
logger: { disabled: true },
|
|
68
|
+
|
|
69
|
+
// better-auth counts by client address, which a proxy hides, so all
|
|
70
|
+
// callers would share one bucket. The core limits sign-ins itself, and a
|
|
71
|
+
// guess fails on 32 random characters and PKCE.
|
|
72
|
+
rateLimit: { enabled: false },
|
|
73
|
+
advanced: { database: { validateSchema: false } },
|
|
74
|
+
trustedOrigins: [origin],
|
|
75
|
+
onAPIError: { errorURL: options.paths.browser.error },
|
|
76
|
+
|
|
77
|
+
// A session carries one sign-in from the login page to the code exchange,
|
|
78
|
+
// which detaches every token from it.
|
|
79
|
+
session: { expiresIn: SESSION_SECONDS, disableSessionRefresh: true },
|
|
80
|
+
user: {
|
|
81
|
+
additionalFields: {
|
|
82
|
+
clientId: { type: 'string', required: true, input: false },
|
|
83
|
+
scopes: { type: 'string', required: false, input: false },
|
|
84
|
+
approvedBy: { type: 'string', required: true, input: false },
|
|
85
|
+
limits: { type: 'string', required: false, input: false },
|
|
86
|
+
lastUsedAt: { type: 'date', required: false, input: false },
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
|
|
90
|
+
// The provider's endpoint types do not satisfy the plugin type under
|
|
91
|
+
// exactOptionalPropertyTypes.
|
|
92
|
+
// oxlint-disable-next-line typescript/consistent-type-assertions -- better-auth plugin type under exactOptionalPropertyTypes
|
|
93
|
+
plugins: [provider as BetterAuthPlugin, createGrantPlugin()],
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export type AuthServer = ReturnType<typeof createAuthServer>;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { getOAuthProviderApi } from '@better-auth/oauth-provider';
|
|
2
|
+
import type { BetterAuthPlugin } from 'better-auth';
|
|
3
|
+
import { createAuthEndpoint } from 'better-auth/api';
|
|
4
|
+
import { setSessionCookie } from 'better-auth/cookies';
|
|
5
|
+
import { generateRandomString } from 'better-auth/crypto';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
|
|
8
|
+
// better-auth needs a unique email on every user row; no mail ever reaches it.
|
|
9
|
+
const GRANT_EMAIL_DOMAIN = 'grant.invalid';
|
|
10
|
+
|
|
11
|
+
const SignInBodySchema = z.object({
|
|
12
|
+
oauth_query: z.string().optional(),
|
|
13
|
+
clientID: z.string().min(1),
|
|
14
|
+
clientName: z.string().min(1),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
// Every endpoint is server-only: better-auth refuses it over HTTP, so only the
|
|
18
|
+
// core's own routes reach it, after they check what it guards.
|
|
19
|
+
export function createGrantPlugin() {
|
|
20
|
+
return {
|
|
21
|
+
id: 'mcp-auth-grant',
|
|
22
|
+
endpoints: {
|
|
23
|
+
signInGrant: createAuthEndpoint(
|
|
24
|
+
'/mcp-auth/sign-in-grant',
|
|
25
|
+
{ method: 'POST', body: SignInBodySchema, metadata: { SERVER_ONLY: true } },
|
|
26
|
+
async (ctx) => {
|
|
27
|
+
const adapter = ctx.context.internalAdapter;
|
|
28
|
+
const id = generateRandomString(32, 'a-z', 'A-Z', '0-9');
|
|
29
|
+
|
|
30
|
+
const user = await adapter.createUser(
|
|
31
|
+
{
|
|
32
|
+
id,
|
|
33
|
+
email: `${id}@${GRANT_EMAIL_DOMAIN}`,
|
|
34
|
+
name: ctx.body.clientName,
|
|
35
|
+
emailVerified: true,
|
|
36
|
+
clientId: ctx.body.clientID,
|
|
37
|
+
approvedBy: 'passkey',
|
|
38
|
+
},
|
|
39
|
+
{ method: 'admin' },
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
const session = await adapter.createSession(user.id);
|
|
43
|
+
|
|
44
|
+
await setSessionCookie(ctx, { session, user });
|
|
45
|
+
|
|
46
|
+
return ctx.json({ signedIn: true });
|
|
47
|
+
},
|
|
48
|
+
),
|
|
49
|
+
verifyAccessToken: createAuthEndpoint(
|
|
50
|
+
'/mcp-auth/verify-access-token',
|
|
51
|
+
{ method: 'POST', body: z.object({ token: z.string() }), metadata: { SERVER_ONLY: true } },
|
|
52
|
+
async (ctx) => {
|
|
53
|
+
const provider = ctx.context.getPlugin('oauth-provider');
|
|
54
|
+
|
|
55
|
+
if (provider === null) {
|
|
56
|
+
throw new Error('the oauth-provider plugin is not installed');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const payload = await getOAuthProviderApi(ctx, provider.options).requireActiveAccessToken(
|
|
60
|
+
ctx.body.token,
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
return ctx.json(payload);
|
|
64
|
+
},
|
|
65
|
+
),
|
|
66
|
+
},
|
|
67
|
+
} satisfies BetterAuthPlugin;
|
|
68
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { MCPAuthError } from '../mcp-auth-error.ts';
|
|
3
|
+
import type { MCPAuthTables } from '../types.ts';
|
|
4
|
+
import { readTableColumns } from './read-table-columns.ts';
|
|
5
|
+
|
|
6
|
+
const PASSKEY_COLUMNS = [
|
|
7
|
+
'id',
|
|
8
|
+
'public_key',
|
|
9
|
+
'counter',
|
|
10
|
+
'transports',
|
|
11
|
+
'created_at',
|
|
12
|
+
'last_used_at',
|
|
13
|
+
] as const;
|
|
14
|
+
|
|
15
|
+
const ENROLLMENT_COLUMNS = ['token_hash', 'created_at', 'expires_at'] as const;
|
|
16
|
+
|
|
17
|
+
// The core creates its own table and any column of it that is missing. It
|
|
18
|
+
// creates the app's passkey table when absent, and never adds a column to it.
|
|
19
|
+
export function createOwnedTables(sqlite: Database, tables: MCPAuthTables): void {
|
|
20
|
+
sqlite.run(
|
|
21
|
+
`create table if not exists "${tables.passkey}" (id text primary key not null, public_key text not null, counter integer not null, transports text not null, created_at text not null, last_used_at text)`,
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
const passkeyColumns = readTableColumns(sqlite, tables.passkey);
|
|
25
|
+
const missing = PASSKEY_COLUMNS.filter((column) => !passkeyColumns.includes(column));
|
|
26
|
+
|
|
27
|
+
if (missing.length > 0) {
|
|
28
|
+
throw new MCPAuthError(
|
|
29
|
+
'invalid-setup',
|
|
30
|
+
`the passkey table ${tables.passkey} lacks the columns ${missing.join(', ')}`,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
sqlite.run(
|
|
35
|
+
`create table if not exists "${tables.enrollmentToken}" (token_hash text primary key not null, created_at text not null, expires_at text not null)`,
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
const enrollmentColumns = readTableColumns(sqlite, tables.enrollmentToken);
|
|
39
|
+
|
|
40
|
+
for (const column of ENROLLMENT_COLUMNS) {
|
|
41
|
+
if (!enrollmentColumns.includes(column)) {
|
|
42
|
+
sqlite.run(`alter table "${tables.enrollmentToken}" add column "${column}" text`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { buildSQLiteDialect } from '@zgeoff/kysely-bun-sqlite';
|
|
2
|
+
import { getMigrations } from 'better-auth/db/migration';
|
|
3
|
+
import { Kysely } from 'kysely';
|
|
4
|
+
import type { MCPAuthAdminOptions, MCPAuthPaths } from '../types.ts';
|
|
5
|
+
import { checkCascadeKeys } from './check-cascade-keys.ts';
|
|
6
|
+
import { checkForeignKeys } from './check-foreign-keys.ts';
|
|
7
|
+
import { checkTableNames } from './check-table-names.ts';
|
|
8
|
+
import { checkUserColumns } from './check-user-columns.ts';
|
|
9
|
+
import { createAuthServer } from './create-auth-server.ts';
|
|
10
|
+
import type { AuthServer } from './create-auth-server.ts';
|
|
11
|
+
import { createOwnedTables } from './create-owned-tables.ts';
|
|
12
|
+
import type { StoreSchema } from './store-schema.ts';
|
|
13
|
+
|
|
14
|
+
export interface Store {
|
|
15
|
+
readonly db: Kysely<StoreSchema>;
|
|
16
|
+
readonly auth: AuthServer;
|
|
17
|
+
readonly options: MCPAuthAdminOptions<string>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface StoreOptions {
|
|
21
|
+
readonly origin: string | null;
|
|
22
|
+
readonly paths: MCPAuthPaths;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// The database, better-auth over it, and the tables the core adds, checked
|
|
26
|
+
// for what a revoke relies on.
|
|
27
|
+
export async function openStore(
|
|
28
|
+
admin: MCPAuthAdminOptions<string>,
|
|
29
|
+
options: StoreOptions,
|
|
30
|
+
): Promise<Store> {
|
|
31
|
+
checkTableNames(admin.tables);
|
|
32
|
+
checkForeignKeys(admin.database);
|
|
33
|
+
checkUserColumns(admin.database);
|
|
34
|
+
|
|
35
|
+
const db = new Kysely<StoreSchema>({ dialect: buildSQLiteDialect(admin.database) });
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
const auth = createAuthServer({
|
|
39
|
+
db,
|
|
40
|
+
origin: options.origin,
|
|
41
|
+
paths: options.paths,
|
|
42
|
+
scopes: admin.scopes,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const migrations = await getMigrations(auth.options);
|
|
46
|
+
|
|
47
|
+
await migrations.runMigrations();
|
|
48
|
+
|
|
49
|
+
createOwnedTables(admin.database, admin.tables);
|
|
50
|
+
checkCascadeKeys(admin.database);
|
|
51
|
+
|
|
52
|
+
// better-auth starts its context when it is built, and that start queries
|
|
53
|
+
// the database, so a close before it settles destroys the driver under it.
|
|
54
|
+
await auth.$context;
|
|
55
|
+
|
|
56
|
+
// Only the admin fields stay: a full options object may hold the
|
|
57
|
+
// plaintext service tokens, and the handle keeps digests only.
|
|
58
|
+
const kept: MCPAuthAdminOptions<string> = {
|
|
59
|
+
database: admin.database,
|
|
60
|
+
scopes: admin.scopes,
|
|
61
|
+
tables: admin.tables,
|
|
62
|
+
clock: admin.clock,
|
|
63
|
+
onGrantRevoked: admin.onGrantRevoked,
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
return { db, auth, options: kept };
|
|
67
|
+
} catch (error) {
|
|
68
|
+
await db.destroy();
|
|
69
|
+
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
const ColumnRowSchema = z.object({ name: z.string() });
|
|
5
|
+
|
|
6
|
+
// The columns a table holds, or an empty list when it does not exist. The
|
|
7
|
+
// table name goes into the statement, so the caller has checked it.
|
|
8
|
+
export function readTableColumns(sqlite: Database, table: string): string[] {
|
|
9
|
+
const rows = sqlite.query(`PRAGMA table_info("${table}")`).all();
|
|
10
|
+
|
|
11
|
+
return rows.map((row) => ColumnRowSchema.parse(row).name);
|
|
12
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { GrantID } from '../types.ts';
|
|
2
|
+
import type { Store } from './open-store.ts';
|
|
3
|
+
|
|
4
|
+
// One delete ends a grant: every token and session of it references the row
|
|
5
|
+
// with on delete cascade. The hook runs after the delete commits.
|
|
6
|
+
export async function removeGrantRows(
|
|
7
|
+
store: Store,
|
|
8
|
+
grantIDs: readonly GrantID[],
|
|
9
|
+
): Promise<GrantID[]> {
|
|
10
|
+
if (grantIDs.length === 0) {
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const removed = await store.db
|
|
15
|
+
.deleteFrom('user')
|
|
16
|
+
.where('id', 'in', grantIDs)
|
|
17
|
+
.returning('id')
|
|
18
|
+
.execute();
|
|
19
|
+
|
|
20
|
+
const removedIDs = removed.map((row) => row.id);
|
|
21
|
+
|
|
22
|
+
for (const grantID of removedIDs) {
|
|
23
|
+
store.options.onGrantRevoked(grantID);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return removedIDs;
|
|
27
|
+
}
|