@atcute/oauth-browser-client 1.0.4 → 1.0.6
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/README.md +17 -4
- package/dist/resolvers.js +4 -1
- package/dist/resolvers.js.map +1 -1
- package/dist/utils/strings.d.ts +1 -0
- package/dist/utils/strings.js +17 -0
- package/dist/utils/strings.js.map +1 -1
- package/lib/agents/exchange.ts +115 -0
- package/lib/agents/server-agent.ts +149 -0
- package/lib/agents/sessions.ts +142 -0
- package/lib/agents/user-agent.ts +99 -0
- package/lib/constants.ts +1 -0
- package/lib/dpop.ts +154 -0
- package/lib/environment.ts +27 -0
- package/lib/errors.ts +76 -0
- package/lib/index.ts +17 -0
- package/lib/resolvers.ts +225 -0
- package/lib/store/db.ts +184 -0
- package/lib/types/client.ts +82 -0
- package/lib/types/dpop.ts +7 -0
- package/lib/types/identity.ts +7 -0
- package/lib/types/par.ts +4 -0
- package/lib/types/server.ts +67 -0
- package/lib/types/store.ts +6 -0
- package/lib/types/token.ts +46 -0
- package/lib/utils/misc.ts +14 -0
- package/lib/utils/response.ts +3 -0
- package/lib/utils/runtime.ts +55 -0
- package/lib/utils/strings.ts +24 -0
- package/package.json +8 -4
package/lib/dpop.ts
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { nanoid } from 'nanoid/non-secure';
|
|
2
|
+
|
|
3
|
+
import { database } from './environment.js';
|
|
4
|
+
import type { DPoPKey } from './types/dpop.js';
|
|
5
|
+
import { extractContentType } from './utils/response.js';
|
|
6
|
+
import { encoder, fromBase64Url, toBase64Url, toSha256 } from './utils/runtime.js';
|
|
7
|
+
|
|
8
|
+
const ES256_ALG = { name: 'ECDSA', namedCurve: 'P-256' } as const;
|
|
9
|
+
|
|
10
|
+
export const createES256Key = async (): Promise<DPoPKey> => {
|
|
11
|
+
const pair = await crypto.subtle.generateKey(ES256_ALG, true, ['sign', 'verify']);
|
|
12
|
+
|
|
13
|
+
const key = await crypto.subtle.exportKey('pkcs8', pair.privateKey);
|
|
14
|
+
const { ext: _ext, key_ops: _key_opts, ...jwk } = await crypto.subtle.exportKey('jwk', pair.publicKey);
|
|
15
|
+
|
|
16
|
+
return {
|
|
17
|
+
typ: 'ES256',
|
|
18
|
+
key: toBase64Url(new Uint8Array(key)),
|
|
19
|
+
jwt: toBase64Url(encoder.encode(JSON.stringify({ typ: 'dpop+jwt', alg: 'ES256', jwk: jwk }))),
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export const createDPoPSignage = (issuer: string, dpopKey: DPoPKey) => {
|
|
24
|
+
const headerString = dpopKey.jwt;
|
|
25
|
+
const keyPromise = crypto.subtle.importKey('pkcs8', fromBase64Url(dpopKey.key), ES256_ALG, true, ['sign']);
|
|
26
|
+
|
|
27
|
+
const constructPayload = (
|
|
28
|
+
method: string,
|
|
29
|
+
url: string,
|
|
30
|
+
nonce: string | undefined,
|
|
31
|
+
ath: string | undefined,
|
|
32
|
+
) => {
|
|
33
|
+
const now = (Date.now() / 1_000) | 0;
|
|
34
|
+
|
|
35
|
+
const payload = {
|
|
36
|
+
iss: issuer,
|
|
37
|
+
iat: now,
|
|
38
|
+
// This seems fine, we can remake the request if it fails.
|
|
39
|
+
jti: nanoid(12),
|
|
40
|
+
htm: method,
|
|
41
|
+
htu: url,
|
|
42
|
+
nonce: nonce,
|
|
43
|
+
ath: ath,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
return toBase64Url(encoder.encode(JSON.stringify(payload)));
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
return async (method: string, url: string, nonce: string | undefined, ath: string | undefined) => {
|
|
50
|
+
const payloadString = constructPayload(method, url, nonce, ath);
|
|
51
|
+
|
|
52
|
+
const signed = await crypto.subtle.sign(
|
|
53
|
+
{ name: 'ECDSA', hash: { name: 'SHA-256' } },
|
|
54
|
+
await keyPromise,
|
|
55
|
+
encoder.encode(headerString + '.' + payloadString),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
const signatureString = toBase64Url(new Uint8Array(signed));
|
|
59
|
+
|
|
60
|
+
return headerString + '.' + payloadString + '.' + signatureString;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const createDPoPFetch = (issuer: string, dpopKey: DPoPKey, isAuthServer?: boolean): typeof fetch => {
|
|
65
|
+
const nonces = database.dpopNonces;
|
|
66
|
+
const sign = createDPoPSignage(issuer, dpopKey);
|
|
67
|
+
|
|
68
|
+
return async (input, init) => {
|
|
69
|
+
const request: Request = init == null && input instanceof Request ? input : new Request(input, init);
|
|
70
|
+
|
|
71
|
+
const authorizationHeader = request.headers.get('authorization');
|
|
72
|
+
const ath = authorizationHeader?.startsWith('DPoP ')
|
|
73
|
+
? await toSha256(authorizationHeader.slice(5))
|
|
74
|
+
: undefined;
|
|
75
|
+
|
|
76
|
+
const { method, url } = request;
|
|
77
|
+
const { origin } = new URL(url);
|
|
78
|
+
|
|
79
|
+
let initNonce: string | undefined;
|
|
80
|
+
try {
|
|
81
|
+
initNonce = nonces.get(origin);
|
|
82
|
+
} catch {
|
|
83
|
+
// Ignore get errors, we will just not send a nonce
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const initProof = await sign(method, url, initNonce, ath);
|
|
87
|
+
request.headers.set('dpop', initProof);
|
|
88
|
+
|
|
89
|
+
const initResponse = await fetch(request);
|
|
90
|
+
|
|
91
|
+
const nextNonce = initResponse.headers.get('dpop-nonce');
|
|
92
|
+
if (!nextNonce || nextNonce === initNonce) {
|
|
93
|
+
// No nonce was returned or it is the same as the one we sent. No need to
|
|
94
|
+
// update the nonce store, or retry the request.
|
|
95
|
+
return initResponse;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Store the fresh nonce for future requests
|
|
99
|
+
try {
|
|
100
|
+
nonces.set(origin, nextNonce);
|
|
101
|
+
} catch {
|
|
102
|
+
// Ignore set errors
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const shouldRetry = await isUseDpopNonceError(initResponse, isAuthServer);
|
|
106
|
+
if (!shouldRetry) {
|
|
107
|
+
// Not a "use_dpop_nonce" error, so there is no need to retry
|
|
108
|
+
return initResponse;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// If the input stream was already consumed, we cannot retry the request. A
|
|
112
|
+
// solution would be to clone() the request but that would bufferize the
|
|
113
|
+
// entire stream in memory which can lead to memory starvation. Instead, we
|
|
114
|
+
// will return the original response and let the calling code handle retries.
|
|
115
|
+
|
|
116
|
+
if (input === request || init?.body instanceof ReadableStream) {
|
|
117
|
+
return initResponse;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const nextProof = await sign(method, url, nextNonce, ath);
|
|
121
|
+
const nextRequest = new Request(input, init);
|
|
122
|
+
nextRequest.headers.set('dpop', nextProof);
|
|
123
|
+
|
|
124
|
+
return await fetch(nextRequest);
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const isUseDpopNonceError = async (response: Response, isAuthServer?: boolean): Promise<boolean> => {
|
|
129
|
+
// https://datatracker.ietf.org/doc/html/rfc6750#section-3
|
|
130
|
+
// https://datatracker.ietf.org/doc/html/rfc9449#name-resource-server-provided-no
|
|
131
|
+
if (isAuthServer === undefined || isAuthServer === false) {
|
|
132
|
+
if (response.status === 401) {
|
|
133
|
+
const wwwAuth = response.headers.get('www-authenticate');
|
|
134
|
+
if (wwwAuth?.startsWith('DPoP')) {
|
|
135
|
+
return wwwAuth.includes('error="use_dpop_nonce"');
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// https://datatracker.ietf.org/doc/html/rfc9449#name-authorization-server-provid
|
|
141
|
+
if (isAuthServer === undefined || isAuthServer === true) {
|
|
142
|
+
if (response.status === 400 && extractContentType(response.headers) === 'application/json') {
|
|
143
|
+
try {
|
|
144
|
+
const json = await response.clone().json();
|
|
145
|
+
return typeof json === 'object' && json?.['error'] === 'use_dpop_nonce';
|
|
146
|
+
} catch {
|
|
147
|
+
// Response too big (to be "use_dpop_nonce" error) or invalid JSON
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return false;
|
|
154
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createOAuthDatabase, type OAuthDatabase } from './store/db.js';
|
|
2
|
+
|
|
3
|
+
export let CLIENT_ID: string;
|
|
4
|
+
export let REDIRECT_URI: string;
|
|
5
|
+
|
|
6
|
+
export let database: OAuthDatabase;
|
|
7
|
+
|
|
8
|
+
export interface ConfigureOAuthOptions {
|
|
9
|
+
/**
|
|
10
|
+
* Client metadata, necessary to drive the whole request
|
|
11
|
+
*/
|
|
12
|
+
metadata: {
|
|
13
|
+
client_id: string;
|
|
14
|
+
redirect_uri: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Name that will be used as prefix for storage keys needed to persist authentication.
|
|
19
|
+
* @default "atcute-oauth"
|
|
20
|
+
*/
|
|
21
|
+
storageName?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const configureOAuth = (options: ConfigureOAuthOptions) => {
|
|
25
|
+
({ client_id: CLIENT_ID, redirect_uri: REDIRECT_URI } = options.metadata);
|
|
26
|
+
database = createOAuthDatabase({ name: options.storageName ?? 'atcute-oauth' });
|
|
27
|
+
};
|
package/lib/errors.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { At } from '@atcute/client/lexicons';
|
|
2
|
+
|
|
3
|
+
export class LoginError extends Error {
|
|
4
|
+
override name = 'LoginError';
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export class AuthorizationError extends Error {
|
|
8
|
+
override name = 'AuthorizationError';
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export class ResolverError extends Error {
|
|
12
|
+
override name = 'ResolverError';
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class TokenRefreshError extends Error {
|
|
16
|
+
override name = 'TokenRefreshError';
|
|
17
|
+
|
|
18
|
+
constructor(
|
|
19
|
+
public readonly sub: At.DID,
|
|
20
|
+
message: string,
|
|
21
|
+
options?: ErrorOptions,
|
|
22
|
+
) {
|
|
23
|
+
super(message, options);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class OAuthResponseError extends Error {
|
|
28
|
+
override name = 'OAuthResponseError';
|
|
29
|
+
|
|
30
|
+
readonly error: string | undefined;
|
|
31
|
+
readonly description: string | undefined;
|
|
32
|
+
|
|
33
|
+
constructor(
|
|
34
|
+
public readonly response: Response,
|
|
35
|
+
public readonly data: any,
|
|
36
|
+
) {
|
|
37
|
+
const error = ifString(ifObject(data)?.['error']);
|
|
38
|
+
const errorDescription = ifString(ifObject(data)?.['error_description']);
|
|
39
|
+
|
|
40
|
+
const messageError = error ? `"${error}"` : 'unknown';
|
|
41
|
+
const messageDesc = errorDescription ? `: ${errorDescription}` : '';
|
|
42
|
+
const message = `OAuth ${messageError} error${messageDesc}`;
|
|
43
|
+
|
|
44
|
+
super(message);
|
|
45
|
+
|
|
46
|
+
this.error = error;
|
|
47
|
+
this.description = errorDescription;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
get status() {
|
|
51
|
+
return this.response.status;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
get headers() {
|
|
55
|
+
return this.response.headers;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class FetchResponseError extends Error {
|
|
60
|
+
override name = 'FetchResponseError';
|
|
61
|
+
|
|
62
|
+
constructor(
|
|
63
|
+
public readonly response: Response,
|
|
64
|
+
public status: number,
|
|
65
|
+
message: string,
|
|
66
|
+
) {
|
|
67
|
+
super(message);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const ifString = (v: unknown): string | undefined => {
|
|
72
|
+
return typeof v === 'string' ? v : undefined;
|
|
73
|
+
};
|
|
74
|
+
const ifObject = (v: unknown): Record<string, unknown> | undefined => {
|
|
75
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as any) : undefined;
|
|
76
|
+
};
|
package/lib/index.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { configureOAuth, type ConfigureOAuthOptions } from './environment.js';
|
|
2
|
+
|
|
3
|
+
export * from './errors.js';
|
|
4
|
+
export * from './resolvers.js';
|
|
5
|
+
|
|
6
|
+
export * from './agents/exchange.js';
|
|
7
|
+
export * from './agents/server-agent.js';
|
|
8
|
+
export * from './agents/sessions.js';
|
|
9
|
+
export * from './agents/user-agent.js';
|
|
10
|
+
|
|
11
|
+
export * from './types/client.js';
|
|
12
|
+
export * from './types/dpop.js';
|
|
13
|
+
export * from './types/identity.js';
|
|
14
|
+
export * from './types/par.js';
|
|
15
|
+
export * from './types/server.js';
|
|
16
|
+
export * from './types/store.js';
|
|
17
|
+
export * from './types/token.js';
|
package/lib/resolvers.ts
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import type { At, ComAtprotoIdentityResolveHandle } from '@atcute/client/lexicons';
|
|
2
|
+
import { type DidDocument, getPdsEndpoint } from '@atcute/client/utils/did';
|
|
3
|
+
|
|
4
|
+
import { DEFAULT_APPVIEW_URL } from './constants.js';
|
|
5
|
+
import { ResolverError } from './errors.js';
|
|
6
|
+
import type { IdentityMetadata } from './types/identity.js';
|
|
7
|
+
import type { AuthorizationServerMetadata, ProtectedResourceMetadata } from './types/server.js';
|
|
8
|
+
import { extractContentType } from './utils/response.js';
|
|
9
|
+
import { isDid, isValidUrl } from './utils/strings.js';
|
|
10
|
+
|
|
11
|
+
const DID_WEB_RE = /^([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*(?:\.[a-zA-Z]{2,}))$/;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Resolves domain handles into DID identifiers, by requesting Bluesky's AppView
|
|
15
|
+
* for identity resolution.
|
|
16
|
+
* @param handle Domain handle to resolve
|
|
17
|
+
* @returns DID identifier resolved from the domain handle
|
|
18
|
+
*/
|
|
19
|
+
export const resolveHandle = async (handle: string): Promise<At.DID> => {
|
|
20
|
+
const url = DEFAULT_APPVIEW_URL + `/xrpc/com.atproto.identity.resolveHandle` + `?handle=${handle}`;
|
|
21
|
+
|
|
22
|
+
const response = await fetch(url);
|
|
23
|
+
if (response.status === 400) {
|
|
24
|
+
throw new ResolverError(`domain handle not found`);
|
|
25
|
+
} else if (!response.ok) {
|
|
26
|
+
throw new ResolverError(`directory is unreachable`);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const json = (await response.json()) as ComAtprotoIdentityResolveHandle.Output;
|
|
30
|
+
return json.did;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Get DID documents of did:plc (via plc.directory) and did:web identifiers
|
|
35
|
+
* @param did DID identifier we're seeking DID doc from
|
|
36
|
+
* @returns Retrieved DID document
|
|
37
|
+
*/
|
|
38
|
+
export const getDidDocument = async (did: At.DID): Promise<DidDocument> => {
|
|
39
|
+
const colon_index = did.indexOf(':', 4);
|
|
40
|
+
|
|
41
|
+
const type = did.slice(4, colon_index);
|
|
42
|
+
const ident = did.slice(colon_index + 1);
|
|
43
|
+
|
|
44
|
+
// 2. retrieve their DID documents
|
|
45
|
+
let doc: DidDocument;
|
|
46
|
+
|
|
47
|
+
if (type === 'plc') {
|
|
48
|
+
const response = await fetch(`https://plc.directory/${did}`);
|
|
49
|
+
|
|
50
|
+
if (response.status === 404) {
|
|
51
|
+
throw new ResolverError(`did not found in directory`);
|
|
52
|
+
} else if (!response.ok) {
|
|
53
|
+
throw new ResolverError(`directory is unreachable`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const json = await response.json();
|
|
57
|
+
|
|
58
|
+
doc = json as DidDocument;
|
|
59
|
+
} else if (type === 'web') {
|
|
60
|
+
if (!DID_WEB_RE.test(ident)) {
|
|
61
|
+
throw new ResolverError(`invalid identifier`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const response = await fetch(`https://${ident}/.well-known/did.json`);
|
|
65
|
+
|
|
66
|
+
if (!response.ok) {
|
|
67
|
+
throw new ResolverError(`did document is unreachable`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const json = await response.json();
|
|
71
|
+
|
|
72
|
+
doc = json as DidDocument;
|
|
73
|
+
} else {
|
|
74
|
+
throw new ResolverError(`unsupported did method`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return doc;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Get OAuth protected resource metadata from a host
|
|
82
|
+
* @param host URL of the host
|
|
83
|
+
* @returns Retrieved protected resource metadata
|
|
84
|
+
*/
|
|
85
|
+
export const getProtectedResourceMetadata = async (host: string): Promise<ProtectedResourceMetadata> => {
|
|
86
|
+
const url = new URL(`/.well-known/oauth-protected-resource`, host);
|
|
87
|
+
const response = await fetch(url, {
|
|
88
|
+
redirect: 'manual',
|
|
89
|
+
headers: {
|
|
90
|
+
accept: 'application/json',
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
if (response.status !== 200 || extractContentType(response.headers) !== 'application/json') {
|
|
95
|
+
throw new ResolverError(`unexpected response`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const metadata = (await response.json()) as ProtectedResourceMetadata;
|
|
99
|
+
if (metadata.resource !== url.origin) {
|
|
100
|
+
throw new ResolverError(`unexpected issuer`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return metadata;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Get OAuth authorization server metadata from a host
|
|
108
|
+
* @param host URL of the host
|
|
109
|
+
* @returns Retrieved authorization server metadata
|
|
110
|
+
*/
|
|
111
|
+
export const getAuthorizationServerMetadata = async (host: string): Promise<AuthorizationServerMetadata> => {
|
|
112
|
+
const url = new URL(`/.well-known/oauth-authorization-server`, host);
|
|
113
|
+
const response = await fetch(url, {
|
|
114
|
+
redirect: 'manual',
|
|
115
|
+
headers: {
|
|
116
|
+
accept: 'application/json',
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (response.status !== 200 || extractContentType(response.headers) !== 'application/json') {
|
|
121
|
+
throw new ResolverError(`unexpected response`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const metadata = (await response.json()) as AuthorizationServerMetadata;
|
|
125
|
+
if (metadata.issuer !== url.origin) {
|
|
126
|
+
throw new ResolverError(`unexpected issuer`);
|
|
127
|
+
}
|
|
128
|
+
if (!isValidUrl(metadata.authorization_endpoint)) {
|
|
129
|
+
throw new ResolverError(`authorization server provided incorrect authorization endpoint`);
|
|
130
|
+
}
|
|
131
|
+
if (!metadata.client_id_metadata_document_supported) {
|
|
132
|
+
throw new ResolverError(`authorization server does not support 'client_id_metadata_document'`);
|
|
133
|
+
}
|
|
134
|
+
if (!metadata.pushed_authorization_request_endpoint) {
|
|
135
|
+
throw new ResolverError(`authorization server does not support 'pushed_authorization request'`);
|
|
136
|
+
}
|
|
137
|
+
if (metadata.response_types_supported) {
|
|
138
|
+
if (!metadata.response_types_supported.includes('code')) {
|
|
139
|
+
throw new ResolverError(`authorization server does not support 'code' response type`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return metadata;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Resolve handle domains or DID identifiers to get their PDS and its authorization server metadata
|
|
148
|
+
* @param ident Handle domain or DID identifier to resolve
|
|
149
|
+
* @returns Resolved PDS and authorization server metadata
|
|
150
|
+
*/
|
|
151
|
+
export const resolveFromIdentity = async (
|
|
152
|
+
ident: string,
|
|
153
|
+
): Promise<{ identity: IdentityMetadata; metadata: AuthorizationServerMetadata }> => {
|
|
154
|
+
let did: At.DID;
|
|
155
|
+
if (isDid(ident)) {
|
|
156
|
+
did = ident;
|
|
157
|
+
} else {
|
|
158
|
+
const resolved = await resolveHandle(ident);
|
|
159
|
+
did = resolved;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const doc = await getDidDocument(did);
|
|
163
|
+
const pds = getPdsEndpoint(doc);
|
|
164
|
+
|
|
165
|
+
if (!pds) {
|
|
166
|
+
throw new ResolverError(`missing pds endpoint`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
identity: {
|
|
171
|
+
id: did,
|
|
172
|
+
raw: ident,
|
|
173
|
+
pds: new URL(pds),
|
|
174
|
+
},
|
|
175
|
+
metadata: await getMetadataFromResourceServer(pds),
|
|
176
|
+
};
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Request authorization server metadata from a PDS
|
|
181
|
+
* @param host URL of the host
|
|
182
|
+
* @returns Resolved authorization server metadata
|
|
183
|
+
*/
|
|
184
|
+
export const resolveFromService = async (
|
|
185
|
+
host: string,
|
|
186
|
+
): Promise<{ metadata: AuthorizationServerMetadata }> => {
|
|
187
|
+
try {
|
|
188
|
+
const metadata = await getMetadataFromResourceServer(host);
|
|
189
|
+
return { metadata };
|
|
190
|
+
} catch (err) {
|
|
191
|
+
if (err instanceof ResolverError) {
|
|
192
|
+
try {
|
|
193
|
+
const metadata = await getAuthorizationServerMetadata(host);
|
|
194
|
+
return { metadata };
|
|
195
|
+
} catch {}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
throw err;
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Request authorization server metadata from its protected resource metadata
|
|
204
|
+
* @param input URL of the host whose authorization server is delegated
|
|
205
|
+
* @returns Resolved authorization server metadata
|
|
206
|
+
*/
|
|
207
|
+
export const getMetadataFromResourceServer = async (input: string) => {
|
|
208
|
+
const rs_metadata = await getProtectedResourceMetadata(input);
|
|
209
|
+
|
|
210
|
+
if (rs_metadata.authorization_servers?.length !== 1) {
|
|
211
|
+
throw new ResolverError(`expected exactly one authorization server in the listing`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const issuer = rs_metadata.authorization_servers[0];
|
|
215
|
+
|
|
216
|
+
const as_metadata = await getAuthorizationServerMetadata(issuer);
|
|
217
|
+
|
|
218
|
+
if (as_metadata.protected_resources) {
|
|
219
|
+
if (!as_metadata.protected_resources.includes(rs_metadata.resource)) {
|
|
220
|
+
throw new ResolverError(`server is not in authorization server's jurisdiction`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return as_metadata;
|
|
225
|
+
};
|
package/lib/store/db.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { At } from '@atcute/client/lexicons';
|
|
2
|
+
|
|
3
|
+
import type { DPoPKey } from '../types/dpop.js';
|
|
4
|
+
import type { AuthorizationServerMetadata } from '../types/server.js';
|
|
5
|
+
import type { SimpleStore } from '../types/store.js';
|
|
6
|
+
import type { Session } from '../types/token.js';
|
|
7
|
+
import { locks } from '../utils/runtime.js';
|
|
8
|
+
|
|
9
|
+
export interface OAuthDatabaseOptions {
|
|
10
|
+
name: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface SchemaItem<T> {
|
|
14
|
+
value: T;
|
|
15
|
+
expiresAt: number | null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface Schema {
|
|
19
|
+
sessions: {
|
|
20
|
+
key: At.DID;
|
|
21
|
+
value: Session;
|
|
22
|
+
indexes: {
|
|
23
|
+
expiresAt: number;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
states: {
|
|
27
|
+
key: string;
|
|
28
|
+
value: {
|
|
29
|
+
dpopKey: DPoPKey;
|
|
30
|
+
metadata: AuthorizationServerMetadata;
|
|
31
|
+
verifier?: string;
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
dpopNonces: {
|
|
36
|
+
key: string;
|
|
37
|
+
value: string;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const parse = (raw: string | null) => {
|
|
42
|
+
if (raw != null) {
|
|
43
|
+
const parsed = JSON.parse(raw);
|
|
44
|
+
if (parsed != null) {
|
|
45
|
+
return parsed;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return {};
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export type OAuthDatabase = ReturnType<typeof createOAuthDatabase>;
|
|
53
|
+
|
|
54
|
+
export const createOAuthDatabase = ({ name }: OAuthDatabaseOptions) => {
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const signal = controller.signal;
|
|
57
|
+
|
|
58
|
+
const createStore = <N extends keyof Schema>(
|
|
59
|
+
subname: N,
|
|
60
|
+
expiresAt: (item: Schema[N]['value']) => null | number,
|
|
61
|
+
): SimpleStore<Schema[N]['key'], Schema[N]['value']> => {
|
|
62
|
+
let store: any;
|
|
63
|
+
|
|
64
|
+
const storageKey = `${name}:${subname}`;
|
|
65
|
+
|
|
66
|
+
const persist = () => store && localStorage.setItem(storageKey, JSON.stringify(store));
|
|
67
|
+
const read = () => {
|
|
68
|
+
if (signal.aborted) {
|
|
69
|
+
throw new Error(`store closed`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return (store ??= parse(localStorage.getItem(storageKey)));
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
{
|
|
76
|
+
const listener = (ev: StorageEvent) => {
|
|
77
|
+
if (ev.key === storageKey) {
|
|
78
|
+
store = undefined;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
globalThis.addEventListener('storage', listener, { signal });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
{
|
|
86
|
+
const cleanup = async (lock: Lock | true | null) => {
|
|
87
|
+
if (!lock || signal.aborted) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
await new Promise((resolve) => setTimeout(resolve, 10_000));
|
|
92
|
+
if (signal.aborted) {
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let now = Date.now();
|
|
97
|
+
let changed = false;
|
|
98
|
+
|
|
99
|
+
read();
|
|
100
|
+
|
|
101
|
+
for (const key in store) {
|
|
102
|
+
const item = store[key];
|
|
103
|
+
const expiresAt = item.expiresAt;
|
|
104
|
+
|
|
105
|
+
if (expiresAt !== null && now > expiresAt) {
|
|
106
|
+
changed = true;
|
|
107
|
+
delete store[key];
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (changed) {
|
|
112
|
+
persist();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
if (locks) {
|
|
117
|
+
locks.request(`${storageKey}:cleanup`, { ifAvailable: true }, cleanup);
|
|
118
|
+
} else {
|
|
119
|
+
cleanup(true);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
get(key) {
|
|
125
|
+
read();
|
|
126
|
+
|
|
127
|
+
const item: SchemaItem<Schema[N]['value']> = store[key];
|
|
128
|
+
if (!item) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const expiresAt = item.expiresAt;
|
|
133
|
+
if (expiresAt !== null && Date.now() > expiresAt) {
|
|
134
|
+
delete store[key];
|
|
135
|
+
persist();
|
|
136
|
+
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return item.value;
|
|
141
|
+
},
|
|
142
|
+
set(key, value) {
|
|
143
|
+
read();
|
|
144
|
+
|
|
145
|
+
const item: SchemaItem<Schema[N]['value']> = {
|
|
146
|
+
expiresAt: expiresAt(value),
|
|
147
|
+
value: value,
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
store[key] = item;
|
|
151
|
+
persist();
|
|
152
|
+
},
|
|
153
|
+
delete(key) {
|
|
154
|
+
read();
|
|
155
|
+
|
|
156
|
+
if (store[key] !== undefined) {
|
|
157
|
+
delete store[key];
|
|
158
|
+
persist();
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
keys() {
|
|
162
|
+
read();
|
|
163
|
+
|
|
164
|
+
return Object.keys(store);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
dispose: () => {
|
|
171
|
+
controller.abort();
|
|
172
|
+
},
|
|
173
|
+
|
|
174
|
+
sessions: createStore('sessions', ({ token }) => {
|
|
175
|
+
if (token.refresh) {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return token.expires_at ?? null;
|
|
180
|
+
}),
|
|
181
|
+
states: createStore('states', (_item) => Date.now() + 10 * 60 * 1_000),
|
|
182
|
+
dpopNonces: createStore('dpopNonces', (_item) => Date.now() + 10 * 60 * 1_000),
|
|
183
|
+
};
|
|
184
|
+
};
|