Skip to content

Commit 96a8c99

Browse files
committed
fix(workerd): avoid "The script will never generate a response" edge cases completely
closes #355 closes #509
1 parent 2421496 commit 96a8c99

File tree

2 files changed

+18
-28
lines changed

2 files changed

+18
-28
lines changed

src/jwks/remote.ts

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -103,36 +103,26 @@ class RemoteJWKSet<T extends KeyLike = KeyLike> extends LocalJWKSet<T> {
103103
}
104104

105105
async reload() {
106-
// see https://github.com/panva/jose/issues/355
106+
// Do not assume a fetch created in another request reliably resolves
107+
// see https://github.com/panva/jose/issues/355 and https://github.com/panva/jose/issues/509
107108
if (this._pendingFetch && isCloudflareWorkers()) {
108-
return new Promise<void>((resolve) => {
109-
const isDone = () => {
110-
if (this._pendingFetch === undefined) {
111-
resolve()
112-
} else {
113-
setTimeout(isDone, 5)
114-
}
115-
}
116-
isDone()
117-
})
109+
this._pendingFetch = undefined
118110
}
119111

120-
if (!this._pendingFetch) {
121-
this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)
122-
.then((json) => {
123-
if (!isJWKSLike(json)) {
124-
throw new JWKSInvalid('JSON Web Key Set malformed')
125-
}
126-
127-
this._jwks = { keys: json.keys }
128-
this._jwksTimestamp = Date.now()
129-
this._pendingFetch = undefined
130-
})
131-
.catch((err: Error) => {
132-
this._pendingFetch = undefined
133-
throw err
134-
})
135-
}
112+
this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)
113+
.then((json) => {
114+
if (!isJWKSLike(json)) {
115+
throw new JWKSInvalid('JSON Web Key Set malformed')
116+
}
117+
118+
this._jwks = { keys: json.keys }
119+
this._jwksTimestamp = Date.now()
120+
this._pendingFetch = undefined
121+
})
122+
.catch((err: Error) => {
123+
this._pendingFetch = undefined
124+
throw err
125+
})
136126

137127
await this._pendingFetch
138128
}

tap/jwks.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export default (QUnit: QUnit, lib: typeof jose) => {
1616
jwks({ kid: 'foo', alg: 'RS256' }),
1717
'no applicable key found in the JSON Web Key Set',
1818
)
19-
t.ok(await jwks({ alg, kid }))
19+
t.ok(await Promise.all([jwks({ alg, kid }), jwks({ alg, kid })]))
2020
})
2121

2222
test('[createLocalJWKSet] establishes local JWKSet', async (t: typeof QUnit.assert) => {

0 commit comments

Comments
 (0)