@atproto/oauth-client 0.7.5 → 0.7.7
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/CHANGELOG.md +26 -0
- package/package.json +19 -14
- package/src/constants.ts +0 -4
- package/src/core-js.d.ts +0 -1
- package/src/errors/auth-method-unsatisfiable-error.ts +0 -1
- package/src/errors/token-invalid-error.ts +0 -9
- package/src/errors/token-refresh-error.ts +0 -9
- package/src/errors/token-revoked-error.ts +0 -9
- package/src/fetch-dpop.ts +0 -250
- package/src/identity-resolver.ts +0 -25
- package/src/index.ts +0 -32
- package/src/lock.ts +0 -33
- package/src/oauth-authorization-server-metadata-resolver.ts +0 -120
- package/src/oauth-callback-error.ts +0 -16
- package/src/oauth-client-auth.ts +0 -180
- package/src/oauth-client.ts +0 -541
- package/src/oauth-protected-resource-metadata-resolver.ts +0 -122
- package/src/oauth-resolver-error.ts +0 -21
- package/src/oauth-resolver.ts +0 -177
- package/src/oauth-response-error.ts +0 -33
- package/src/oauth-server-agent.ts +0 -289
- package/src/oauth-server-factory.ts +0 -64
- package/src/oauth-session.ts +0 -170
- package/src/runtime-implementation.ts +0 -25
- package/src/runtime.ts +0 -114
- package/src/session-getter.ts +0 -281
- package/src/state-store.ts +0 -24
- package/src/types.ts +0 -39
- package/src/util.test.ts +0 -86
- package/src/util.ts +0 -81
- package/src/validate-client-metadata.ts +0 -116
- package/tsconfig.build.json +0 -9
- package/tsconfig.build.tsbuildinfo +0 -1
- package/tsconfig.json +0 -7
- package/tsconfig.tests.json +0 -8
- package/vitest.config.ts +0 -5
package/src/oauth-session.ts
DELETED
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
import { AtprotoDid } from '@atproto/did'
|
|
2
|
-
import {
|
|
3
|
-
AtprotoOAuthScope,
|
|
4
|
-
OAuthAuthorizationServerMetadata,
|
|
5
|
-
} from '@atproto/oauth-types'
|
|
6
|
-
import { Fetch, bindFetch } from '@atproto-labs/fetch'
|
|
7
|
-
import { TokenInvalidError } from './errors/token-invalid-error.js'
|
|
8
|
-
import { TokenRevokedError } from './errors/token-revoked-error.js'
|
|
9
|
-
import { dpopFetchWrapper } from './fetch-dpop.js'
|
|
10
|
-
import { OAuthServerAgent, TokenSet } from './oauth-server-agent.js'
|
|
11
|
-
import { SessionGetter } from './session-getter.js'
|
|
12
|
-
|
|
13
|
-
const ReadableStream = globalThis.ReadableStream as
|
|
14
|
-
| typeof globalThis.ReadableStream
|
|
15
|
-
| undefined
|
|
16
|
-
|
|
17
|
-
export type { AtprotoDid, AtprotoOAuthScope }
|
|
18
|
-
export type TokenInfo = {
|
|
19
|
-
expiresAt?: Date
|
|
20
|
-
expired?: boolean
|
|
21
|
-
scope: AtprotoOAuthScope
|
|
22
|
-
iss: string
|
|
23
|
-
aud: string
|
|
24
|
-
sub: AtprotoDid
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export class OAuthSession {
|
|
28
|
-
protected dpopFetch: Fetch<unknown>
|
|
29
|
-
|
|
30
|
-
constructor(
|
|
31
|
-
public readonly server: OAuthServerAgent,
|
|
32
|
-
public readonly sub: AtprotoDid,
|
|
33
|
-
private readonly sessionGetter: SessionGetter,
|
|
34
|
-
fetch: Fetch = globalThis.fetch,
|
|
35
|
-
) {
|
|
36
|
-
this.dpopFetch = dpopFetchWrapper<void>({
|
|
37
|
-
fetch: bindFetch(fetch),
|
|
38
|
-
key: server.dpopKey,
|
|
39
|
-
supportedAlgs: server.serverMetadata.dpop_signing_alg_values_supported,
|
|
40
|
-
sha256: async (v) => server.runtime.sha256(v),
|
|
41
|
-
nonces: server.dpopNonces,
|
|
42
|
-
isAuthServer: false,
|
|
43
|
-
})
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
get did(): AtprotoDid {
|
|
47
|
-
return this.sub
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
get serverMetadata(): Readonly<OAuthAuthorizationServerMetadata> {
|
|
51
|
-
return this.server.serverMetadata
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* @param refresh When `true`, the credentials will be refreshed even if they
|
|
56
|
-
* are not expired. When `false`, the credentials will not be refreshed even
|
|
57
|
-
* if they are expired. When `undefined`, the credentials will be refreshed
|
|
58
|
-
* if, and only if, they are (about to be) expired. Defaults to `undefined`.
|
|
59
|
-
*/
|
|
60
|
-
protected async getTokenSet(refresh: boolean | 'auto'): Promise<TokenSet> {
|
|
61
|
-
const { tokenSet } = await this.sessionGetter.getSession(this.sub, refresh)
|
|
62
|
-
|
|
63
|
-
return tokenSet
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
async getTokenInfo(refresh: boolean | 'auto' = 'auto'): Promise<TokenInfo> {
|
|
67
|
-
const tokenSet = await this.getTokenSet(refresh)
|
|
68
|
-
const expiresAt =
|
|
69
|
-
tokenSet.expires_at == null ? undefined : new Date(tokenSet.expires_at)
|
|
70
|
-
|
|
71
|
-
return {
|
|
72
|
-
expiresAt,
|
|
73
|
-
get expired() {
|
|
74
|
-
return expiresAt == null
|
|
75
|
-
? undefined
|
|
76
|
-
: expiresAt.getTime() < Date.now() - 5e3
|
|
77
|
-
},
|
|
78
|
-
scope: tokenSet.scope,
|
|
79
|
-
iss: tokenSet.iss,
|
|
80
|
-
aud: tokenSet.aud,
|
|
81
|
-
sub: tokenSet.sub,
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async signOut(): Promise<void> {
|
|
86
|
-
try {
|
|
87
|
-
const tokenSet = await this.getTokenSet(false)
|
|
88
|
-
await this.server.revoke(tokenSet.access_token)
|
|
89
|
-
} finally {
|
|
90
|
-
await this.sessionGetter.delStored(
|
|
91
|
-
this.sub,
|
|
92
|
-
new TokenRevokedError(this.sub),
|
|
93
|
-
)
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
async fetchHandler(pathname: string, init?: RequestInit): Promise<Response> {
|
|
98
|
-
// This will try and refresh the token if it is known to be expired
|
|
99
|
-
const tokenSet = await this.getTokenSet('auto')
|
|
100
|
-
|
|
101
|
-
const initialUrl = new URL(pathname, tokenSet.aud satisfies string)
|
|
102
|
-
const initialAuth = `${tokenSet.token_type} ${tokenSet.access_token}`
|
|
103
|
-
|
|
104
|
-
const headers = new Headers(init?.headers)
|
|
105
|
-
headers.set('Authorization', initialAuth)
|
|
106
|
-
|
|
107
|
-
const initialResponse = await this.dpopFetch(initialUrl, {
|
|
108
|
-
...init,
|
|
109
|
-
headers,
|
|
110
|
-
})
|
|
111
|
-
|
|
112
|
-
// If the token is not expired, we don't need to refresh it
|
|
113
|
-
if (!isInvalidTokenResponse(initialResponse)) {
|
|
114
|
-
return initialResponse
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
let tokenSetFresh: TokenSet
|
|
118
|
-
try {
|
|
119
|
-
// Force a refresh
|
|
120
|
-
tokenSetFresh = await this.getTokenSet(true)
|
|
121
|
-
} catch (err) {
|
|
122
|
-
return initialResponse
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// The stream was already consumed. We cannot retry the request. A solution
|
|
126
|
-
// would be to tee() the input stream but that would bufferize the entire
|
|
127
|
-
// stream in memory which can lead to memory starvation. Instead, we will
|
|
128
|
-
// return the original response and let the calling code handle retries.
|
|
129
|
-
if (ReadableStream && init?.body instanceof ReadableStream) {
|
|
130
|
-
return initialResponse
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
const finalAuth = `${tokenSetFresh.token_type} ${tokenSetFresh.access_token}`
|
|
134
|
-
const finalUrl = new URL(pathname, tokenSetFresh.aud)
|
|
135
|
-
|
|
136
|
-
headers.set('Authorization', finalAuth)
|
|
137
|
-
|
|
138
|
-
const finalResponse = await this.dpopFetch(finalUrl, { ...init, headers })
|
|
139
|
-
|
|
140
|
-
// The token was successfully refreshed, but is still not accepted by the
|
|
141
|
-
// resource server. This might be due to the resource server not accepting
|
|
142
|
-
// credentials from the authorization server (e.g. because some migration
|
|
143
|
-
// occurred). Any ways, there is no point in keeping the session.
|
|
144
|
-
if (isInvalidTokenResponse(finalResponse)) {
|
|
145
|
-
// @TODO Is there a "softer" way to handle this, e.g. by marking the
|
|
146
|
-
// session as "expired" in the session store, allowing the user to trigger
|
|
147
|
-
// a new login (using login_hint)?
|
|
148
|
-
await this.sessionGetter.delStored(
|
|
149
|
-
this.sub,
|
|
150
|
-
new TokenInvalidError(this.sub),
|
|
151
|
-
)
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
return finalResponse
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* @see {@link https://datatracker.ietf.org/doc/html/rfc6750#section-3}
|
|
160
|
-
* @see {@link https://datatracker.ietf.org/doc/html/rfc9449#name-resource-server-provided-no}
|
|
161
|
-
*/
|
|
162
|
-
function isInvalidTokenResponse(response: Response) {
|
|
163
|
-
if (response.status !== 401) return false
|
|
164
|
-
const wwwAuth = response.headers.get('WWW-Authenticate')
|
|
165
|
-
return (
|
|
166
|
-
wwwAuth != null &&
|
|
167
|
-
(wwwAuth.startsWith('Bearer ') || wwwAuth.startsWith('DPoP ')) &&
|
|
168
|
-
wwwAuth.includes('error="invalid_token"')
|
|
169
|
-
)
|
|
170
|
-
}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { Key } from '@atproto/jwk'
|
|
2
|
-
import { Awaitable } from './util.js'
|
|
3
|
-
|
|
4
|
-
export type { Key }
|
|
5
|
-
export type RuntimeKeyFactory = (algs: string[]) => Key | PromiseLike<Key>
|
|
6
|
-
|
|
7
|
-
export type RuntimeRandomValues = (length: number) => Awaitable<Uint8Array>
|
|
8
|
-
|
|
9
|
-
export type DigestAlgorithm = { name: 'sha256' | 'sha384' | 'sha512' }
|
|
10
|
-
export type RuntimeDigest = (
|
|
11
|
-
data: Uint8Array<ArrayBuffer>,
|
|
12
|
-
alg: DigestAlgorithm,
|
|
13
|
-
) => Awaitable<Uint8Array>
|
|
14
|
-
|
|
15
|
-
export type RuntimeLock = <T>(
|
|
16
|
-
name: string,
|
|
17
|
-
fn: () => Awaitable<T>,
|
|
18
|
-
) => Awaitable<T>
|
|
19
|
-
|
|
20
|
-
export interface RuntimeImplementation {
|
|
21
|
-
createKey: RuntimeKeyFactory
|
|
22
|
-
getRandomValues: RuntimeRandomValues
|
|
23
|
-
digest: RuntimeDigest
|
|
24
|
-
requestLock?: RuntimeLock
|
|
25
|
-
}
|
package/src/runtime.ts
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
import { base64url } from 'multiformats/bases/base64'
|
|
2
|
-
import { Key } from '@atproto/jwk'
|
|
3
|
-
import { requestLocalLock } from './lock.js'
|
|
4
|
-
import { RuntimeImplementation, RuntimeLock } from './runtime-implementation.js'
|
|
5
|
-
|
|
6
|
-
export class Runtime {
|
|
7
|
-
readonly hasImplementationLock: boolean
|
|
8
|
-
readonly usingLock: RuntimeLock
|
|
9
|
-
|
|
10
|
-
constructor(protected implementation: RuntimeImplementation) {
|
|
11
|
-
const { requestLock } = implementation
|
|
12
|
-
|
|
13
|
-
this.hasImplementationLock = requestLock != null
|
|
14
|
-
this.usingLock =
|
|
15
|
-
requestLock?.bind(implementation) ||
|
|
16
|
-
// Falling back to a local lock
|
|
17
|
-
requestLocalLock
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
public async generateKey(algs: string[]): Promise<Key> {
|
|
21
|
-
const algsSorted = Array.from(algs).sort(compareAlgos)
|
|
22
|
-
return this.implementation.createKey(algsSorted)
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
public async sha256(text: string): Promise<string> {
|
|
26
|
-
const bytes = new TextEncoder().encode(text)
|
|
27
|
-
const digest = await this.implementation.digest(bytes, { name: 'sha256' })
|
|
28
|
-
return base64url.baseEncode(digest)
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
public async generateNonce(length = 16): Promise<string> {
|
|
32
|
-
const bytes = await this.implementation.getRandomValues(length)
|
|
33
|
-
return base64url.baseEncode(bytes)
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
public async generatePKCE(byteLength?: number) {
|
|
37
|
-
const verifier = await this.generateVerifier(byteLength)
|
|
38
|
-
return {
|
|
39
|
-
verifier,
|
|
40
|
-
challenge: await this.sha256(verifier),
|
|
41
|
-
method: 'S256' as const,
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
public async calculateJwkThumbprint(jwk) {
|
|
46
|
-
const components = extractJktComponents(jwk)
|
|
47
|
-
const data = JSON.stringify(components)
|
|
48
|
-
return this.sha256(data)
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* @see {@link https://datatracker.ietf.org/doc/html/rfc7636#section-4.1}
|
|
53
|
-
* @note It is RECOMMENDED that the output of a suitable random number generator
|
|
54
|
-
* be used to create a 32-octet sequence. The octet sequence is then
|
|
55
|
-
* base64url-encoded to produce a 43-octet URL safe string to use as the code
|
|
56
|
-
* verifier.
|
|
57
|
-
*/
|
|
58
|
-
protected async generateVerifier(byteLength = 32) {
|
|
59
|
-
if (byteLength < 32 || byteLength > 96) {
|
|
60
|
-
throw new TypeError('Invalid code_verifier length')
|
|
61
|
-
}
|
|
62
|
-
const bytes = await this.implementation.getRandomValues(byteLength)
|
|
63
|
-
return base64url.baseEncode(bytes)
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function extractJktComponents(jwk) {
|
|
68
|
-
const get = (field) => {
|
|
69
|
-
const value = jwk[field]
|
|
70
|
-
if (typeof value !== 'string' || !value) {
|
|
71
|
-
throw new TypeError(`"${field}" Parameter missing or invalid`)
|
|
72
|
-
}
|
|
73
|
-
return value
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
switch (jwk.kty) {
|
|
77
|
-
case 'EC':
|
|
78
|
-
return { crv: get('crv'), kty: get('kty'), x: get('x'), y: get('y') }
|
|
79
|
-
case 'OKP':
|
|
80
|
-
return { crv: get('crv'), kty: get('kty'), x: get('x') }
|
|
81
|
-
case 'RSA':
|
|
82
|
-
return { e: get('e'), kty: get('kty'), n: get('n') }
|
|
83
|
-
case 'oct':
|
|
84
|
-
return { k: get('k'), kty: get('kty') }
|
|
85
|
-
default:
|
|
86
|
-
throw new TypeError('"kty" (Key Type) Parameter missing or unsupported')
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* 256K > ES (256 > 384 > 512) > PS (256 > 384 > 512) > RS (256 > 384 > 512) > other (in original order)
|
|
92
|
-
*/
|
|
93
|
-
function compareAlgos(a: string, b: string): number {
|
|
94
|
-
if (a === 'ES256K') return -1
|
|
95
|
-
if (b === 'ES256K') return 1
|
|
96
|
-
|
|
97
|
-
for (const prefix of ['ES', 'PS', 'RS']) {
|
|
98
|
-
if (a.startsWith(prefix)) {
|
|
99
|
-
if (b.startsWith(prefix)) {
|
|
100
|
-
const aLen = parseInt(a.slice(2, 5))
|
|
101
|
-
const bLen = parseInt(b.slice(2, 5))
|
|
102
|
-
|
|
103
|
-
// Prefer shorter key lengths
|
|
104
|
-
return aLen - bLen
|
|
105
|
-
}
|
|
106
|
-
return -1
|
|
107
|
-
} else if (b.startsWith(prefix)) {
|
|
108
|
-
return 1
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// Don't know how to compare, keep original order
|
|
113
|
-
return 0
|
|
114
|
-
}
|
package/src/session-getter.ts
DELETED
|
@@ -1,281 +0,0 @@
|
|
|
1
|
-
import { AtprotoDid } from '@atproto/did'
|
|
2
|
-
import { Key } from '@atproto/jwk'
|
|
3
|
-
import {
|
|
4
|
-
CachedGetter,
|
|
5
|
-
GetCachedOptions,
|
|
6
|
-
GetOptions,
|
|
7
|
-
SimpleStore,
|
|
8
|
-
} from '@atproto-labs/simple-store'
|
|
9
|
-
import { AuthMethodUnsatisfiableError } from './errors/auth-method-unsatisfiable-error.js'
|
|
10
|
-
import { TokenInvalidError } from './errors/token-invalid-error.js'
|
|
11
|
-
import { TokenRefreshError } from './errors/token-refresh-error.js'
|
|
12
|
-
import { TokenRevokedError } from './errors/token-revoked-error.js'
|
|
13
|
-
import { ClientAuthMethod } from './oauth-client-auth.js'
|
|
14
|
-
import { OAuthResponseError } from './oauth-response-error.js'
|
|
15
|
-
import { TokenSet } from './oauth-server-agent.js'
|
|
16
|
-
import { OAuthServerFactory } from './oauth-server-factory.js'
|
|
17
|
-
import { Runtime } from './runtime.js'
|
|
18
|
-
import { combineSignals, timeoutSignal } from './util.js'
|
|
19
|
-
|
|
20
|
-
export type Session = {
|
|
21
|
-
dpopKey: Key
|
|
22
|
-
authMethod: ClientAuthMethod
|
|
23
|
-
tokenSet: TokenSet
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export type SessionStore = SimpleStore<string, Session>
|
|
27
|
-
|
|
28
|
-
export type SessionHooks = {
|
|
29
|
-
onUpdate?: (sub: AtprotoDid, session: Session) => void
|
|
30
|
-
onDelete?: (
|
|
31
|
-
sub: AtprotoDid,
|
|
32
|
-
cause: TokenRefreshError | TokenRevokedError | TokenInvalidError | unknown,
|
|
33
|
-
) => void
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export function isExpectedSessionError(err: unknown) {
|
|
37
|
-
return (
|
|
38
|
-
err instanceof TokenRefreshError ||
|
|
39
|
-
err instanceof TokenRevokedError ||
|
|
40
|
-
err instanceof TokenInvalidError ||
|
|
41
|
-
err instanceof AuthMethodUnsatisfiableError ||
|
|
42
|
-
// The stored session is invalid (e.g. missing properties) and cannot
|
|
43
|
-
// be used properly
|
|
44
|
-
err instanceof TypeError
|
|
45
|
-
)
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* There are several advantages to wrapping the sessionStore in a (single)
|
|
50
|
-
* CachedGetter, the main of which is that the cached getter will ensure that at
|
|
51
|
-
* most one fresh call is ever being made. Another advantage, is that it
|
|
52
|
-
* contains the logic for reading from the cache which, if the cache is based on
|
|
53
|
-
* localStorage/indexedDB, will sync across multiple tabs (for a given sub).
|
|
54
|
-
*/
|
|
55
|
-
export class SessionGetter extends CachedGetter<AtprotoDid, Session> {
|
|
56
|
-
constructor(
|
|
57
|
-
sessionStore: SessionStore,
|
|
58
|
-
serverFactory: OAuthServerFactory,
|
|
59
|
-
private readonly runtime: Runtime,
|
|
60
|
-
private readonly hooks: SessionHooks = {},
|
|
61
|
-
) {
|
|
62
|
-
super(
|
|
63
|
-
async (sub, { signal }, storedSession) => {
|
|
64
|
-
// There needs to be a previous session to be able to refresh. If
|
|
65
|
-
// storedSession is undefined, it means that the store does not contain
|
|
66
|
-
// a session for the given sub.
|
|
67
|
-
if (storedSession === undefined) {
|
|
68
|
-
// Because the session is not in the store, this.delStored() method
|
|
69
|
-
// will not be called by the CachedGetter class (because there is
|
|
70
|
-
// nothing to delete). This would typically happen if there is no
|
|
71
|
-
// synchronization mechanism between instances of this class. Let's
|
|
72
|
-
// make sure an event is dispatched here if this occurs.
|
|
73
|
-
const msg = 'The session was deleted by another process'
|
|
74
|
-
const cause = new TokenRefreshError(sub, msg)
|
|
75
|
-
await hooks.onDelete?.call(null, sub, cause)
|
|
76
|
-
throw cause
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// @NOTE Throwing a TokenRefreshError (or any other error class defined
|
|
80
|
-
// in the deleteOnError options) will result in this.delStored() being
|
|
81
|
-
// called.
|
|
82
|
-
|
|
83
|
-
const { dpopKey, authMethod, tokenSet } = storedSession
|
|
84
|
-
|
|
85
|
-
if (sub !== tokenSet.sub) {
|
|
86
|
-
// Fool-proofing (e.g. against invalid session storage)
|
|
87
|
-
throw new TokenRefreshError(sub, 'Stored session sub mismatch')
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
if (!tokenSet.refresh_token) {
|
|
91
|
-
throw new TokenRefreshError(sub, 'No refresh token available')
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
const server = await serverFactory.fromIssuer(
|
|
95
|
-
tokenSet.iss,
|
|
96
|
-
authMethod,
|
|
97
|
-
dpopKey,
|
|
98
|
-
)
|
|
99
|
-
|
|
100
|
-
// Because refresh tokens can only be used once, we must not use the
|
|
101
|
-
// "signal" to abort the refresh, or throw any abort error beyond this
|
|
102
|
-
// point. Any thrown error beyond this point will prevent the
|
|
103
|
-
// TokenGetter from obtaining, and storing, the new token set,
|
|
104
|
-
// effectively rendering the currently saved session unusable.
|
|
105
|
-
signal?.throwIfAborted()
|
|
106
|
-
|
|
107
|
-
try {
|
|
108
|
-
const newTokenSet = await server.refresh(tokenSet)
|
|
109
|
-
|
|
110
|
-
if (sub !== newTokenSet.sub) {
|
|
111
|
-
// The server returned another sub. Was the tokenSet manipulated?
|
|
112
|
-
throw new TokenRefreshError(sub, 'Token set sub mismatch')
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
return {
|
|
116
|
-
dpopKey,
|
|
117
|
-
tokenSet: newTokenSet,
|
|
118
|
-
authMethod: server.authMethod,
|
|
119
|
-
}
|
|
120
|
-
} catch (cause) {
|
|
121
|
-
// Since refresh tokens can only be used once, we might run into
|
|
122
|
-
// concurrency issues if multiple instances (e.g. browser tabs) are
|
|
123
|
-
// trying to refresh the same token simultaneously. The chances of
|
|
124
|
-
// this happening when multiple instances are started simultaneously
|
|
125
|
-
// is reduced by randomizing the expiry time (see isStale() below).
|
|
126
|
-
// The best solution is to use a mutex/lock to ensure that only one
|
|
127
|
-
// instance is refreshing the token at a time (runtime.usingLock) but
|
|
128
|
-
// that is not always possible. Let's try to recover from concurrency
|
|
129
|
-
// issues, or force the session to be deleted by throwing a
|
|
130
|
-
// TokenRefreshError.
|
|
131
|
-
if (
|
|
132
|
-
cause instanceof OAuthResponseError &&
|
|
133
|
-
cause.status === 400 &&
|
|
134
|
-
cause.error === 'invalid_grant'
|
|
135
|
-
) {
|
|
136
|
-
// In case there is no lock implementation in the runtime, we will
|
|
137
|
-
// wait for a short time to give the other concurrent instances a
|
|
138
|
-
// chance to finish their refreshing of the token. If a concurrent
|
|
139
|
-
// refresh did occur, we will pretend that this one succeeded.
|
|
140
|
-
if (!runtime.hasImplementationLock) {
|
|
141
|
-
await new Promise((r) => setTimeout(r, 1000))
|
|
142
|
-
|
|
143
|
-
const stored = await this.getStored(sub)
|
|
144
|
-
if (stored === undefined) {
|
|
145
|
-
// A concurrent refresh occurred and caused the session to be
|
|
146
|
-
// deleted (for a reason we can't know at this point).
|
|
147
|
-
|
|
148
|
-
// Using a distinct error message mainly for debugging
|
|
149
|
-
// purposes. Also, throwing a TokenRefreshError to trigger
|
|
150
|
-
// deletion through the deleteOnError callback.
|
|
151
|
-
const msg = 'The session was deleted by another process'
|
|
152
|
-
throw new TokenRefreshError(sub, msg, { cause })
|
|
153
|
-
} else if (
|
|
154
|
-
stored.tokenSet.access_token !== tokenSet.access_token ||
|
|
155
|
-
stored.tokenSet.refresh_token !== tokenSet.refresh_token
|
|
156
|
-
) {
|
|
157
|
-
// A concurrent refresh occurred. Pretend this one succeeded.
|
|
158
|
-
return stored
|
|
159
|
-
} else {
|
|
160
|
-
// There were no concurrent refresh. The token is (likely)
|
|
161
|
-
// simply no longer valid.
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// Make sure the session gets deleted from the store
|
|
166
|
-
const msg = cause.errorDescription ?? 'The session was revoked'
|
|
167
|
-
throw new TokenRefreshError(sub, msg, { cause })
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
throw cause
|
|
171
|
-
}
|
|
172
|
-
},
|
|
173
|
-
sessionStore,
|
|
174
|
-
{
|
|
175
|
-
isStale: (sub, { tokenSet }) => {
|
|
176
|
-
return (
|
|
177
|
-
tokenSet.expires_at != null &&
|
|
178
|
-
new Date(tokenSet.expires_at).getTime() <
|
|
179
|
-
Date.now() +
|
|
180
|
-
// Add some lee way to ensure the token is not expired when it
|
|
181
|
-
// reaches the server.
|
|
182
|
-
10e3 +
|
|
183
|
-
// Add some randomness to reduce the chances of multiple
|
|
184
|
-
// instances trying to refresh the token at the same.
|
|
185
|
-
30e3 * Math.random()
|
|
186
|
-
)
|
|
187
|
-
},
|
|
188
|
-
onStoreError: async (err, sub, { tokenSet, dpopKey, authMethod }) => {
|
|
189
|
-
// If the token data cannot be stored, let's revoke it
|
|
190
|
-
try {
|
|
191
|
-
const server = await serverFactory.fromIssuer(
|
|
192
|
-
tokenSet.iss,
|
|
193
|
-
authMethod,
|
|
194
|
-
dpopKey,
|
|
195
|
-
)
|
|
196
|
-
await server.revoke(tokenSet.refresh_token ?? tokenSet.access_token)
|
|
197
|
-
} catch {
|
|
198
|
-
// At least we tried...
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// Attempt to delete the session from the store. Note that this might
|
|
202
|
-
// fail if the store is not available, which is fine.
|
|
203
|
-
try {
|
|
204
|
-
await this.delStored(sub, err)
|
|
205
|
-
} catch {
|
|
206
|
-
// Ignore (better to propagate the original storage error)
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
throw err
|
|
210
|
-
},
|
|
211
|
-
deleteOnError: isExpectedSessionError,
|
|
212
|
-
},
|
|
213
|
-
)
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
override async getStored(
|
|
217
|
-
sub: AtprotoDid,
|
|
218
|
-
options?: GetOptions,
|
|
219
|
-
): Promise<Session | undefined> {
|
|
220
|
-
return super.getStored(sub, options)
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
override async setStored(sub: AtprotoDid, session: Session) {
|
|
224
|
-
// Prevent tampering with the stored value
|
|
225
|
-
if (sub !== session.tokenSet.sub) {
|
|
226
|
-
throw new TypeError('Token set does not match the expected sub')
|
|
227
|
-
}
|
|
228
|
-
await super.setStored(sub, session)
|
|
229
|
-
await this.hooks.onUpdate?.call(null, sub, session)
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
override async delStored(sub: AtprotoDid, cause?: unknown): Promise<void> {
|
|
233
|
-
await super.delStored(sub, cause)
|
|
234
|
-
await this.hooks.onDelete?.call(null, sub, cause)
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/**
|
|
238
|
-
* @deprecated Use {@link getSession} instead
|
|
239
|
-
* @internal (not really deprecated)
|
|
240
|
-
*/
|
|
241
|
-
override async get(
|
|
242
|
-
sub: AtprotoDid,
|
|
243
|
-
options?: GetCachedOptions,
|
|
244
|
-
): Promise<Session> {
|
|
245
|
-
const session = await this.runtime.usingLock(
|
|
246
|
-
`@atproto-oauth-client-${sub}`,
|
|
247
|
-
async () => {
|
|
248
|
-
// Make sure, even if there is no signal in the options, that the
|
|
249
|
-
// request will be cancelled after at most 30 seconds.
|
|
250
|
-
const signal = timeoutSignal(30e3)
|
|
251
|
-
|
|
252
|
-
using abortController = combineSignals([options?.signal, signal])
|
|
253
|
-
|
|
254
|
-
return await super.get(sub, {
|
|
255
|
-
...options,
|
|
256
|
-
signal: abortController.signal,
|
|
257
|
-
})
|
|
258
|
-
},
|
|
259
|
-
)
|
|
260
|
-
|
|
261
|
-
if (sub !== session.tokenSet.sub) {
|
|
262
|
-
// Fool-proofing (e.g. against invalid session storage)
|
|
263
|
-
throw new Error('Token set does not match the expected sub')
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
return session
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
/**
|
|
270
|
-
* @param refresh When `true`, the credentials will be refreshed even if they
|
|
271
|
-
* are not expired. When `false`, the credentials will not be refreshed even
|
|
272
|
-
* if they are expired. When `undefined`, the credentials will be refreshed
|
|
273
|
-
* if, and only if, they are (about to be) expired. Defaults to `undefined`.
|
|
274
|
-
*/
|
|
275
|
-
async getSession(sub: AtprotoDid, refresh: boolean | 'auto' = 'auto') {
|
|
276
|
-
return this.get(sub, {
|
|
277
|
-
noCache: refresh === true,
|
|
278
|
-
allowStale: refresh === false,
|
|
279
|
-
})
|
|
280
|
-
}
|
|
281
|
-
}
|
package/src/state-store.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import { Key } from '@atproto/jwk'
|
|
2
|
-
import { SimpleStore } from '@atproto-labs/simple-store'
|
|
3
|
-
import { ClientAuthMethod } from './oauth-client-auth.js'
|
|
4
|
-
|
|
5
|
-
export type InternalStateData = {
|
|
6
|
-
iss: string
|
|
7
|
-
dpopKey: Key
|
|
8
|
-
authMethod: ClientAuthMethod
|
|
9
|
-
verifier: string
|
|
10
|
-
appState?: string
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* A store pending oauth authorization flows. The key is the "state" parameter
|
|
15
|
-
* used in the authorization request, and the value is an object containing the
|
|
16
|
-
* necessary information to complete the flow once the user is redirected back
|
|
17
|
-
* to the client.
|
|
18
|
-
*
|
|
19
|
-
* @note The data stored in this store is typically short-lived. It should be
|
|
20
|
-
* automatically cleared after a certain period of time (e.g. 1 hour) to prevent
|
|
21
|
-
* the store from growing indefinitely. It is up to the implementation to
|
|
22
|
-
* implement this cleanup mechanism.
|
|
23
|
-
*/
|
|
24
|
-
export type StateStore = SimpleStore<string, InternalStateData>
|
package/src/types.ts
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
import { TypeOf, z } from 'zod'
|
|
2
|
-
import {
|
|
3
|
-
OAuthAuthorizationRequestParameters,
|
|
4
|
-
oauthClientIdDiscoverableSchema,
|
|
5
|
-
oauthClientIdLoopbackSchema,
|
|
6
|
-
oauthClientMetadataSchema,
|
|
7
|
-
} from '@atproto/oauth-types'
|
|
8
|
-
import { Simplify } from './util.js'
|
|
9
|
-
|
|
10
|
-
// Note: These types are not prefixed with `OAuth` because they are not specific
|
|
11
|
-
// to OAuth. They are specific to this packages. OAuth specific types are in
|
|
12
|
-
// `@atproto/oauth-types`.
|
|
13
|
-
|
|
14
|
-
export type AuthorizeOptions = Simplify<
|
|
15
|
-
Omit<
|
|
16
|
-
OAuthAuthorizationRequestParameters,
|
|
17
|
-
| 'client_id'
|
|
18
|
-
| 'response_mode'
|
|
19
|
-
| 'response_type'
|
|
20
|
-
| 'login_hint'
|
|
21
|
-
| 'code_challenge'
|
|
22
|
-
| 'code_challenge_method'
|
|
23
|
-
> & {
|
|
24
|
-
signal?: AbortSignal
|
|
25
|
-
}
|
|
26
|
-
>
|
|
27
|
-
|
|
28
|
-
export type CallbackOptions = Simplify<
|
|
29
|
-
Partial<Pick<OAuthAuthorizationRequestParameters, 'redirect_uri'>>
|
|
30
|
-
>
|
|
31
|
-
|
|
32
|
-
export const clientMetadataSchema = oauthClientMetadataSchema.extend({
|
|
33
|
-
client_id: z.union([
|
|
34
|
-
oauthClientIdDiscoverableSchema,
|
|
35
|
-
oauthClientIdLoopbackSchema,
|
|
36
|
-
]),
|
|
37
|
-
})
|
|
38
|
-
|
|
39
|
-
export type ClientMetadata = TypeOf<typeof clientMetadataSchema>
|