@zgeoff/mcp-auth 0.0.0-stage → 0.0.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 +55 -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/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 +62 -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/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,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
|
+
}
|
|
@@ -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
|
+
}
|