@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,61 @@
|
|
|
1
|
+
import type { GrantID, OAuthClientID } from '../types.ts';
|
|
2
|
+
|
|
3
|
+
// Only the columns the core reads and writes itself: better-auth owns the
|
|
4
|
+
// tables. Dates are ISO 8601 strings and string lists are JSON arrays.
|
|
5
|
+
export interface StoreSchema {
|
|
6
|
+
readonly user: {
|
|
7
|
+
readonly id: GrantID;
|
|
8
|
+
readonly email: string;
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly emailVerified: number;
|
|
11
|
+
readonly createdAt: string;
|
|
12
|
+
readonly updatedAt: string;
|
|
13
|
+
readonly clientId: OAuthClientID;
|
|
14
|
+
readonly scopes: string | null;
|
|
15
|
+
readonly approvedBy: string;
|
|
16
|
+
readonly limits: string | null;
|
|
17
|
+
readonly lastUsedAt: string | null;
|
|
18
|
+
};
|
|
19
|
+
readonly session: {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
readonly expiresAt: string;
|
|
22
|
+
readonly userId: GrantID;
|
|
23
|
+
};
|
|
24
|
+
readonly verification: { readonly id: string; readonly expiresAt: string };
|
|
25
|
+
readonly oauthClient: {
|
|
26
|
+
readonly id: string;
|
|
27
|
+
readonly clientId: OAuthClientID;
|
|
28
|
+
readonly name: string | null;
|
|
29
|
+
readonly redirectUris: string;
|
|
30
|
+
readonly scopes: string;
|
|
31
|
+
readonly clientCredentialsScopes: string;
|
|
32
|
+
readonly tokenEndpointAuthMethod: string;
|
|
33
|
+
readonly grantTypes: string;
|
|
34
|
+
readonly responseTypes: string;
|
|
35
|
+
readonly applicationType: string;
|
|
36
|
+
readonly requirePKCE: number;
|
|
37
|
+
readonly disabled: number;
|
|
38
|
+
readonly createdAt: string | null;
|
|
39
|
+
readonly updatedAt: string | null;
|
|
40
|
+
};
|
|
41
|
+
readonly oauthAccessToken: {
|
|
42
|
+
readonly id: string;
|
|
43
|
+
readonly token: string;
|
|
44
|
+
readonly clientId: OAuthClientID;
|
|
45
|
+
readonly sessionId: string | null;
|
|
46
|
+
readonly userId: GrantID | null;
|
|
47
|
+
readonly expiresAt: string;
|
|
48
|
+
};
|
|
49
|
+
readonly oauthRefreshToken: {
|
|
50
|
+
readonly id: string;
|
|
51
|
+
readonly token: string;
|
|
52
|
+
readonly clientId: OAuthClientID;
|
|
53
|
+
readonly sessionId: string | null;
|
|
54
|
+
readonly userId: GrantID;
|
|
55
|
+
readonly expiresAt: string;
|
|
56
|
+
readonly createdAt: string;
|
|
57
|
+
readonly revoked: string | null;
|
|
58
|
+
readonly rotatedAt: string | null;
|
|
59
|
+
};
|
|
60
|
+
readonly oauthResource: { readonly identifier: string };
|
|
61
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import type { GrantID, MCPAuth, OAuthClientID } from '../types.ts';
|
|
2
|
+
import { buildFormRequest } from './build-form-request.ts';
|
|
3
|
+
import { buildTestRequester } from './build-test-requester.ts';
|
|
4
|
+
import { readJSONRecord } from './read-json-record.ts';
|
|
5
|
+
import { TEST_REDIRECT_URI, runSignInToConsent } from './run-sign-in-to-consent.ts';
|
|
6
|
+
|
|
7
|
+
export interface TestClientInput {
|
|
8
|
+
readonly scopes: readonly string[];
|
|
9
|
+
|
|
10
|
+
// The form fields that the app's grant limits read on the consent page.
|
|
11
|
+
readonly consentFields?: URLSearchParams;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface TestClientAuthorization {
|
|
15
|
+
readonly accessToken: string;
|
|
16
|
+
readonly refreshToken: string;
|
|
17
|
+
readonly grantID: GrantID;
|
|
18
|
+
readonly clientID: OAuthClientID;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Drives auth.routes through a whole sign-in, with a stub WebAuthn
|
|
22
|
+
// authenticator in place of the owner's passkey: a new client, a new passkey,
|
|
23
|
+
// the authorize request, the passkey login, the consent, and the code exchange.
|
|
24
|
+
export async function authorizeTestClient(
|
|
25
|
+
auth: MCPAuth<string, unknown>,
|
|
26
|
+
input: TestClientInput,
|
|
27
|
+
): Promise<TestClientAuthorization> {
|
|
28
|
+
const signedIn = await runSignInToConsent(auth, { scopes: input.scopes });
|
|
29
|
+
|
|
30
|
+
const requester = buildTestRequester();
|
|
31
|
+
const headers = { origin: auth.issuer };
|
|
32
|
+
const consent = signedIn.consent;
|
|
33
|
+
const cookie = signedIn.cookie;
|
|
34
|
+
|
|
35
|
+
const form = new URLSearchParams(input.consentFields);
|
|
36
|
+
|
|
37
|
+
form.set('oauth_query', consent.search.slice(1));
|
|
38
|
+
form.set('decision', 'approve');
|
|
39
|
+
|
|
40
|
+
for (const scope of input.scopes) {
|
|
41
|
+
form.append('scope', scope);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const consented = await auth.routes.consent(
|
|
45
|
+
buildFormRequest(`${auth.issuer}${auth.paths.browser.consent}`, form, { ...headers, cookie }),
|
|
46
|
+
requester,
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
const callback = consented.headers.get('location');
|
|
50
|
+
const code = callback === null ? null : new URL(callback).searchParams.get('code');
|
|
51
|
+
|
|
52
|
+
if (code === null) {
|
|
53
|
+
throw new Error(`the consent did not issue a code: ${consented.status}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const exchanged = await auth.routes.token(
|
|
57
|
+
buildFormRequest(
|
|
58
|
+
`${auth.issuer}${auth.paths.machine.token}`,
|
|
59
|
+
new URLSearchParams({
|
|
60
|
+
grant_type: 'authorization_code',
|
|
61
|
+
code,
|
|
62
|
+
redirect_uri: TEST_REDIRECT_URI,
|
|
63
|
+
client_id: signedIn.clientID,
|
|
64
|
+
code_verifier: signedIn.verifier,
|
|
65
|
+
}),
|
|
66
|
+
),
|
|
67
|
+
requester,
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const tokens = await readJSONRecord(exchanged);
|
|
71
|
+
|
|
72
|
+
const accessToken = tokens['access_token'];
|
|
73
|
+
const refreshToken = tokens['refresh_token'];
|
|
74
|
+
|
|
75
|
+
if (typeof accessToken !== 'string' || typeof refreshToken !== 'string') {
|
|
76
|
+
throw new TypeError(`the token endpoint answered ${exchanged.status} with no tokens`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const grants = await auth.grants.list();
|
|
80
|
+
|
|
81
|
+
const grant = grants.find((view) => view.clientID === signedIn.clientID);
|
|
82
|
+
|
|
83
|
+
if (grant === undefined) {
|
|
84
|
+
throw new Error('the sign-in left no grant');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
accessToken,
|
|
89
|
+
refreshToken,
|
|
90
|
+
grantID: grant.grantID,
|
|
91
|
+
clientID: signedIn.clientID,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// A browser's form post to the server's own page.
|
|
2
|
+
export function buildFormRequest(
|
|
3
|
+
url: string,
|
|
4
|
+
fields: URLSearchParams,
|
|
5
|
+
headers: Readonly<Record<string, string>> = {},
|
|
6
|
+
): Request {
|
|
7
|
+
return new Request(url, {
|
|
8
|
+
method: 'POST',
|
|
9
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers },
|
|
10
|
+
body: fields,
|
|
11
|
+
});
|
|
12
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { MCPAuth } from '../types.ts';
|
|
2
|
+
import { authorizeTestClient } from './authorize-test-client.ts';
|
|
3
|
+
import { seedClient } from './seed-client.ts';
|
|
4
|
+
import { seedEnrollmentToken } from './seed-enrollment-token.ts';
|
|
5
|
+
import { seedPasskey } from './seed-passkey.ts';
|
|
6
|
+
|
|
7
|
+
export interface TestDeps {
|
|
8
|
+
readonly auth: MCPAuth<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function buildSeeder(deps: TestDeps) {
|
|
12
|
+
return {
|
|
13
|
+
client: (input?: Parameters<typeof seedClient>[1]) => seedClient(deps.auth, input),
|
|
14
|
+
enrollmentToken: () => seedEnrollmentToken(deps.auth),
|
|
15
|
+
passkey: (input: Parameters<typeof seedPasskey>[1]) => seedPasskey(deps.auth, input),
|
|
16
|
+
grant: (input: Parameters<typeof authorizeTestClient>[1]) =>
|
|
17
|
+
authorizeTestClient(deps.auth, input),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { toTagged } from '@zgeoff/std';
|
|
3
|
+
import type { PasskeyID } from '../types.ts';
|
|
4
|
+
|
|
5
|
+
// The parts of the creation and request options a browser passes to
|
|
6
|
+
// navigator.credentials that an authenticator reads.
|
|
7
|
+
interface CreationOptions {
|
|
8
|
+
readonly challenge: string;
|
|
9
|
+
readonly rp: { readonly id?: string };
|
|
10
|
+
readonly user: { readonly id: string };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface RequestOptions {
|
|
14
|
+
readonly challenge: string;
|
|
15
|
+
readonly rpId?: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// What a browser and its authenticator put in a response, each defaulting
|
|
19
|
+
// to the honest value: the page's origin as given, the RP ID the options
|
|
20
|
+
// hold, and a verified user.
|
|
21
|
+
interface Ceremony {
|
|
22
|
+
readonly origin: string;
|
|
23
|
+
readonly rpID?: string;
|
|
24
|
+
readonly userVerified?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface StubRegistration {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly rawId: string;
|
|
30
|
+
readonly type: 'public-key';
|
|
31
|
+
readonly response: {
|
|
32
|
+
readonly clientDataJSON: string;
|
|
33
|
+
readonly attestationObject: string;
|
|
34
|
+
readonly transports: readonly string[];
|
|
35
|
+
};
|
|
36
|
+
readonly clientExtensionResults: Readonly<Record<string, never>>;
|
|
37
|
+
readonly authenticatorAttachment: 'platform';
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface StubAssertion {
|
|
41
|
+
readonly id: string;
|
|
42
|
+
readonly rawId: string;
|
|
43
|
+
readonly type: 'public-key';
|
|
44
|
+
readonly response: {
|
|
45
|
+
readonly clientDataJSON: string;
|
|
46
|
+
readonly authenticatorData: string;
|
|
47
|
+
readonly signature: string;
|
|
48
|
+
readonly userHandle: string;
|
|
49
|
+
};
|
|
50
|
+
readonly clientExtensionResults: Readonly<Record<string, never>>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const FLAG_AT = 0x40;
|
|
54
|
+
|
|
55
|
+
type CBORValue = number | string | Buffer | ReadonlyMap<number | string, CBORValue>;
|
|
56
|
+
|
|
57
|
+
export function buildStubAuthenticator() {
|
|
58
|
+
const credentialID = randomBytes(16);
|
|
59
|
+
|
|
60
|
+
const keys = crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [
|
|
61
|
+
'sign',
|
|
62
|
+
'verify',
|
|
63
|
+
]);
|
|
64
|
+
|
|
65
|
+
let userHandle: string | null = null;
|
|
66
|
+
let counter = 0;
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
credentialID: toTagged<PasskeyID>(credentialID.toString('base64url')),
|
|
70
|
+
async create(options: CreationOptions, ceremony: Ceremony): Promise<StubRegistration> {
|
|
71
|
+
const pair = await keys;
|
|
72
|
+
const jwk = await crypto.subtle.exportKey('jwk', pair.publicKey);
|
|
73
|
+
|
|
74
|
+
userHandle = options.user.id;
|
|
75
|
+
|
|
76
|
+
// A COSE EC2 key: kty 2, alg -7 (ES256), crv 1 (P-256), x, y.
|
|
77
|
+
const coseKey = encodeCBOR(
|
|
78
|
+
new Map<number, CBORValue>([
|
|
79
|
+
[1, 2],
|
|
80
|
+
[3, -7],
|
|
81
|
+
[-1, 1],
|
|
82
|
+
[-2, Buffer.from(jwk.x ?? '', 'base64url')],
|
|
83
|
+
[-3, Buffer.from(jwk.y ?? '', 'base64url')],
|
|
84
|
+
]),
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
const length = Buffer.alloc(2);
|
|
88
|
+
|
|
89
|
+
length.writeUInt16BE(credentialID.length);
|
|
90
|
+
|
|
91
|
+
const authData = Buffer.concat([
|
|
92
|
+
buildAuthenticatorHeader(ceremony.rpID ?? options.rp.id ?? '', ceremony, 0, FLAG_AT),
|
|
93
|
+
Buffer.alloc(16),
|
|
94
|
+
length,
|
|
95
|
+
credentialID,
|
|
96
|
+
coseKey,
|
|
97
|
+
]);
|
|
98
|
+
|
|
99
|
+
const attestationObject = encodeCBOR(
|
|
100
|
+
new Map<string, CBORValue>([
|
|
101
|
+
['fmt', 'none'],
|
|
102
|
+
['attStmt', new Map()],
|
|
103
|
+
['authData', authData],
|
|
104
|
+
]),
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
id: credentialID.toString('base64url'),
|
|
109
|
+
rawId: credentialID.toString('base64url'),
|
|
110
|
+
type: 'public-key',
|
|
111
|
+
response: {
|
|
112
|
+
clientDataJSON: buildClientData('webauthn.create', options.challenge, ceremony),
|
|
113
|
+
attestationObject: attestationObject.toString('base64url'),
|
|
114
|
+
transports: ['internal'],
|
|
115
|
+
},
|
|
116
|
+
clientExtensionResults: {},
|
|
117
|
+
authenticatorAttachment: 'platform',
|
|
118
|
+
};
|
|
119
|
+
},
|
|
120
|
+
async signAssertion(options: RequestOptions, ceremony: Ceremony): Promise<StubAssertion> {
|
|
121
|
+
if (userHandle === null) {
|
|
122
|
+
throw new Error('the stub authenticator holds no credential yet');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const pair = await keys;
|
|
126
|
+
|
|
127
|
+
counter += 1;
|
|
128
|
+
|
|
129
|
+
const authenticatorData = buildAuthenticatorHeader(
|
|
130
|
+
ceremony.rpID ?? options.rpId ?? '',
|
|
131
|
+
ceremony,
|
|
132
|
+
counter,
|
|
133
|
+
0,
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
const clientDataJSON = buildClientData('webauthn.get', options.challenge, ceremony);
|
|
137
|
+
|
|
138
|
+
const signed = Buffer.concat([
|
|
139
|
+
authenticatorData,
|
|
140
|
+
createHash('sha256').update(Buffer.from(clientDataJSON, 'base64url')).digest(),
|
|
141
|
+
]);
|
|
142
|
+
|
|
143
|
+
const raw = await crypto.subtle.sign(
|
|
144
|
+
{ name: 'ECDSA', hash: 'SHA-256' },
|
|
145
|
+
pair.privateKey,
|
|
146
|
+
signed,
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
id: credentialID.toString('base64url'),
|
|
151
|
+
rawId: credentialID.toString('base64url'),
|
|
152
|
+
type: 'public-key',
|
|
153
|
+
response: {
|
|
154
|
+
clientDataJSON,
|
|
155
|
+
authenticatorData: authenticatorData.toString('base64url'),
|
|
156
|
+
signature: toDERSignature(Buffer.from(raw)).toString('base64url'),
|
|
157
|
+
userHandle,
|
|
158
|
+
},
|
|
159
|
+
clientExtensionResults: {},
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// The CBOR subset a COSE key and a `none` attestation need: integers,
|
|
166
|
+
// byte strings, text strings, and maps.
|
|
167
|
+
function encodeCBOR(value: CBORValue): Buffer {
|
|
168
|
+
if (typeof value === 'number') {
|
|
169
|
+
return value >= 0 ? encodeCBORHead(0, value) : encodeCBORHead(1, -1 - value);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (typeof value === 'string') {
|
|
173
|
+
const text = Buffer.from(value);
|
|
174
|
+
|
|
175
|
+
return Buffer.concat([encodeCBORHead(3, text.length), text]);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (Buffer.isBuffer(value)) {
|
|
179
|
+
return Buffer.concat([encodeCBORHead(2, value.length), value]);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return Buffer.concat([
|
|
183
|
+
encodeCBORHead(5, value.size),
|
|
184
|
+
...[...value].flatMap(([key, item]) => [encodeCBOR(key), encodeCBOR(item)]),
|
|
185
|
+
]);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function encodeCBORHead(major: number, length: number): Buffer {
|
|
189
|
+
if (length < 24) {
|
|
190
|
+
return Buffer.from([(major << 5) | length]);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (length < 256) {
|
|
194
|
+
return Buffer.from([(major << 5) | 24, length]);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const head = Buffer.alloc(3);
|
|
198
|
+
|
|
199
|
+
head.writeUInt8((major << 5) | 25);
|
|
200
|
+
head.writeUInt16BE(length, 1);
|
|
201
|
+
|
|
202
|
+
return head;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const FLAG_UP = 0x01;
|
|
206
|
+
const FLAG_UV = 0x04;
|
|
207
|
+
|
|
208
|
+
// The RP ID hash, the flags with user presence always set, and the
|
|
209
|
+
// big-endian signature counter.
|
|
210
|
+
function buildAuthenticatorHeader(
|
|
211
|
+
rpID: string,
|
|
212
|
+
ceremony: Ceremony,
|
|
213
|
+
signCount: number,
|
|
214
|
+
extraFlags: number,
|
|
215
|
+
): Buffer {
|
|
216
|
+
const flags = FLAG_UP | (ceremony.userVerified === false ? 0 : FLAG_UV) | extraFlags;
|
|
217
|
+
const count = Buffer.alloc(4);
|
|
218
|
+
|
|
219
|
+
count.writeUInt32BE(signCount);
|
|
220
|
+
|
|
221
|
+
return Buffer.concat([createHash('sha256').update(rpID).digest(), Buffer.from([flags]), count]);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function buildClientData(type: string, challenge: string, ceremony: Ceremony): string {
|
|
225
|
+
return Buffer.from(
|
|
226
|
+
JSON.stringify({ type, challenge, origin: ceremony.origin, crossOrigin: false }),
|
|
227
|
+
).toString('base64url');
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// WebCrypto signs ECDSA as r and s side by side; WebAuthn carries the
|
|
231
|
+
// signature as an ASN.1 DER sequence of two integers.
|
|
232
|
+
function toDERSignature(raw: Buffer): Buffer {
|
|
233
|
+
const integers = [raw.subarray(0, 32), raw.subarray(32)].map((part) => {
|
|
234
|
+
const start = part.findIndex((byte) => byte !== 0);
|
|
235
|
+
const trimmed = start === -1 ? Buffer.from([0]) : part.subarray(start);
|
|
236
|
+
const value = (trimmed[0] ?? 0) >= 0x80 ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed;
|
|
237
|
+
|
|
238
|
+
return Buffer.concat([Buffer.from([0x02, value.length]), value]);
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
const body = Buffer.concat(integers);
|
|
242
|
+
|
|
243
|
+
return Buffer.concat([Buffer.from([0x30, body.length]), body]);
|
|
244
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Clock } from '../types.ts';
|
|
2
|
+
|
|
3
|
+
// A clock a test moves by hand. It starts at the real time, since better-auth
|
|
4
|
+
// stamps tokens and codes from Date.now(); a test that steps past a token's
|
|
5
|
+
// life also sets the system time with bun:test.
|
|
6
|
+
export function buildStubClock(startMs: number = Date.now()): Clock & {
|
|
7
|
+
readonly setTime: (timeMs: number) => void;
|
|
8
|
+
readonly advance: (durationMs: number) => void;
|
|
9
|
+
} {
|
|
10
|
+
let time = startMs;
|
|
11
|
+
|
|
12
|
+
return {
|
|
13
|
+
now: () => time,
|
|
14
|
+
setTime: (timeMs) => {
|
|
15
|
+
time = timeMs;
|
|
16
|
+
},
|
|
17
|
+
advance: (durationMs) => {
|
|
18
|
+
time += durationMs;
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite';
|
|
2
|
+
|
|
3
|
+
// A real SQLite engine in memory. A test that needs a second connection, such
|
|
4
|
+
// as one that revokes from another process, passes a file path instead.
|
|
5
|
+
export function createTestDatabase(path = ':memory:'): Database {
|
|
6
|
+
return new Database(path, { create: true });
|
|
7
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
|
|
3
|
+
// Calls the hook with each statement the handle prepares, right before it
|
|
4
|
+
// runs. The Kysely driver prepares every statement through sqlite.query, so
|
|
5
|
+
// the hook is the exact point between two statements of the code under test.
|
|
6
|
+
export function hookSQLiteStatements(
|
|
7
|
+
sqlite: Database,
|
|
8
|
+
onStatement: (statement: string) => void,
|
|
9
|
+
): void {
|
|
10
|
+
const original = sqlite.query.bind(sqlite);
|
|
11
|
+
|
|
12
|
+
Reflect.set(sqlite, 'query', (statement: string) => {
|
|
13
|
+
onStatement(statement);
|
|
14
|
+
|
|
15
|
+
return original(statement);
|
|
16
|
+
});
|
|
17
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { authorizeTestClient } from './authorize-test-client.ts';
|
|
2
|
+
export { buildSeeder } from './build-seeder.ts';
|
|
3
|
+
export type { TestDeps } from './build-seeder.ts';
|
|
4
|
+
export { buildStubAuthenticator } from './build-stub-authenticator.ts';
|
|
5
|
+
export { buildStubClock } from './build-stub-clock.ts';
|
|
6
|
+
export { buildTestRequester } from './build-test-requester.ts';
|
|
7
|
+
export { createTestDatabase } from './create-test-database.ts';
|
|
8
|
+
export { hookSQLiteStatements } from './hook-sqlite-statements.ts';
|
|
9
|
+
export { openTestAuth } from './open-test-auth.ts';
|
|
10
|
+
export { seedClient } from './seed-client.ts';
|
|
11
|
+
export { seedEnrollmentToken } from './seed-enrollment-token.ts';
|
|
12
|
+
export { seedPasskey } from './seed-passkey.ts';
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { DEFAULT_PATHS } from '../default-paths.ts';
|
|
3
|
+
import { openMCPAuth } from '../open-mcp-auth.ts';
|
|
4
|
+
import type { GrantID, GrantLimits, MCPAuth, SecurityEvent, ServiceTokenFile } from '../types.ts';
|
|
5
|
+
import { buildStubClock } from './build-stub-clock.ts';
|
|
6
|
+
import { createTestDatabase } from './create-test-database.ts';
|
|
7
|
+
|
|
8
|
+
interface TestAuthInput<Limits> {
|
|
9
|
+
readonly database?: Database;
|
|
10
|
+
readonly grantLimits?: GrantLimits<Limits>;
|
|
11
|
+
readonly serviceTokens?: {
|
|
12
|
+
readonly prefix: string;
|
|
13
|
+
readonly file: ServiceTokenFile<'read' | 'write'>;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface TestAuth<Limits> {
|
|
18
|
+
readonly auth: MCPAuth<'read' | 'write', Limits>;
|
|
19
|
+
readonly database: Database;
|
|
20
|
+
readonly clock: ReturnType<typeof buildStubClock>;
|
|
21
|
+
|
|
22
|
+
// Every security event the core recorded, and every grant it revoked.
|
|
23
|
+
readonly events: SecurityEvent[];
|
|
24
|
+
readonly revoked: GrantID[];
|
|
25
|
+
|
|
26
|
+
// Closes the handle, then the database.
|
|
27
|
+
readonly close: () => Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// A server for one test, at https://app.example with the read and write
|
|
31
|
+
// scopes, on a fresh in-memory database unless the test passes its own.
|
|
32
|
+
export async function openTestAuth<Limits = null>(
|
|
33
|
+
input: TestAuthInput<Limits> = {},
|
|
34
|
+
): Promise<TestAuth<Limits>> {
|
|
35
|
+
const database = input.database ?? createTestDatabase();
|
|
36
|
+
const clock = buildStubClock();
|
|
37
|
+
const events: SecurityEvent[] = [];
|
|
38
|
+
const revoked: GrantID[] = [];
|
|
39
|
+
|
|
40
|
+
const auth = await openMCPAuth({
|
|
41
|
+
database,
|
|
42
|
+
origin: 'https://app.example',
|
|
43
|
+
productName: 'app',
|
|
44
|
+
scopes: ['read', 'write'],
|
|
45
|
+
paths: DEFAULT_PATHS,
|
|
46
|
+
tables: { passkey: 'app_passkey', enrollmentToken: 'app_enrollment_token' },
|
|
47
|
+
clock,
|
|
48
|
+
security: {
|
|
49
|
+
record: (event) => {
|
|
50
|
+
events.push(event);
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
onGrantRevoked: (grantID) => {
|
|
54
|
+
revoked.push(grantID);
|
|
55
|
+
},
|
|
56
|
+
...(input.grantLimits === undefined ? {} : { grantLimits: input.grantLimits }),
|
|
57
|
+
...(input.serviceTokens === undefined ? {} : { serviceTokens: input.serviceTokens }),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
auth,
|
|
62
|
+
database,
|
|
63
|
+
clock,
|
|
64
|
+
events,
|
|
65
|
+
revoked,
|
|
66
|
+
close: async () => {
|
|
67
|
+
await auth.close();
|
|
68
|
+
|
|
69
|
+
database.close();
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
const REQUEST_OPTIONS = z.object({ challenge: z.string(), rpId: z.string() });
|
|
4
|
+
|
|
5
|
+
const CREATION_OPTIONS = z.object({
|
|
6
|
+
challenge: z.string(),
|
|
7
|
+
rp: z.object({ id: z.string() }),
|
|
8
|
+
user: z.object({ id: z.string() }),
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
const SIGN_IN = z.object({ mode: z.literal('get'), options: REQUEST_OPTIONS });
|
|
12
|
+
const ENROLLMENT = z.object({ mode: z.literal('create'), options: CREATION_OPTIONS });
|
|
13
|
+
const PASSKEY_PAGE = z.discriminatedUnion('mode', [SIGN_IN, ENROLLMENT]);
|
|
14
|
+
|
|
15
|
+
export function parsePasskeyPage(html: string): z.infer<typeof PASSKEY_PAGE> {
|
|
16
|
+
const block =
|
|
17
|
+
/<script type="application\/json" id="mcp-auth-passkey">(?<json>[^<]*)<\/script>/u.exec(html)
|
|
18
|
+
?.groups?.['json'];
|
|
19
|
+
|
|
20
|
+
if (block === undefined) {
|
|
21
|
+
throw new Error('the page holds no passkey ceremony');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return PASSKEY_PAGE.parse(JSON.parse(block));
|
|
25
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { isRecord } from '@zgeoff/std';
|
|
2
|
+
|
|
3
|
+
interface JSONBody {
|
|
4
|
+
readonly json: () => Promise<unknown>;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function readJSONRecord(response: JSONBody): Promise<Record<string, unknown>> {
|
|
8
|
+
const body: unknown = await response.json();
|
|
9
|
+
|
|
10
|
+
if (!isRecord(body) || Array.isArray(body)) {
|
|
11
|
+
throw new TypeError('response body is not a JSON object');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
return body;
|
|
15
|
+
}
|