@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,116 @@
|
|
|
1
|
+
import type { RegistrationResponseJSON } from '@simplewebauthn/server';
|
|
2
|
+
import { verifyRegistrationResponse } from '@simplewebauthn/server';
|
|
3
|
+
import { toTagged } from '@zgeoff/std';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import type { PasskeyID } from '../types.ts';
|
|
6
|
+
|
|
7
|
+
interface RegistrationCheck {
|
|
8
|
+
// The credential JSON the enrollment page posted.
|
|
9
|
+
readonly credential: string;
|
|
10
|
+
|
|
11
|
+
// The challenge the page was given, which the caller has already taken.
|
|
12
|
+
readonly challenge: string;
|
|
13
|
+
readonly origin: string;
|
|
14
|
+
readonly rpID: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface RegisteredPasskey {
|
|
18
|
+
readonly id: PasskeyID;
|
|
19
|
+
readonly publicKey: Uint8Array;
|
|
20
|
+
readonly counter: number;
|
|
21
|
+
readonly transports: readonly string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function verifyPasskeyRegistration(
|
|
25
|
+
check: RegistrationCheck,
|
|
26
|
+
): Promise<RegisteredPasskey | null> {
|
|
27
|
+
const response = parseRegistration(check.credential);
|
|
28
|
+
|
|
29
|
+
if (response === null) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const verified = await verifyRegistrationResponse({
|
|
35
|
+
response,
|
|
36
|
+
expectedChallenge: check.challenge,
|
|
37
|
+
expectedOrigin: check.origin,
|
|
38
|
+
expectedRPID: check.rpID,
|
|
39
|
+
expectedType: 'webauthn.create',
|
|
40
|
+
requireUserVerification: true,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
if (!verified.verified || !verified.registrationInfo.userVerified) {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const credential = verified.registrationInfo.credential;
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
id: toTagged<PasskeyID>(credential.id),
|
|
51
|
+
publicKey: credential.publicKey,
|
|
52
|
+
counter: credential.counter,
|
|
53
|
+
transports: response.response.transports ?? [],
|
|
54
|
+
};
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const TRANSPORTS: ReadonlySet<string> = new Set([
|
|
61
|
+
'ble',
|
|
62
|
+
'cable',
|
|
63
|
+
'hybrid',
|
|
64
|
+
'internal',
|
|
65
|
+
'nfc',
|
|
66
|
+
'smart-card',
|
|
67
|
+
'usb',
|
|
68
|
+
]);
|
|
69
|
+
|
|
70
|
+
const REGISTRATION_REPLY = z.object({
|
|
71
|
+
clientDataJSON: z.string(),
|
|
72
|
+
attestationObject: z.string(),
|
|
73
|
+
transports: z.string().array().optional(),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const REGISTRATION = z.object({
|
|
77
|
+
id: z.string().min(1),
|
|
78
|
+
rawId: z.string().min(1),
|
|
79
|
+
type: z.literal('public-key'),
|
|
80
|
+
response: REGISTRATION_REPLY,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
// The posted JSON when it has the shape of a registration response, keeping
|
|
84
|
+
// only the transports WebAuthn defines, else null; the verifier checks
|
|
85
|
+
// every value.
|
|
86
|
+
function parseRegistration(credential: string): RegistrationResponseJSON | null {
|
|
87
|
+
let parsed: unknown;
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
parsed = JSON.parse(credential);
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const result = REGISTRATION.safeParse(parsed);
|
|
96
|
+
|
|
97
|
+
if (!result.success) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const transports = (result.data.response.transports ?? []).filter((transport) =>
|
|
102
|
+
TRANSPORTS.has(transport),
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
id: result.data.id,
|
|
107
|
+
rawId: result.data.rawId,
|
|
108
|
+
type: result.data.type,
|
|
109
|
+
response: {
|
|
110
|
+
clientDataJSON: result.data.response.clientDataJSON,
|
|
111
|
+
attestationObject: result.data.response.attestationObject,
|
|
112
|
+
transports,
|
|
113
|
+
},
|
|
114
|
+
clientExtensionResults: {},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Store } from '../store/open-store.ts';
|
|
2
|
+
import type { PasskeyID } from '../types.ts';
|
|
3
|
+
import { readPasskeyRows } from './read-passkey-rows.ts';
|
|
4
|
+
|
|
5
|
+
interface SessionPasskey {
|
|
6
|
+
// The session a passkey sign-in just created.
|
|
7
|
+
readonly sessionID: string;
|
|
8
|
+
|
|
9
|
+
// The passkey whose assertion signed the owner in.
|
|
10
|
+
readonly passkeyID: PasskeyID;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// A passkey removal that committed after the assertion verified and before the
|
|
14
|
+
// session existed deleted no session, so the session carries on only while the
|
|
15
|
+
// passkey that signed is still enrolled.
|
|
16
|
+
export async function verifySessionPasskey(store: Store, check: SessionPasskey): Promise<boolean> {
|
|
17
|
+
try {
|
|
18
|
+
return await store.db.transaction().execute(async (trx) => {
|
|
19
|
+
const passkeys = await readPasskeyRows(trx, store.options.tables.passkey, check.passkeyID);
|
|
20
|
+
|
|
21
|
+
const session = await trx
|
|
22
|
+
.selectFrom('session')
|
|
23
|
+
.select('id')
|
|
24
|
+
.where('id', '=', check.sessionID)
|
|
25
|
+
.executeTakeFirst();
|
|
26
|
+
|
|
27
|
+
if (passkeys.length > 0 && session !== undefined) {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
await trx.deleteFrom('session').where('id', '=', check.sessionID).execute();
|
|
32
|
+
|
|
33
|
+
return false;
|
|
34
|
+
});
|
|
35
|
+
} catch {
|
|
36
|
+
// A transaction that fails, such as one a concurrent write keeps busy,
|
|
37
|
+
// still removes the session.
|
|
38
|
+
await store.db.deleteFrom('session').where('id', '=', check.sessionID).execute();
|
|
39
|
+
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { answerEnrollRequest } from '../passkeys/answer-enroll-request.ts';
|
|
2
|
+
import { answerAuthorizeRequest } from '../sign-in/answer-authorize-request.ts';
|
|
3
|
+
import { answerConsentRequest } from '../sign-in/answer-consent-request.ts';
|
|
4
|
+
import { answerLoginRequest } from '../sign-in/answer-login-request.ts';
|
|
5
|
+
import type { RouteContext } from '../sign-in/route-context.ts';
|
|
6
|
+
import { answerErrorRequest } from '../tokens/answer-error-request.ts';
|
|
7
|
+
import { answerMetadataRequest } from '../tokens/answer-metadata-request.ts';
|
|
8
|
+
import { answerRevokeRequest } from '../tokens/answer-revoke-request.ts';
|
|
9
|
+
import { answerTokenRequest } from '../tokens/answer-token-request.ts';
|
|
10
|
+
import type { MCPAuthRoutes } from '../types.ts';
|
|
11
|
+
import { withFormOrigin } from './with-form-origin.ts';
|
|
12
|
+
|
|
13
|
+
export function buildRoutes(ctx: RouteContext): MCPAuthRoutes {
|
|
14
|
+
return {
|
|
15
|
+
authorize: (request, requester) => answerAuthorizeRequest(ctx, request, requester),
|
|
16
|
+
login: withFormOrigin(ctx.origin, (request, requester) =>
|
|
17
|
+
answerLoginRequest(ctx, request, requester),
|
|
18
|
+
),
|
|
19
|
+
enroll: withFormOrigin(ctx.origin, (request, requester) =>
|
|
20
|
+
answerEnrollRequest(ctx, request, requester),
|
|
21
|
+
),
|
|
22
|
+
consent: withFormOrigin(ctx.origin, (request, requester) =>
|
|
23
|
+
answerConsentRequest(ctx, request, requester),
|
|
24
|
+
),
|
|
25
|
+
error: (request) => Promise.resolve(answerErrorRequest(ctx, request)),
|
|
26
|
+
token: (request, requester) => answerTokenRequest(ctx, request, requester),
|
|
27
|
+
revoke: (request) => answerRevokeRequest(ctx, request),
|
|
28
|
+
authorizationServerMetadata: () => answerMetadataRequest(ctx, 'authorization-server'),
|
|
29
|
+
resourceMetadata: () => answerMetadataRequest(ctx, 'resource'),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Requester } from '../types.ts';
|
|
2
|
+
import { buildPageResponse } from '../utils/build-page-response.ts';
|
|
3
|
+
|
|
4
|
+
type Route = (request: Request, requester: Requester) => Promise<Response>;
|
|
5
|
+
|
|
6
|
+
// A form posts from the server's own pages, so a post with no Origin header or
|
|
7
|
+
// another one is a forged form.
|
|
8
|
+
export function withFormOrigin(origin: string, route: Route): Route {
|
|
9
|
+
return (request, requester) => {
|
|
10
|
+
if (request.method === 'POST' && request.headers.get('origin') !== origin) {
|
|
11
|
+
return Promise.resolve(
|
|
12
|
+
buildPageResponse(403, { message: 'The form came from an unexpected origin.' }),
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
return route(request, requester);
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import type { Access, ServiceTokenFile } from '../types.ts';
|
|
3
|
+
|
|
4
|
+
interface StoredToken<Scope extends string> {
|
|
5
|
+
readonly digest: Buffer;
|
|
6
|
+
readonly access: Extract<Access<Scope, never>, { kind: 'service' }>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface ServiceTokenVerifier<Scope extends string> {
|
|
10
|
+
// The access a service token grants, or null for any other value.
|
|
11
|
+
readonly verify: (token: string) => StoredToken<Scope>['access'] | null;
|
|
12
|
+
|
|
13
|
+
// The scopes of a service client, or null for an ID the file does not list.
|
|
14
|
+
readonly findScopes: (clientID: string) => readonly Scope[] | null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Only the digests of the tokens stay in memory.
|
|
18
|
+
export function buildServiceTokenVerifier<Scope extends string>(
|
|
19
|
+
file: ServiceTokenFile<Scope>,
|
|
20
|
+
): ServiceTokenVerifier<Scope> {
|
|
21
|
+
const stored: StoredToken<Scope>[] = file.clients.flatMap((client) => {
|
|
22
|
+
const clientID: `service:${string}` = `service:${client.name}`;
|
|
23
|
+
|
|
24
|
+
const access: StoredToken<Scope>['access'] = {
|
|
25
|
+
kind: 'service',
|
|
26
|
+
clientID,
|
|
27
|
+
clientName: clientID,
|
|
28
|
+
scopes: client.scopes,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
return client.tokens.map((token) => ({ digest: toDigest(token), access }));
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
verify: (token) => {
|
|
36
|
+
const presented = toDigest(token);
|
|
37
|
+
let match: StoredToken<Scope>['access'] | null = null;
|
|
38
|
+
|
|
39
|
+
// Every stored token is compared, so the time taken does not say which
|
|
40
|
+
// one matched.
|
|
41
|
+
for (const entry of stored) {
|
|
42
|
+
if (timingSafeEqual(presented, entry.digest)) {
|
|
43
|
+
match = entry.access;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return match;
|
|
48
|
+
},
|
|
49
|
+
findScopes: (clientID) =>
|
|
50
|
+
stored.find((entry) => entry.access.clientID === clientID)?.access.scopes ?? null,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function toDigest(token: string): Buffer {
|
|
55
|
+
return createHash('sha256').update(token).digest();
|
|
56
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import type { ParsedServiceTokenFile } from '../types.ts';
|
|
3
|
+
|
|
4
|
+
interface ServiceTokenRules<Scope extends string> {
|
|
5
|
+
// Every service token starts with this, so a bearer is routed to the token
|
|
6
|
+
// file or to the database by its first characters.
|
|
7
|
+
readonly prefix: string;
|
|
8
|
+
readonly scopes: readonly Scope[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// None of these messages holds the value it judges, because a value in the
|
|
12
|
+
// file may be a token.
|
|
13
|
+
const NAME_MESSAGE = 'a client name must match [a-z][a-z0-9-]{0,31}';
|
|
14
|
+
const NameSchema = z.string().regex(/^[a-z][a-z0-9-]{0,31}$/u, NAME_MESSAGE);
|
|
15
|
+
|
|
16
|
+
export function parseServiceTokenFile<Scope extends string>(
|
|
17
|
+
text: string,
|
|
18
|
+
rules: ServiceTokenRules<Scope>,
|
|
19
|
+
): ParsedServiceTokenFile<Scope> {
|
|
20
|
+
let raw: unknown;
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
raw = JSON.parse(text);
|
|
24
|
+
} catch {
|
|
25
|
+
// The parser's own message quotes the text.
|
|
26
|
+
return { ok: false, reason: 'the file is not valid JSON' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const tokenMessage = `a token must be ${rules.prefix} followed by 32 or more of A-Z, a-z, 0-9, _ and -`;
|
|
30
|
+
|
|
31
|
+
const tokenPattern = new RegExp(`^${escapePattern(rules.prefix)}[A-Za-z0-9_-]{32,}$`, 'u');
|
|
32
|
+
|
|
33
|
+
const ClientSchema = z.strictObject({
|
|
34
|
+
scopes: z
|
|
35
|
+
.array(
|
|
36
|
+
z
|
|
37
|
+
.string()
|
|
38
|
+
.refine((scope): scope is Scope => rules.scopes.some((known) => known === scope), {
|
|
39
|
+
message: 'a scope must be one the server knows',
|
|
40
|
+
}),
|
|
41
|
+
)
|
|
42
|
+
.min(1, 'must name at least one scope'),
|
|
43
|
+
tokens: z
|
|
44
|
+
.array(z.string().regex(tokenPattern, tokenMessage))
|
|
45
|
+
.min(1, 'must hold 1 or 2 tokens')
|
|
46
|
+
.max(2, 'must hold 1 or 2 tokens'),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const FileSchema = z.strictObject({
|
|
50
|
+
resource: z.string().min(1, 'must be the resource URL the server serves'),
|
|
51
|
+
clients: z
|
|
52
|
+
.record(NameSchema, ClientSchema)
|
|
53
|
+
.refine((clients) => Object.keys(clients).length > 0, 'must name at least one client'),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const parsed = FileSchema.safeParse(raw);
|
|
57
|
+
|
|
58
|
+
if (!parsed.success) {
|
|
59
|
+
return { ok: false, reason: parsed.error.issues.map((issue) => formatIssue(issue)).join('; ') };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const clients = Object.entries(parsed.data.clients).map(([name, client]) => ({
|
|
63
|
+
name,
|
|
64
|
+
scopes: [...new Set(client.scopes)],
|
|
65
|
+
tokens: client.tokens,
|
|
66
|
+
}));
|
|
67
|
+
|
|
68
|
+
const tokens = clients.flatMap((client) => client.tokens);
|
|
69
|
+
|
|
70
|
+
if (new Set(tokens).size !== tokens.length) {
|
|
71
|
+
return { ok: false, reason: 'the same token appears more than once' };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return { ok: true, file: { resource: parsed.data.resource, clients } };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function escapePattern(text: string): string {
|
|
78
|
+
return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, String.raw`\$&`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function formatIssue(issue: z.core.$ZodIssue): string {
|
|
82
|
+
// A rejected key may be a misplaced token, so the message leaves it out.
|
|
83
|
+
if (issue.code === 'unrecognized_keys') {
|
|
84
|
+
return `${formatPath(issue.path)}has a field the file does not take`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (issue.code === 'invalid_key') {
|
|
88
|
+
return NAME_MESSAGE;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return `${formatPath(issue.path)}${issue.message}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function formatPath(path: readonly PropertyKey[]): string {
|
|
95
|
+
if (path.length === 0) {
|
|
96
|
+
return 'the file: ';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const text = path
|
|
100
|
+
.map((segment) => (typeof segment === 'number' ? `[${segment}]` : `.${String(segment)}`))
|
|
101
|
+
.join('');
|
|
102
|
+
|
|
103
|
+
return `${text.replace(/^\./u, '')}: `;
|
|
104
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { toTagged } from '@zgeoff/std';
|
|
2
|
+
import type { OAuthClientID, Requester } from '../types.ts';
|
|
3
|
+
import { buildPageResponse } from '../utils/build-page-response.ts';
|
|
4
|
+
import { readStoredClientName } from './read-stored-client-name.ts';
|
|
5
|
+
import type { RouteContext } from './route-context.ts';
|
|
6
|
+
|
|
7
|
+
export async function answerAuthorizeRequest(
|
|
8
|
+
ctx: RouteContext,
|
|
9
|
+
request: Request,
|
|
10
|
+
requester: Requester,
|
|
11
|
+
): Promise<Response> {
|
|
12
|
+
const url = new URL(request.url);
|
|
13
|
+
const params = new URLSearchParams(url.searchParams);
|
|
14
|
+
|
|
15
|
+
// Every sign-in asks for a fresh passkey login and the consent page, whatever
|
|
16
|
+
// session or consent the browser kept.
|
|
17
|
+
params.set('prompt', 'login consent');
|
|
18
|
+
|
|
19
|
+
const asked = (params.get('scope') ?? '').split(' ').filter((item) => item !== '');
|
|
20
|
+
|
|
21
|
+
params.set(
|
|
22
|
+
'scope',
|
|
23
|
+
[...new Set([...(asked.length === 0 ? ctx.scopes : asked), 'offline_access'])].join(' '),
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
if (!params.has('resource')) {
|
|
27
|
+
params.set('resource', ctx.resource);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const response = await ctx.store.auth.handler(
|
|
31
|
+
new Request(`${ctx.origin}/oauth2/authorize?${params.toString()}`, {
|
|
32
|
+
headers: { accept: 'text/html' },
|
|
33
|
+
}),
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
const location = response.headers.get('location');
|
|
37
|
+
const target = location === null ? null : new URL(location, ctx.origin);
|
|
38
|
+
|
|
39
|
+
if (
|
|
40
|
+
target === null ||
|
|
41
|
+
target.origin !== ctx.origin ||
|
|
42
|
+
target.pathname !== ctx.paths.browser.login
|
|
43
|
+
) {
|
|
44
|
+
await recordInvalidRequest(ctx, { url, requester, target });
|
|
45
|
+
|
|
46
|
+
return response;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const clientID = toTagged<OAuthClientID>(target.searchParams.get('client_id') ?? '');
|
|
50
|
+
const redirectURI = target.searchParams.get('redirect_uri') ?? '';
|
|
51
|
+
|
|
52
|
+
const clientName = await readStoredClientName(ctx.store, clientID);
|
|
53
|
+
|
|
54
|
+
const context = { path: url.pathname, requester, client: { id: clientID, name: clientName } };
|
|
55
|
+
|
|
56
|
+
const signIn = ctx.signIns.createPending({
|
|
57
|
+
key: target.search.slice(1),
|
|
58
|
+
clientID,
|
|
59
|
+
clientName,
|
|
60
|
+
redirectURI,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
if (signIn === null) {
|
|
64
|
+
ctx.security.record({
|
|
65
|
+
kind: 'authorize_started',
|
|
66
|
+
outcome: 'rejected',
|
|
67
|
+
reason: 'rate_limited',
|
|
68
|
+
...context,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
return buildPageResponse(429, {
|
|
72
|
+
message: 'Too many sign-ins started in the last minute. Wait a minute, then start again.',
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
ctx.security.record({
|
|
77
|
+
kind: 'authorize_started',
|
|
78
|
+
outcome: 'accepted',
|
|
79
|
+
...context,
|
|
80
|
+
correlationID: signIn.correlationID,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
return response;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
interface InvalidRequest {
|
|
87
|
+
readonly url: URL;
|
|
88
|
+
readonly requester: Requester;
|
|
89
|
+
readonly target: URL | null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// The better-auth error codes an `authorize_invalid` event may hold; any other
|
|
93
|
+
// code becomes `other`.
|
|
94
|
+
const AUTHORIZE_ERRORS: ReadonlySet<string> = new Set([
|
|
95
|
+
'invalid_client',
|
|
96
|
+
'client_disabled',
|
|
97
|
+
'invalid_redirect',
|
|
98
|
+
'unauthorized_client',
|
|
99
|
+
'unsupported_response_type',
|
|
100
|
+
'invalid_request',
|
|
101
|
+
'invalid_scope',
|
|
102
|
+
'invalid_target',
|
|
103
|
+
]);
|
|
104
|
+
|
|
105
|
+
// The event holds the client's id and name only for a client the core holds.
|
|
106
|
+
async function recordInvalidRequest(ctx: RouteContext, invalid: InvalidRequest): Promise<void> {
|
|
107
|
+
const code = invalid.target?.searchParams.get('error') ?? null;
|
|
108
|
+
const clientParam = invalid.url.searchParams.get('client_id');
|
|
109
|
+
const clientID = clientParam === null ? null : toTagged<OAuthClientID>(clientParam);
|
|
110
|
+
|
|
111
|
+
const stored =
|
|
112
|
+
clientID === null
|
|
113
|
+
? null
|
|
114
|
+
: await ctx.store.db
|
|
115
|
+
.selectFrom('oauthClient')
|
|
116
|
+
.select('clientId')
|
|
117
|
+
.where('clientId', '=', clientID)
|
|
118
|
+
.executeTakeFirst();
|
|
119
|
+
|
|
120
|
+
const name =
|
|
121
|
+
clientID === null || stored === null || stored === undefined
|
|
122
|
+
? null
|
|
123
|
+
: await readStoredClientName(ctx.store, clientID);
|
|
124
|
+
|
|
125
|
+
ctx.security.record({
|
|
126
|
+
kind: 'authorize_invalid',
|
|
127
|
+
outcome: 'rejected',
|
|
128
|
+
reason: code !== null && AUTHORIZE_ERRORS.has(code) ? code : 'other',
|
|
129
|
+
path: invalid.url.pathname,
|
|
130
|
+
requester: invalid.requester,
|
|
131
|
+
...(clientID === null || name === null ? {} : { client: { id: clientID, name } }),
|
|
132
|
+
});
|
|
133
|
+
}
|