@lostgradient/mcp 0.2.5 → 0.3.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 +1 -1
- package/README.md +15 -173
- package/dist/http.d.ts +35 -0
- package/dist/http.js +251 -0
- package/dist/internal/cryptography/encryption.d.ts +108 -0
- package/dist/internal/cryptography/encryption.js +241 -0
- package/dist/internal/cryptography/hash.d.ts +72 -0
- package/dist/internal/cryptography/hash.js +233 -0
- package/dist/internal/cryptography/index.d.ts +4 -0
- package/dist/internal/cryptography/index.js +2 -0
- package/dist/oauth/canonicalize-ip-address.d.ts +0 -6
- package/dist/oauth/canonicalize-ip-address.js +113 -0
- package/dist/oauth/client-metadata-documents.d.ts +2 -22
- package/dist/oauth/client-metadata-documents.js +205 -19
- package/dist/oauth/index.d.ts +9 -213
- package/dist/oauth/index.js +6 -69
- package/dist/oauth/issuer.d.ts +103 -0
- package/dist/oauth/issuer.js +564 -0
- package/dist/oauth/postgres.d.ts +12 -0
- package/dist/oauth/postgres.js +76 -0
- package/dist/oauth/safe-public-https-fetch.d.ts +3 -5
- package/dist/oauth/safe-public-https-fetch.js +114 -0
- package/dist/oauth/security-utilities.d.ts +0 -3
- package/dist/oauth/security-utilities.js +93 -0
- package/dist/oauth-store.d.ts +108 -0
- package/dist/oauth-store.js +321 -0
- package/package.json +50 -124
- package/dist/chunk-3ek3knfm.js +0 -73
- package/dist/chunk-3rr24vhh.js +0 -28
- package/dist/chunk-6ekjtvcq.js +0 -273
- package/dist/chunk-88nhf6xt.js +0 -449
- package/dist/chunk-en76akaq.js +0 -1107
- package/dist/chunk-k6fm3cmk.js +0 -132
- package/dist/chunk-qxwd8est.js +0 -916
- package/dist/chunk-rxnyn7tf.js +0 -19
- package/dist/chunk-taxyscge.js +0 -67
- package/dist/chunk-wsnfttyg.js +0 -4
- package/dist/chunk-xcf742mf.js +0 -14
- package/dist/conformance-fixture-registration.d.ts +0 -30
- package/dist/conformance-server.d.ts +0 -1
- package/dist/conformance.d.ts +0 -43
- package/dist/env.d.ts +0 -59
- package/dist/env.js +0 -9
- package/dist/environment-schema.d.ts +0 -29
- package/dist/environment-schema.js +0 -6
- package/dist/golden-prompts.d.ts +0 -42
- package/dist/handler-context.d.ts +0 -16
- package/dist/http/authenticate.d.ts +0 -35
- package/dist/http/authorization-header.d.ts +0 -5
- package/dist/http/grant-revocation-channel.d.ts +0 -24
- package/dist/http/handler.d.ts +0 -32
- package/dist/http/index.d.ts +0 -27
- package/dist/http/index.js +0 -870
- package/dist/http/listen-inspection.d.ts +0 -11
- package/dist/http/request-context.d.ts +0 -17
- package/dist/http/responses.d.ts +0 -13
- package/dist/http/serving-layer.d.ts +0 -25
- package/dist/http/user-handler-cache.d.ts +0 -37
- package/dist/http/user-server-event-bus.d.ts +0 -35
- package/dist/index.d.ts +0 -29
- package/dist/index.js +0 -616
- package/dist/localhost-request-validation.d.ts +0 -2
- package/dist/logger.d.ts +0 -59
- package/dist/logger.js +0 -18
- package/dist/long-running-operation-support.d.ts +0 -34
- package/dist/metrics.d.ts +0 -64
- package/dist/metrics.js +0 -6
- package/dist/oauth/authorize-endpoint.d.ts +0 -5
- package/dist/oauth/client-authentication.d.ts +0 -10
- package/dist/oauth/discovery-metadata.d.ts +0 -19
- package/dist/oauth/endpoint-rate-limits.d.ts +0 -10
- package/dist/oauth/endpoint-responses.d.ts +0 -10
- package/dist/oauth/network-identity.d.ts +0 -32
- package/dist/oauth/pkce-validation.d.ts +0 -2
- package/dist/oauth/postgres/client-store.d.ts +0 -12
- package/dist/oauth/postgres/code-store.d.ts +0 -14
- package/dist/oauth/postgres/database.d.ts +0 -59
- package/dist/oauth/postgres/index.d.ts +0 -11
- package/dist/oauth/postgres/index.js +0 -616
- package/dist/oauth/postgres/schema.d.ts +0 -1476
- package/dist/oauth/postgres/token-store.d.ts +0 -16
- package/dist/oauth/postgres/transaction-store.d.ts +0 -14
- package/dist/oauth/redirect-uri-matching.d.ts +0 -2
- package/dist/oauth/registration-endpoint.d.ts +0 -2
- package/dist/oauth/request-body.d.ts +0 -14
- package/dist/oauth/revocation-endpoint.d.ts +0 -2
- package/dist/oauth/scope-utilities.d.ts +0 -15
- package/dist/oauth/stores.d.ts +0 -225
- package/dist/oauth/stores.js +0 -0
- package/dist/oauth/testing/contract-fixtures.d.ts +0 -134
- package/dist/oauth/testing/index.d.ts +0 -56
- package/dist/oauth/testing/index.js +0 -330
- package/dist/oauth/token-endpoint.d.ts +0 -2
- package/dist/oauth-scope-configuration.d.ts +0 -3
- package/dist/prompts/index.d.ts +0 -5
- package/dist/prompts/summarize.d.ts +0 -4
- package/dist/rate-limit/in-memory-sliding-window-store.d.ts +0 -3
- package/dist/rate-limit/index.d.ts +0 -23
- package/dist/rate-limit/index.js +0 -29
- package/dist/rate-limit/mcp-concurrency-limiter.d.ts +0 -26
- package/dist/rate-limit/rate-limit-response.d.ts +0 -1
- package/dist/rate-limit/redis-sliding-window-store.d.ts +0 -2
- package/dist/rate-limit/request-rate-limiter.d.ts +0 -10
- package/dist/rate-limit/sliding-window-rate-limiter.d.ts +0 -16
- package/dist/resources/index.d.ts +0 -4
- package/dist/resources/user-profile.d.ts +0 -1
- package/dist/scope-vocabulary.d.ts +0 -127
- package/dist/scopes.d.ts +0 -49
- package/dist/server.d.ts +0 -113
- package/dist/supported-scopes.d.ts +0 -25
- package/dist/sveltekit-mount-state.d.ts +0 -4
- package/dist/sveltekit-mount.d.ts +0 -43
- package/dist/sveltekit-mount.js +0 -344
- package/dist/template-registry.d.ts +0 -16
- package/dist/tool-response.d.ts +0 -100
- package/dist/tools/get-user-profile.d.ts +0 -8
- package/dist/tools/index.d.ts +0 -16
- package/dist/tools/list-audit-events.d.ts +0 -11
- package/dist/type-assertions.d.ts +0 -1
- package/dist/types/primitives.d.ts +0 -130
- package/dist/ui-extension-support.d.ts +0 -20
- package/dist/version.d.ts +0 -23
- package/dist/version.js +0 -6
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { ConditionalBatchCondition } from '@lostgradient/storage';
|
|
2
|
+
import type { VerifiedGrant } from "../http.js";
|
|
3
|
+
import { OAuthStore } from "../oauth-store.js";
|
|
4
|
+
import { type ClientMetadataDocumentFetchDependencies } from "./client-metadata-documents.js";
|
|
5
|
+
type Identity = {
|
|
6
|
+
subject: string;
|
|
7
|
+
tenant: string;
|
|
8
|
+
binding: string;
|
|
9
|
+
sessionCondition?: ConditionalBatchCondition & {
|
|
10
|
+
deadline?: number | undefined;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
type Options = {
|
|
14
|
+
issuer: string;
|
|
15
|
+
resource: string;
|
|
16
|
+
scopes: string[];
|
|
17
|
+
startingScopes: string[];
|
|
18
|
+
scopeDescriptions: Record<string, string>;
|
|
19
|
+
store: OAuthStore;
|
|
20
|
+
identity: {
|
|
21
|
+
assertStore?(store: OAuthStore): void;
|
|
22
|
+
session(request: Request): Promise<Identity | null>;
|
|
23
|
+
signIn(request: Request): Promise<Response>;
|
|
24
|
+
principalForGrant(identity: {
|
|
25
|
+
subject: string;
|
|
26
|
+
tenant: string;
|
|
27
|
+
}): Promise<{
|
|
28
|
+
delegableScopes: string[];
|
|
29
|
+
} | null>;
|
|
30
|
+
};
|
|
31
|
+
notifyGrantRevoked?: (grantId: string) => Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Dependencies for resolving and fetching a URL-form client ID metadata document.
|
|
34
|
+
* Workers should supply their DNS resolver here because they do not expose a local resolver.
|
|
35
|
+
*/
|
|
36
|
+
clientMetadataDocumentFetch?: ClientMetadataDocumentFetchDependencies;
|
|
37
|
+
};
|
|
38
|
+
type HostedProfileOptions<T extends {
|
|
39
|
+
delegableScopes: string[];
|
|
40
|
+
}> = {
|
|
41
|
+
identity: Omit<Options['identity'], 'principalForGrant'> & {
|
|
42
|
+
principalForGrant(identity: {
|
|
43
|
+
subject: string;
|
|
44
|
+
tenant: string;
|
|
45
|
+
}): Promise<T | null>;
|
|
46
|
+
};
|
|
47
|
+
stores: OAuthStore;
|
|
48
|
+
defaultScopes: string[];
|
|
49
|
+
scopeDescriptions: Record<string, string>;
|
|
50
|
+
notifyGrantRevoked?: (grantId: string) => Promise<void>;
|
|
51
|
+
clientMetadataDocumentFetch?: ClientMetadataDocumentFetchDependencies;
|
|
52
|
+
subscribeGrantRevocation?: (grantId: string, listener: () => void) => () => void;
|
|
53
|
+
};
|
|
54
|
+
type HostedProfile<T> = {
|
|
55
|
+
configure(options: {
|
|
56
|
+
origin: string;
|
|
57
|
+
resourcePath: string;
|
|
58
|
+
scopes: string[];
|
|
59
|
+
}): ReturnType<typeof createHostedOAuth> & {
|
|
60
|
+
issuer: string;
|
|
61
|
+
handle(request: Request): Promise<Response>;
|
|
62
|
+
verifyAccessToken(token: string): Promise<VerifiedGrant | null>;
|
|
63
|
+
resolvePrincipal(grant: VerifiedGrant): Promise<T | null>;
|
|
64
|
+
subscribeGrantRevocation?: (grantId: string, listener: () => void) => () => void;
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
export declare function hostedOAuth(configuration: Options): ReturnType<typeof createHostedOAuth>;
|
|
68
|
+
export declare function hostedOAuth<T extends {
|
|
69
|
+
delegableScopes: string[];
|
|
70
|
+
}>(configuration: HostedProfileOptions<T>): HostedProfile<T>;
|
|
71
|
+
declare function createHostedOAuth(configuration: Options): {
|
|
72
|
+
handle: (request: Request) => Promise<Response>;
|
|
73
|
+
verifyAccessToken: (credential: string) => Promise<{
|
|
74
|
+
issuer: string;
|
|
75
|
+
audience: string;
|
|
76
|
+
expiresAt: number;
|
|
77
|
+
subject: string;
|
|
78
|
+
grantId: string;
|
|
79
|
+
tenant: string;
|
|
80
|
+
clientId: string;
|
|
81
|
+
scopes: string[];
|
|
82
|
+
} | null>;
|
|
83
|
+
listConnectedApps: (identity: {
|
|
84
|
+
subject: string;
|
|
85
|
+
tenant: string;
|
|
86
|
+
}) => Promise<{
|
|
87
|
+
grantId: string;
|
|
88
|
+
clientId: string;
|
|
89
|
+
clientName: string;
|
|
90
|
+
resource: string;
|
|
91
|
+
approvedAt: number | null;
|
|
92
|
+
permissions: {
|
|
93
|
+
scope: string;
|
|
94
|
+
description: string;
|
|
95
|
+
available: boolean;
|
|
96
|
+
}[];
|
|
97
|
+
}[]>;
|
|
98
|
+
revokeConnectedApp: (identity: {
|
|
99
|
+
subject: string;
|
|
100
|
+
tenant: string;
|
|
101
|
+
}, grantId: string) => Promise<boolean>;
|
|
102
|
+
};
|
|
103
|
+
export {};
|
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
import { sha256HexSync, timingSafeEqualHex } from "../internal/cryptography/index.js";
|
|
2
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { OAuthStore } from "../oauth-store.js";
|
|
5
|
+
import { fetchClientIdMetadataDocument, } from "./client-metadata-documents.js";
|
|
6
|
+
import { isValidClientName, isValidRedirectUri } from "./security-utilities.js";
|
|
7
|
+
const random = () => randomBytes(32).toString('base64url');
|
|
8
|
+
const digest = (value) => sha256HexSync(value);
|
|
9
|
+
const escape = (value) => value
|
|
10
|
+
.replaceAll('&', '&')
|
|
11
|
+
.replaceAll('<', '<')
|
|
12
|
+
.replaceAll('>', '>')
|
|
13
|
+
.replaceAll('"', '"')
|
|
14
|
+
.replaceAll("'", ''');
|
|
15
|
+
const json = (payload, status = 200) => Response.json(payload, { status, headers: { 'cache-control': 'no-store' } });
|
|
16
|
+
const error = (name, status = 400) => json({ error: name }, status);
|
|
17
|
+
const loopbackHosts = ['localhost', '127.0.0.1', '[::1]'];
|
|
18
|
+
/**
|
|
19
|
+
* RFC 8252 section 7.3: a loopback redirect matches its registration with the port ignored.
|
|
20
|
+
* Every other redirect URI is an exact match.
|
|
21
|
+
*/
|
|
22
|
+
function redirectUriMatches(registered, requested) {
|
|
23
|
+
if (registered === requested)
|
|
24
|
+
return true;
|
|
25
|
+
if (!isValidRedirectUri(requested) || !isValidRedirectUri(registered))
|
|
26
|
+
return false;
|
|
27
|
+
const left = new URL(registered);
|
|
28
|
+
const right = new URL(requested);
|
|
29
|
+
return (left.protocol === 'http:' &&
|
|
30
|
+
right.protocol === 'http:' &&
|
|
31
|
+
loopbackHosts.includes(left.hostname) &&
|
|
32
|
+
left.hostname === right.hostname &&
|
|
33
|
+
left.pathname === right.pathname &&
|
|
34
|
+
left.search === right.search);
|
|
35
|
+
}
|
|
36
|
+
const registration = z.object({
|
|
37
|
+
client_name: z.string().min(1).max(200).refine(isValidClientName).default('Unknown Client'),
|
|
38
|
+
redirect_uris: z.array(z.string().max(2048).refine(isValidRedirectUri)).min(1).max(10),
|
|
39
|
+
grant_types: z
|
|
40
|
+
.array(z.enum(['authorization_code', 'refresh_token']))
|
|
41
|
+
.max(5)
|
|
42
|
+
.default(['authorization_code', 'refresh_token']),
|
|
43
|
+
response_types: z.array(z.literal('code')).max(5).default(['code']),
|
|
44
|
+
token_endpoint_auth_method: z.enum(['none', 'client_secret_post']).default('client_secret_post'),
|
|
45
|
+
application_type: z.enum(['web', 'native']).optional(),
|
|
46
|
+
});
|
|
47
|
+
async function body(request, type) {
|
|
48
|
+
if (request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== type)
|
|
49
|
+
return null;
|
|
50
|
+
if (Number(request.headers.get('content-length')) > 16384 || !request.body)
|
|
51
|
+
return null;
|
|
52
|
+
const reader = request.body.getReader();
|
|
53
|
+
const chunks = [];
|
|
54
|
+
let size = 0;
|
|
55
|
+
for (;;) {
|
|
56
|
+
const part = await reader.read();
|
|
57
|
+
if (part.done)
|
|
58
|
+
break;
|
|
59
|
+
size += part.value.length;
|
|
60
|
+
if (size > 16384) {
|
|
61
|
+
await reader.cancel();
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
chunks.push(part.value);
|
|
65
|
+
}
|
|
66
|
+
return new TextDecoder().decode(Buffer.concat(chunks));
|
|
67
|
+
}
|
|
68
|
+
function parameters(value) {
|
|
69
|
+
const result = new URLSearchParams(value);
|
|
70
|
+
for (const name of result.keys())
|
|
71
|
+
if (result.getAll(name).length !== 1)
|
|
72
|
+
return null;
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
export function hostedOAuth(configuration) {
|
|
76
|
+
if ('issuer' in configuration)
|
|
77
|
+
return createHostedOAuth(configuration);
|
|
78
|
+
const profile = {
|
|
79
|
+
stores: configuration.stores,
|
|
80
|
+
defaultScopes: [...configuration.defaultScopes],
|
|
81
|
+
scopeDescriptions: { ...configuration.scopeDescriptions },
|
|
82
|
+
...(configuration.clientMetadataDocumentFetch === undefined
|
|
83
|
+
? {}
|
|
84
|
+
: { clientMetadataDocumentFetch: { ...configuration.clientMetadataDocumentFetch } }),
|
|
85
|
+
...(configuration.notifyGrantRevoked === undefined
|
|
86
|
+
? {}
|
|
87
|
+
: { notifyGrantRevoked: configuration.notifyGrantRevoked.bind(configuration) }),
|
|
88
|
+
...(configuration.subscribeGrantRevocation === undefined
|
|
89
|
+
? {}
|
|
90
|
+
: { subscribeGrantRevocation: configuration.subscribeGrantRevocation.bind(configuration) }),
|
|
91
|
+
identity: {
|
|
92
|
+
...(configuration.identity.assertStore === undefined
|
|
93
|
+
? {}
|
|
94
|
+
: { assertStore: configuration.identity.assertStore.bind(configuration.identity) }),
|
|
95
|
+
session: configuration.identity.session.bind(configuration.identity),
|
|
96
|
+
signIn: configuration.identity.signIn.bind(configuration.identity),
|
|
97
|
+
principalForGrant: configuration.identity.principalForGrant.bind(configuration.identity),
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
configure({ origin, resourcePath, scopes, }) {
|
|
102
|
+
if (Object.keys(profile.scopeDescriptions).some((scope) => !scopes.includes(scope)) ||
|
|
103
|
+
scopes.some((scope) => !Object.hasOwn(profile.scopeDescriptions, scope)))
|
|
104
|
+
throw new TypeError('Scope descriptions must match the catalog');
|
|
105
|
+
const issuer = createHostedOAuth({
|
|
106
|
+
issuer: origin,
|
|
107
|
+
resource: new URL(resourcePath, origin).href,
|
|
108
|
+
scopes,
|
|
109
|
+
startingScopes: profile.defaultScopes,
|
|
110
|
+
scopeDescriptions: profile.scopeDescriptions,
|
|
111
|
+
store: profile.stores,
|
|
112
|
+
identity: profile.identity,
|
|
113
|
+
...(profile.clientMetadataDocumentFetch === undefined
|
|
114
|
+
? {}
|
|
115
|
+
: { clientMetadataDocumentFetch: profile.clientMetadataDocumentFetch }),
|
|
116
|
+
...(profile.notifyGrantRevoked === undefined
|
|
117
|
+
? {}
|
|
118
|
+
: { notifyGrantRevoked: profile.notifyGrantRevoked }),
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
...issuer,
|
|
122
|
+
issuer: origin,
|
|
123
|
+
...(profile.subscribeGrantRevocation === undefined
|
|
124
|
+
? {}
|
|
125
|
+
: { subscribeGrantRevocation: profile.subscribeGrantRevocation }),
|
|
126
|
+
resolvePrincipal(grant) {
|
|
127
|
+
return grant.tenant === undefined
|
|
128
|
+
? Promise.resolve(null)
|
|
129
|
+
: profile.identity.principalForGrant({
|
|
130
|
+
subject: grant.subject,
|
|
131
|
+
tenant: grant.tenant,
|
|
132
|
+
});
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function createHostedOAuth(configuration) {
|
|
139
|
+
configuration.identity.assertStore?.(configuration.store);
|
|
140
|
+
const options = {
|
|
141
|
+
...configuration,
|
|
142
|
+
scopes: [...configuration.scopes],
|
|
143
|
+
startingScopes: [...configuration.startingScopes],
|
|
144
|
+
scopeDescriptions: { ...configuration.scopeDescriptions },
|
|
145
|
+
identity: {
|
|
146
|
+
session: configuration.identity.session.bind(configuration.identity),
|
|
147
|
+
signIn: configuration.identity.signIn.bind(configuration.identity),
|
|
148
|
+
principalForGrant: configuration.identity.principalForGrant.bind(configuration.identity),
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
const issuer = new URL(options.issuer);
|
|
152
|
+
const resource = new URL(options.resource);
|
|
153
|
+
const prefix = issuer.pathname === '/' ? '' : issuer.pathname;
|
|
154
|
+
if (issuer.protocol !== 'https:' ||
|
|
155
|
+
issuer.href.replace(/\/$/, '') !== options.issuer ||
|
|
156
|
+
issuer.search ||
|
|
157
|
+
issuer.hash ||
|
|
158
|
+
issuer.username ||
|
|
159
|
+
issuer.password ||
|
|
160
|
+
resource.protocol !== 'https:' ||
|
|
161
|
+
resource.username ||
|
|
162
|
+
resource.password ||
|
|
163
|
+
resource.hash ||
|
|
164
|
+
options.scopes.some((scope) => !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)) ||
|
|
165
|
+
options.startingScopes.some((scope) => !options.scopes.includes(scope)))
|
|
166
|
+
throw new TypeError('Invalid OAuth configuration');
|
|
167
|
+
const clientFor = async (id) => {
|
|
168
|
+
const saved = await options.store.getClient(id);
|
|
169
|
+
if (saved)
|
|
170
|
+
return saved.issuer === options.issuer ? saved : null;
|
|
171
|
+
const document = await fetchClientIdMetadataDocument(id, options.clientMetadataDocumentFetch);
|
|
172
|
+
return document
|
|
173
|
+
? {
|
|
174
|
+
issuer: options.issuer,
|
|
175
|
+
clientId: document.clientId,
|
|
176
|
+
name: document.clientName,
|
|
177
|
+
redirectUris: document.redirectUris,
|
|
178
|
+
grantTypes: document.grantTypes,
|
|
179
|
+
authentication: 'none',
|
|
180
|
+
secretHash: null,
|
|
181
|
+
secretExpiresAt: null,
|
|
182
|
+
}
|
|
183
|
+
: null;
|
|
184
|
+
};
|
|
185
|
+
const authenticate = async (form) => {
|
|
186
|
+
const client = await clientFor(form.get('client_id') ?? '');
|
|
187
|
+
if (!client)
|
|
188
|
+
return null;
|
|
189
|
+
const secret = form.get('client_secret');
|
|
190
|
+
if (client.authentication === 'none')
|
|
191
|
+
return secret === null ? client : null;
|
|
192
|
+
if (!secret ||
|
|
193
|
+
!client.secretHash ||
|
|
194
|
+
(client.secretExpiresAt !== null && client.secretExpiresAt <= Date.now()))
|
|
195
|
+
return null;
|
|
196
|
+
return timingSafeEqualHex(digest(secret), client.secretHash) ? client : null;
|
|
197
|
+
};
|
|
198
|
+
const authority = (identity) => options.identity.principalForGrant({ subject: identity.subject, tenant: identity.tenant });
|
|
199
|
+
const register = async (request) => {
|
|
200
|
+
const text = await body(request, 'application/json');
|
|
201
|
+
if (text === null)
|
|
202
|
+
return error('invalid_request');
|
|
203
|
+
let input;
|
|
204
|
+
try {
|
|
205
|
+
input = JSON.parse(text);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return error('invalid_request');
|
|
209
|
+
}
|
|
210
|
+
const parsed = registration.safeParse(input);
|
|
211
|
+
if (!parsed.success ||
|
|
212
|
+
(parsed.data.application_type === 'web' &&
|
|
213
|
+
parsed.data.redirect_uris.some((uri) => new URL(uri).protocol !== 'https:')))
|
|
214
|
+
return error('invalid_client_metadata');
|
|
215
|
+
const data = parsed.data;
|
|
216
|
+
const clientId = randomUUID();
|
|
217
|
+
const secret = data.token_endpoint_auth_method === 'client_secret_post' ? random() : null;
|
|
218
|
+
const secretExpiresAt = secret
|
|
219
|
+
? Math.floor((Date.now() + 180 * 86_400_000) / 1000) * 1000
|
|
220
|
+
: null;
|
|
221
|
+
const registered = await options.store.registerClient({
|
|
222
|
+
issuer: options.issuer,
|
|
223
|
+
clientId,
|
|
224
|
+
name: data.client_name,
|
|
225
|
+
redirectUris: data.redirect_uris,
|
|
226
|
+
grantTypes: data.grant_types,
|
|
227
|
+
authentication: data.token_endpoint_auth_method,
|
|
228
|
+
secretHash: secret ? digest(secret) : null,
|
|
229
|
+
secretExpiresAt,
|
|
230
|
+
});
|
|
231
|
+
if (!registered)
|
|
232
|
+
return error('server_error', 500);
|
|
233
|
+
return json({
|
|
234
|
+
...data,
|
|
235
|
+
client_id: clientId,
|
|
236
|
+
...(secret && secretExpiresAt
|
|
237
|
+
? { client_secret: secret, client_secret_expires_at: secretExpiresAt / 1000 }
|
|
238
|
+
: {}),
|
|
239
|
+
client_id_issued_at: Math.floor(Date.now() / 1000),
|
|
240
|
+
}, 201);
|
|
241
|
+
};
|
|
242
|
+
const authorize = async (request) => {
|
|
243
|
+
const form = parameters(new URL(request.url).search.slice(1));
|
|
244
|
+
if (!form)
|
|
245
|
+
return error('invalid_request');
|
|
246
|
+
const client = await clientFor(form.get('client_id') ?? '');
|
|
247
|
+
const redirect = form.get('redirect_uri') ?? '';
|
|
248
|
+
const challenge = form.get('code_challenge') ?? '';
|
|
249
|
+
if (!client ||
|
|
250
|
+
!client.redirectUris.some((registered) => redirectUriMatches(registered, redirect)) ||
|
|
251
|
+
form.get('response_type') !== 'code' ||
|
|
252
|
+
!client.grantTypes.includes('authorization_code') ||
|
|
253
|
+
form.get('code_challenge_method') !== 'S256' ||
|
|
254
|
+
!/^[A-Za-z0-9_-]{43}$/.test(challenge) ||
|
|
255
|
+
form.get('resource') !== options.resource)
|
|
256
|
+
return error('invalid_request');
|
|
257
|
+
const session = await options.identity.session(request);
|
|
258
|
+
if (!session)
|
|
259
|
+
return options.identity.signIn(request);
|
|
260
|
+
const identity = { ...session };
|
|
261
|
+
const principal = await authority(identity);
|
|
262
|
+
if (!principal)
|
|
263
|
+
return error('access_denied', 403);
|
|
264
|
+
const requested = form.get('scope');
|
|
265
|
+
const scopes = [
|
|
266
|
+
...new Set(requested === null
|
|
267
|
+
? options.startingScopes.filter((scope) => principal.delegableScopes.includes(scope))
|
|
268
|
+
: requested.split(' ').filter(Boolean)),
|
|
269
|
+
].toSorted();
|
|
270
|
+
if (!scopes.length ||
|
|
271
|
+
scopes.some((scope) => !options.scopes.includes(scope) || !principal.delegableScopes.includes(scope)))
|
|
272
|
+
return error('invalid_scope');
|
|
273
|
+
const transaction = random();
|
|
274
|
+
const csrf = random();
|
|
275
|
+
const created = await options.store.createConsent(transaction, {
|
|
276
|
+
issuer: options.issuer,
|
|
277
|
+
client: client.clientId,
|
|
278
|
+
redirect,
|
|
279
|
+
csrf,
|
|
280
|
+
binding: identity.binding,
|
|
281
|
+
subject: identity.subject,
|
|
282
|
+
tenant: identity.tenant,
|
|
283
|
+
challenge,
|
|
284
|
+
resource: options.resource,
|
|
285
|
+
scopes,
|
|
286
|
+
state: form.get('state') ?? '',
|
|
287
|
+
expiresAt: Date.now() + 600_000,
|
|
288
|
+
});
|
|
289
|
+
if (!created)
|
|
290
|
+
return error('server_error', 500);
|
|
291
|
+
const fields = [
|
|
292
|
+
['transaction', transaction],
|
|
293
|
+
['csrf', csrf],
|
|
294
|
+
['client_id', client.clientId],
|
|
295
|
+
]
|
|
296
|
+
.map(([name, value]) => `<input type="hidden" name="${name}" value="${escape(value)}">`)
|
|
297
|
+
.join('');
|
|
298
|
+
return new Response(`<!doctype html><html><body><h1>Authorize ${escape(client.name)}</h1><p>${escape(identity.subject)} ${escape(identity.tenant)}</p><p>${escape(options.resource)}</p><ul>${scopes.map((scope) => `<li>${escape(Object.hasOwn(options.scopeDescriptions, scope) ? options.scopeDescriptions[scope] : scope)}</li>`).join('')}</ul><form method="post">${fields}<button name="decision" value="approve">Approve</button><button name="decision" value="deny">Deny</button></form></body></html>`, {
|
|
299
|
+
headers: {
|
|
300
|
+
'content-type': 'text/html; charset=utf-8',
|
|
301
|
+
'cache-control': 'no-store',
|
|
302
|
+
// Chromium applies form-action to the redirect after the form submission.
|
|
303
|
+
'content-security-policy': `default-src 'none'; form-action 'self' ${new URL(redirect).origin}; base-uri 'none'`,
|
|
304
|
+
'x-content-type-options': 'nosniff',
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
};
|
|
308
|
+
const consent = async (request) => {
|
|
309
|
+
const text = await body(request, 'application/x-www-form-urlencoded');
|
|
310
|
+
const form = text === null ? null : parameters(text);
|
|
311
|
+
const session = await options.identity.session(request);
|
|
312
|
+
if (!form || !session)
|
|
313
|
+
return error('invalid_request');
|
|
314
|
+
const identity = {
|
|
315
|
+
...session,
|
|
316
|
+
sessionCondition: session.sessionCondition && {
|
|
317
|
+
key: session.sessionCondition.key,
|
|
318
|
+
expectedValue: session.sessionCondition.expectedValue?.slice() ?? null,
|
|
319
|
+
deadline: session.sessionCondition.deadline,
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
const transaction = form.get('transaction') ?? '';
|
|
323
|
+
const binding = {
|
|
324
|
+
issuer: options.issuer,
|
|
325
|
+
client: form.get('client_id') ?? '',
|
|
326
|
+
csrf: form.get('csrf') ?? '',
|
|
327
|
+
binding: identity.binding,
|
|
328
|
+
subject: identity.subject,
|
|
329
|
+
};
|
|
330
|
+
const pending = await options.store.getConsent(transaction, binding);
|
|
331
|
+
if (!pending || pending.tenant !== identity.tenant || !pending.resource || !pending.scopes)
|
|
332
|
+
return error('invalid_request');
|
|
333
|
+
const decision = form.get('decision');
|
|
334
|
+
const destination = new URL(pending.redirect);
|
|
335
|
+
if (pending.state)
|
|
336
|
+
destination.searchParams.set('state', pending.state);
|
|
337
|
+
destination.searchParams.set('iss', options.issuer);
|
|
338
|
+
if (decision === 'deny') {
|
|
339
|
+
if (!(await options.store.denyConsent(transaction, binding, identity.sessionCondition)))
|
|
340
|
+
return error('invalid_request');
|
|
341
|
+
destination.searchParams.set('error', 'access_denied');
|
|
342
|
+
}
|
|
343
|
+
else if (decision === 'approve') {
|
|
344
|
+
const principal = await authority(identity);
|
|
345
|
+
if (!principal || pending.scopes.some((scope) => !principal.delegableScopes.includes(scope)))
|
|
346
|
+
return error('access_denied', 403);
|
|
347
|
+
const code = random();
|
|
348
|
+
if (!(await options.store.approveConsent(transaction, binding, {
|
|
349
|
+
grantId: randomUUID(),
|
|
350
|
+
code,
|
|
351
|
+
subject: identity.subject,
|
|
352
|
+
tenant: identity.tenant,
|
|
353
|
+
resource: pending.resource,
|
|
354
|
+
scopes: pending.scopes,
|
|
355
|
+
}, identity.sessionCondition)))
|
|
356
|
+
return error('invalid_request');
|
|
357
|
+
destination.searchParams.set('code', code);
|
|
358
|
+
}
|
|
359
|
+
else
|
|
360
|
+
return error('invalid_request');
|
|
361
|
+
return new Response(null, {
|
|
362
|
+
status: 302,
|
|
363
|
+
headers: { location: destination.href, 'cache-control': 'no-store' },
|
|
364
|
+
});
|
|
365
|
+
};
|
|
366
|
+
const token = async (request) => {
|
|
367
|
+
const text = await body(request, 'application/x-www-form-urlencoded');
|
|
368
|
+
const form = text === null ? null : parameters(text);
|
|
369
|
+
if (!form)
|
|
370
|
+
return error('invalid_request');
|
|
371
|
+
const client = await authenticate(form);
|
|
372
|
+
if (!client)
|
|
373
|
+
return error('invalid_client', 401);
|
|
374
|
+
const type = form.get('grant_type') ?? '';
|
|
375
|
+
if (type !== 'authorization_code' && type !== 'refresh_token')
|
|
376
|
+
return error('unsupported_grant_type');
|
|
377
|
+
if (!client.grantTypes.includes(type))
|
|
378
|
+
return error('unauthorized_client');
|
|
379
|
+
const access = random();
|
|
380
|
+
const refresh = random();
|
|
381
|
+
const now = Date.now();
|
|
382
|
+
const accessExpiresAt = now + 3_600_000;
|
|
383
|
+
const refreshExpiresAt = now + 2_592_000_000;
|
|
384
|
+
if (type === 'authorization_code') {
|
|
385
|
+
const code = await options.store.getCode(form.get('code') ?? '');
|
|
386
|
+
const grant = code ? await options.store.getGrant(code.grantId) : null;
|
|
387
|
+
const principal = grant ? await authority(grant) : null;
|
|
388
|
+
if (!grant ||
|
|
389
|
+
grant.issuer !== options.issuer ||
|
|
390
|
+
!principal ||
|
|
391
|
+
grant.scopes.some((scope) => !principal.delegableScopes.includes(scope)))
|
|
392
|
+
return error('invalid_grant');
|
|
393
|
+
const valid = await options.store.exchange({
|
|
394
|
+
issuer: options.issuer,
|
|
395
|
+
code: form.get('code') ?? '',
|
|
396
|
+
client: client.clientId,
|
|
397
|
+
redirect: form.get('redirect_uri') ?? '',
|
|
398
|
+
verifier: form.get('code_verifier') ?? '',
|
|
399
|
+
resource: form.get('resource') ?? '',
|
|
400
|
+
access,
|
|
401
|
+
refresh: client.grantTypes.includes('refresh_token') ? refresh : null,
|
|
402
|
+
accessExpiresAt,
|
|
403
|
+
refreshExpiresAt,
|
|
404
|
+
});
|
|
405
|
+
if (!valid)
|
|
406
|
+
return error('invalid_grant');
|
|
407
|
+
}
|
|
408
|
+
else if (type === 'refresh_token') {
|
|
409
|
+
const prior = form.get('refresh_token') ?? '';
|
|
410
|
+
const grant = await options.store.getRefreshGrant(prior);
|
|
411
|
+
if (!grant ||
|
|
412
|
+
grant.issuer !== options.issuer ||
|
|
413
|
+
grant.client !== client.clientId ||
|
|
414
|
+
grant.resource !== form.get('resource'))
|
|
415
|
+
return error('invalid_grant');
|
|
416
|
+
const principal = await authority(grant);
|
|
417
|
+
if (!principal)
|
|
418
|
+
return error('invalid_grant');
|
|
419
|
+
const scopes = form.has('scope')
|
|
420
|
+
? (form.get('scope') ?? '').split(' ').filter(Boolean)
|
|
421
|
+
: grant.scopes.filter((scope) => principal.delegableScopes.includes(scope));
|
|
422
|
+
if (!scopes.length || scopes.some((scope) => !principal.delegableScopes.includes(scope)))
|
|
423
|
+
return error('invalid_scope');
|
|
424
|
+
const result = await options.store.rotate({
|
|
425
|
+
issuer: options.issuer,
|
|
426
|
+
refresh: prior,
|
|
427
|
+
client: client.clientId,
|
|
428
|
+
resource: form.get('resource') ?? '',
|
|
429
|
+
access,
|
|
430
|
+
nextRefresh: refresh,
|
|
431
|
+
accessExpiresAt,
|
|
432
|
+
refreshExpiresAt,
|
|
433
|
+
scopes,
|
|
434
|
+
});
|
|
435
|
+
if (result !== 'rotated')
|
|
436
|
+
return error(result === 'scope_rejected' ? 'invalid_scope' : 'invalid_grant');
|
|
437
|
+
}
|
|
438
|
+
else
|
|
439
|
+
return error('unsupported_grant_type');
|
|
440
|
+
const grant = await options.store.getAccess(access);
|
|
441
|
+
if (!grant)
|
|
442
|
+
return error('invalid_grant');
|
|
443
|
+
return json({
|
|
444
|
+
access_token: access,
|
|
445
|
+
...(client.grantTypes.includes('refresh_token') ? { refresh_token: refresh } : {}),
|
|
446
|
+
token_type: 'Bearer',
|
|
447
|
+
expires_in: 3600,
|
|
448
|
+
scope: grant.scopes.join(' '),
|
|
449
|
+
});
|
|
450
|
+
};
|
|
451
|
+
const handle = async (request) => {
|
|
452
|
+
try {
|
|
453
|
+
const url = new URL(request.url);
|
|
454
|
+
if (request.url.length > 8192)
|
|
455
|
+
return error('invalid_request');
|
|
456
|
+
if (url.pathname === `/.well-known/oauth-authorization-server${prefix}` &&
|
|
457
|
+
request.method === 'GET')
|
|
458
|
+
return json({
|
|
459
|
+
issuer: options.issuer,
|
|
460
|
+
authorization_endpoint: `${options.issuer}/oauth/authorize`,
|
|
461
|
+
token_endpoint: `${options.issuer}/oauth/token`,
|
|
462
|
+
registration_endpoint: `${options.issuer}/oauth/register`,
|
|
463
|
+
revocation_endpoint: `${options.issuer}/oauth/revoke`,
|
|
464
|
+
response_types_supported: ['code'],
|
|
465
|
+
grant_types_supported: ['authorization_code', 'refresh_token'],
|
|
466
|
+
code_challenge_methods_supported: ['S256'],
|
|
467
|
+
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
|
|
468
|
+
scopes_supported: options.scopes,
|
|
469
|
+
client_id_metadata_document_supported: true,
|
|
470
|
+
authorization_response_iss_parameter_supported: true,
|
|
471
|
+
});
|
|
472
|
+
if (url.pathname === `${prefix}/oauth/register` && request.method === 'POST')
|
|
473
|
+
return await register(request);
|
|
474
|
+
if (url.pathname === `${prefix}/oauth/authorize` && request.method === 'GET')
|
|
475
|
+
return await authorize(request);
|
|
476
|
+
if (url.pathname === `${prefix}/oauth/authorize` && request.method === 'POST')
|
|
477
|
+
return await consent(request);
|
|
478
|
+
if (url.pathname === `${prefix}/oauth/token` && request.method === 'POST')
|
|
479
|
+
return await token(request);
|
|
480
|
+
if (url.pathname === `${prefix}/oauth/revoke` && request.method === 'POST') {
|
|
481
|
+
const text = await body(request, 'application/x-www-form-urlencoded');
|
|
482
|
+
const form = text === null ? null : parameters(text);
|
|
483
|
+
if (!form)
|
|
484
|
+
return error('invalid_request');
|
|
485
|
+
const client = await authenticate(form);
|
|
486
|
+
if (!client)
|
|
487
|
+
return error('invalid_client', 401);
|
|
488
|
+
await options.store.revokeToken(form.get('token') ?? '', options.issuer, client.clientId);
|
|
489
|
+
return json({});
|
|
490
|
+
}
|
|
491
|
+
return new Response(null, { status: 404 });
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
return error('server_error', 500);
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
const verifyAccessToken = async (credential) => {
|
|
498
|
+
const grant = await options.store.getAccess(credential);
|
|
499
|
+
if (!grant || grant.issuer !== options.issuer)
|
|
500
|
+
return null;
|
|
501
|
+
const principal = await authority(grant);
|
|
502
|
+
if (!principal || grant.scopes.some((scope) => !principal.delegableScopes.includes(scope)))
|
|
503
|
+
return null;
|
|
504
|
+
const current = await options.store.getAccess(credential);
|
|
505
|
+
if (!current ||
|
|
506
|
+
current.issuer !== grant.issuer ||
|
|
507
|
+
current.grantId !== grant.grantId ||
|
|
508
|
+
current.subject !== grant.subject ||
|
|
509
|
+
current.tenant !== grant.tenant ||
|
|
510
|
+
current.client !== grant.client ||
|
|
511
|
+
current.resource !== grant.resource ||
|
|
512
|
+
current.expiresAt !== grant.expiresAt ||
|
|
513
|
+
current.scopes.length !== grant.scopes.length ||
|
|
514
|
+
current.scopes.some((scope, index) => scope !== grant.scopes[index]))
|
|
515
|
+
return null;
|
|
516
|
+
return {
|
|
517
|
+
issuer: options.issuer,
|
|
518
|
+
audience: grant.resource,
|
|
519
|
+
expiresAt: grant.expiresAt,
|
|
520
|
+
subject: grant.subject,
|
|
521
|
+
grantId: grant.grantId,
|
|
522
|
+
tenant: grant.tenant,
|
|
523
|
+
clientId: grant.client,
|
|
524
|
+
scopes: grant.scopes,
|
|
525
|
+
};
|
|
526
|
+
};
|
|
527
|
+
const listConnectedApps = async (identity) => {
|
|
528
|
+
identity = { ...identity };
|
|
529
|
+
const principal = await authority(identity);
|
|
530
|
+
if (!principal)
|
|
531
|
+
throw new Error('Forbidden');
|
|
532
|
+
const grants = await options.store.listGrants({ issuer: options.issuer, ...identity });
|
|
533
|
+
return Promise.all(grants.map(async (grant) => {
|
|
534
|
+
const client = await clientFor(grant.client);
|
|
535
|
+
return {
|
|
536
|
+
grantId: grant.grantId,
|
|
537
|
+
clientId: grant.client,
|
|
538
|
+
clientName: client?.name && isValidClientName(client.name) ? client.name : 'Unknown Client',
|
|
539
|
+
resource: grant.resource,
|
|
540
|
+
approvedAt: grant.approvedAt,
|
|
541
|
+
permissions: grant.scopes.map((scope) => ({
|
|
542
|
+
scope,
|
|
543
|
+
description: Object.hasOwn(options.scopeDescriptions, scope)
|
|
544
|
+
? options.scopeDescriptions[scope]
|
|
545
|
+
: scope,
|
|
546
|
+
available: principal.delegableScopes.includes(scope),
|
|
547
|
+
})),
|
|
548
|
+
};
|
|
549
|
+
}));
|
|
550
|
+
};
|
|
551
|
+
const revokeConnectedApp = async (identity, grantId) => {
|
|
552
|
+
identity = { ...identity };
|
|
553
|
+
if (!(await authority(identity)))
|
|
554
|
+
throw new Error('Forbidden');
|
|
555
|
+
const revoked = await options.store.revokeOwnedGrant(grantId, {
|
|
556
|
+
issuer: options.issuer,
|
|
557
|
+
...identity,
|
|
558
|
+
});
|
|
559
|
+
if (revoked && options.notifyGrantRevoked)
|
|
560
|
+
await options.notifyGrantRevoked(grantId);
|
|
561
|
+
return revoked;
|
|
562
|
+
};
|
|
563
|
+
return { handle, verifyAccessToken, listConnectedApps, revokeConnectedApp };
|
|
564
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type PostgresStorageOptions } from '@lostgradient/storage-postgres';
|
|
2
|
+
import { OAuthStore } from "../oauth-store.js";
|
|
3
|
+
export declare function createPostgresOAuthStores(options: PostgresStorageOptions): OAuthStore & AsyncDisposable;
|
|
4
|
+
/** Cross-host revocation hints. Durable authority remains the source of truth. */
|
|
5
|
+
export declare function createPostgresGrantRevocationChannel(options: {
|
|
6
|
+
url: string;
|
|
7
|
+
issuer: string;
|
|
8
|
+
}): Promise<{
|
|
9
|
+
publish(grantId: string): Promise<void>;
|
|
10
|
+
subscribe(grantId: string, callback: () => void): () => void;
|
|
11
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
12
|
+
}>;
|