Skip to content

Commit c4dc24d

Browse files
committed
refactor: use as Type for type assertions instead of <Type>
1 parent e932007 commit c4dc24d

34 files changed

+78
-70
lines changed

src/jwe/compact/decrypt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ export async function compactDecrypt(
9090
tag: tag || undefined,
9191
encrypted_key: encryptedKey || undefined,
9292
},
93-
<Parameters<typeof flattenedDecrypt>[1]>key,
93+
key as Parameters<typeof flattenedDecrypt>[1],
9494
options,
9595
)
9696

src/jwe/general/decrypt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ export async function generalDecrypt(
101101
tag: jwe.tag,
102102
unprotected: jwe.unprotected,
103103
},
104-
<Parameters<typeof flattenedDecrypt>[1]>key,
104+
key as Parameters<typeof flattenedDecrypt>[1],
105105
options,
106106
)
107107
} catch {

src/jwe/general/encrypt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,6 @@ export class GeneralEncrypt {
291291
target.header = { ...recipient.unprotectedHeader, ...parameters }
292292
}
293293

294-
return <GeneralJWE>jwe
294+
return jwe as GeneralJWE
295295
}
296296
}

src/jwks/remote.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,10 +240,10 @@ class RemoteJWKSet<KeyLikeType extends KeyLike = KeyLike> {
240240

241241
this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)
242242
.then((json) => {
243-
this._local = createLocalJWKSet(<JSONWebKeySet>(<unknown>json))
243+
this._local = createLocalJWKSet(json as unknown as JSONWebKeySet)
244244
if (this._cache) {
245245
this._cache.uat = Date.now()
246-
this._cache.jwks = <JSONWebKeySet>(<unknown>json)
246+
this._cache.jwks = json as unknown as JSONWebKeySet
247247
}
248248
this._jwksTimestamp = Date.now()
249249
this._pendingFetch = undefined

src/jws/compact/verify.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ export async function compactVerify(
8484

8585
const verified = await flattenedVerify(
8686
{ payload, protected: protectedHeader, signature },
87-
<Parameters<typeof flattenedVerify>[1]>key,
87+
key as Parameters<typeof flattenedVerify>[1],
8888
options,
8989
)
9090

src/jws/general/verify.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ export async function generalVerify(
9595
protected: signature.protected,
9696
signature: signature.signature,
9797
},
98-
<Parameters<typeof flattenedVerify>[1]>key,
98+
key as Parameters<typeof flattenedVerify>[1],
9999
options,
100100
)
101101
} catch {

src/jwt/decrypt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ export async function jwtDecrypt(
7272
key: KeyLike | Uint8Array | JWTDecryptGetKey,
7373
options?: JWTDecryptOptions,
7474
) {
75-
const decrypted = await compactDecrypt(jwt, <Parameters<typeof compactDecrypt>[1]>key, options)
75+
const decrypted = await compactDecrypt(jwt, key as Parameters<typeof compactDecrypt>[1], options)
7676
const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options)
7777

7878
const { protectedHeader } = decrypted

src/jwt/verify.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ export async function jwtVerify(
152152
key: KeyLike | Uint8Array | JWK | JWTVerifyGetKey,
153153
options?: JWTVerifyOptions,
154154
) {
155-
const verified = await compactVerify(jwt, <Parameters<typeof compactVerify>[1]>key, options)
155+
const verified = await compactVerify(jwt, key as Parameters<typeof compactVerify>[1], options)
156156
if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
157157
throw new JWTInvalid('JWTs MUST NOT use unencoded payload')
158158
}

src/lib/check_key_type.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,14 +80,14 @@ const asymmetricTypeCheck = (alg: string, key: unknown, usage: Usage, allowJwk:
8080
}
8181

8282
// KeyObject allows this but CryptoKey does not.
83-
if ((<CryptoKey>key).algorithm && usage === 'verify' && key.type === 'private') {
83+
if ((key as CryptoKey).algorithm && usage === 'verify' && key.type === 'private') {
8484
throw new TypeError(
8585
`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`,
8686
)
8787
}
8888

8989
// KeyObject allows this but CryptoKey does not.
90-
if ((<CryptoKey>key).algorithm && usage === 'encrypt' && key.type === 'private') {
90+
if ((key as CryptoKey).algorithm && usage === 'encrypt' && key.type === 'private') {
9191
throw new TypeError(
9292
`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`,
9393
)

src/lib/is_disjoint.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
const isDisjoint = (...headers: Array<object | undefined>) => {
2-
const sources = <object[]>headers.filter(Boolean)
2+
const sources = headers.filter(Boolean) as object[]
33

44
if (sources.length === 0 || sources.length === 1) {
55
return true

src/lib/jwt_claims_set.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,10 @@ export default (
7676
}
7777
}
7878

79-
if (issuer && !(<unknown[]>(Array.isArray(issuer) ? issuer : [issuer])).includes(payload.iss!)) {
79+
if (
80+
issuer &&
81+
!((Array.isArray(issuer) ? issuer : [issuer]) as unknown[]).includes(payload.iss!)
82+
) {
8083
throw new JWTClaimValidationFailed(
8184
'unexpected "iss" claim value',
8285
payload,
@@ -174,5 +177,5 @@ export default (
174177
}
175178
}
176179

177-
return <JWTPayload>payload
180+
return payload as JWTPayload
178181
}

src/runtime/browser/aeskw.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import invalidKeyInput from '../../lib/invalid_key_input.js'
66
import { types } from './is_key_like.js'
77

88
function checkKeySize(key: CryptoKey, alg: string) {
9-
if ((<AesKeyAlgorithm>key.algorithm).length !== parseInt(alg.slice(1, 4), 10)) {
9+
if ((key.algorithm as AesKeyAlgorithm).length !== parseInt(alg.slice(1, 4), 10)) {
1010
throw new TypeError(`Invalid key size for alg: ${alg}`)
1111
}
1212
}

src/runtime/browser/check_key_length.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export default (alg: string, key: CryptoKey) => {
22
if (alg.startsWith('RS') || alg.startsWith('PS')) {
3-
const { modulusLength } = <RsaKeyAlgorithm>key.algorithm
3+
const { modulusLength } = key.algorithm as RsaKeyAlgorithm
44
if (typeof modulusLength !== 'number' || modulusLength < 2048) {
55
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`)
66
}

src/runtime/browser/ecdhes.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ export async function deriveKey(
3535
length = 448
3636
} else {
3737
length =
38-
Math.ceil(parseInt((<EcKeyAlgorithm>publicKey.algorithm).namedCurve.substr(-3), 10) / 8) << 3
38+
Math.ceil(parseInt((publicKey.algorithm as EcKeyAlgorithm).namedCurve.substr(-3), 10) / 8) <<
39+
3
3940
}
4041

4142
const sharedSecret = new Uint8Array(
@@ -57,15 +58,15 @@ export async function generateEpk(key: unknown) {
5758
throw new TypeError(invalidKeyInput(key, ...types))
5859
}
5960

60-
return crypto.subtle.generateKey(<EcKeyAlgorithm>key.algorithm, true, ['deriveBits'])
61+
return crypto.subtle.generateKey(key.algorithm as EcKeyAlgorithm, true, ['deriveBits'])
6162
}
6263

6364
export function ecdhAllowed(key: unknown) {
6465
if (!isCryptoKey(key)) {
6566
throw new TypeError(invalidKeyInput(key, ...types))
6667
}
6768
return (
68-
['P-256', 'P-384', 'P-521'].includes((<EcKeyAlgorithm>key.algorithm).namedCurve) ||
69+
['P-256', 'P-384', 'P-521'].includes((key.algorithm as EcKeyAlgorithm).namedCurve) ||
6970
key.algorithm.name === 'X25519' ||
7071
key.algorithm.name === 'X448'
7172
)

src/runtime/browser/generate.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,11 @@ export async function generateSecret(alg: string, options?: GenerateSecretOption
4242
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
4343
}
4444

45-
return <Promise<CryptoKey>>(
46-
(<unknown>crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages))
47-
)
45+
return crypto.subtle.generateKey(
46+
algorithm,
47+
options?.extractable ?? false,
48+
keyUsages,
49+
) as unknown as Promise<CryptoKey>
4850
}
4951

5052
function getModulusLengthOption(options?: GenerateKeyPairOptions) {
@@ -149,7 +151,8 @@ export async function generateKeyPair(alg: string, options?: GenerateKeyPairOpti
149151
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
150152
}
151153

152-
return <Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }>>(
153-
crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)
154-
)
154+
return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) as Promise<{
155+
publicKey: CryptoKey
156+
privateKey: CryptoKey
157+
}>
155158
}

src/runtime/browser/jwk_to_key.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ const parse = async (jwk: JWK): Promise<CryptoKey> => {
9999
const rest: [RsaHashedImportParams | EcKeyAlgorithm | Algorithm, boolean, KeyUsage[]] = [
100100
algorithm,
101101
jwk.ext ?? false,
102-
<KeyUsage[]>jwk.key_ops ?? keyUsages,
102+
(jwk.key_ops as KeyUsage[]) ?? keyUsages,
103103
]
104104

105105
const keyData: JWK = { ...jwk }

src/runtime/browser/key_to_jwk.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,6 @@ const keyToJWK: JWKExportFunction = async (key: unknown): Promise<JWK> => {
2020
}
2121
const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key)
2222

23-
return <JWK>jwk
23+
return jwk as JWK
2424
}
2525
export default keyToJWK

src/runtime/browser/normalize_key.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ const normalizePublicKey = (key: KeyLike | Uint8Array | JWK | unknown, alg: stri
6060
return cryptoKey
6161
}
6262

63-
return <KeyLike | Uint8Array>key
63+
return key as KeyLike | Uint8Array
6464
}
6565

6666
const normalizePrivateKey = (key: KeyLike | Uint8Array | JWK | unknown, alg: string) => {
@@ -82,7 +82,7 @@ const normalizePrivateKey = (key: KeyLike | Uint8Array | JWK | unknown, alg: str
8282
return cryptoKey
8383
}
8484

85-
return <KeyLike | Uint8Array>key
85+
return key as KeyLike | Uint8Array
8686
}
8787

8888
export default { normalizePublicKey, normalizePrivateKey }

src/runtime/browser/subtle_dsa.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ export default function subtleDsa(alg: string, algorithm: KeyAlgorithm | EcKeyAl
1919
case 'ES256':
2020
case 'ES384':
2121
case 'ES512':
22-
return { hash, name: 'ECDSA', namedCurve: (<EcKeyAlgorithm>algorithm).namedCurve }
22+
return { hash, name: 'ECDSA', namedCurve: (algorithm as EcKeyAlgorithm).namedCurve }
2323
case 'EdDSA':
2424
return { name: algorithm.name }
2525
default:

src/runtime/node/asn1.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const genericExport = (
2727
throw new TypeError(`key is not a ${keyType} key`)
2828
}
2929

30-
return <string>keyObject.export({ format: 'pem', type: keyFormat })
30+
return keyObject.export({ format: 'pem', type: keyFormat }) as string
3131
}
3232

3333
export const toSPKI: PEMExportFunction = (key) => {

src/runtime/node/decrypt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ function gcmDecrypt(
7474
) {
7575
const keySize = parseInt(enc.slice(1, 4), 10)
7676

77-
const algorithm = <CipherGCMTypes>`aes-${keySize}-gcm`
77+
const algorithm = `aes-${keySize}-gcm` as CipherGCMTypes
7878
if (!supported(algorithm)) {
7979
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`)
8080
}

src/runtime/node/encrypt.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ function gcmEncrypt(
5454
) {
5555
const keySize = parseInt(enc.slice(1, 4), 10)
5656

57-
const algorithm = <CipherGCMTypes>`aes-${keySize}-gcm`
57+
const algorithm = `aes-${keySize}-gcm` as CipherGCMTypes
5858
if (!supported(algorithm)) {
5959
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`)
6060
}

src/runtime/node/fetch_jwks.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ const fetchJwks: FetchFunction = async (
3434
headers,
3535
})
3636

37-
const [response] = <[IncomingMessage]>(
38-
await Promise.race([once(req, 'response'), once(req, 'timeout')])
39-
)
37+
const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')])) as [
38+
IncomingMessage,
39+
]
4040

4141
// timeout reached
4242
if (!response) {

src/runtime/node/jwk_to_key.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import type { JWK } from '../../types.d'
55

66
const parse = (key: JWK): KeyObject => {
77
if (key.d) {
8-
return createPrivateKey(<JsonWebKeyInput>{ format: 'jwk', key })
8+
return createPrivateKey({ format: 'jwk', key } as JsonWebKeyInput)
99
}
10-
return createPublicKey(<JsonWebKeyInput>{ format: 'jwk', key })
10+
return createPublicKey({ format: 'jwk', key } as JsonWebKeyInput)
1111
}
1212
export default parse

src/runtime/node/key_to_jwk.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,6 @@ const keyToJWK: JWKExportFunction = (key: unknown): JWK => {
3232
) {
3333
throw new JOSENotSupported('Unsupported key asymmetricKeyType')
3434
}
35-
return <JWK>keyObject.export({ format: 'jwk' })
35+
return keyObject.export({ format: 'jwk' }) as JWK
3636
}
3737
export default keyToJWK

src/runtime/node/node_key.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ export default function keyForCrypto<KeyObjectOptions, JWKOptions>(
126126
}
127127

128128
if (isJWK) {
129-
return <JWKOptions>{ format: 'jwk', key, ...options }
129+
return { format: 'jwk', key, ...options } as JWKOptions
130130
}
131131

132-
return options ? <KeyObjectOptions>{ ...options, key } : <KeyObject>key
132+
return options ? ({ ...options, key } as KeyObjectOptions) : (key as KeyObject)
133133
}

src/runtime/node/sign.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const sign: SignFunction = async (alg, key: unknown, data) => {
1414
const k = getSignKey(alg, key, 'sign')
1515

1616
if (alg.startsWith('HS')) {
17-
const hmac = crypto.createHmac(hmacDigest(alg), <KeyObject>k)
17+
const hmac = crypto.createHmac(hmacDigest(alg), k as KeyObject)
1818
hmac.update(data)
1919
return hmac.digest()
2020
}

src/runtime/node/webcrypto.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as crypto from 'node:crypto'
22
import * as util from 'node:util'
33

44
// @ts-ignore
5-
const webcrypto = <Crypto>crypto.webcrypto
5+
const webcrypto = crypto.webcrypto as Crypto
66

77
export default webcrypto
88

src/util/decode_protected_header.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export function decodeProtectedHeader(token: string | object): ProtectedHeaderPa
4444
if (!isObject(result)) {
4545
throw new Error()
4646
}
47-
return <ProtectedHeaderParameters>result
47+
return result as ProtectedHeaderParameters
4848
} catch {
4949
throw new TypeError('Invalid Token or Protected Header formatting')
5050
}

tap/cookbook.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -219,9 +219,10 @@ export default (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
219219
}
220220

221221
if (vector.encrypting_key && vector.encrypting_key.epk) {
222-
keyManagementParameters.epk = <jose.KeyLike>(
223-
await keys.importJWK(vector.encrypting_key.epk, vector.input.alg)
224-
)
222+
keyManagementParameters.epk = (await keys.importJWK(
223+
vector.encrypting_key.epk,
224+
vector.input.alg,
225+
)) as jose.KeyLike
225226
}
226227

227228
if (Object.keys(keyManagementParameters).length !== 0) {
@@ -254,12 +255,10 @@ export default (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
254255
encrypt.setUnprotectedHeader(vector.encrypting_content.unprotected)
255256
}
256257

257-
const privateKey = <jose.KeyLike>(
258-
await keys.importJWK(
259-
toJWK(vector.input.pwd || vector.input.key),
260-
dir ? vector.input.enc : vector.input.alg,
261-
)
262-
)
258+
const privateKey = (await keys.importJWK(
259+
toJWK(vector.input.pwd || vector.input.key),
260+
dir ? vector.input.enc : vector.input.alg,
261+
)) as jose.KeyLike
263262
let publicKey
264263
if (privateKey.type === 'secret') {
265264
publicKey = privateKey

tap/generate_options.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,15 @@ export default async (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
1212
for (const extractable of [undefined, true, false]) {
1313
test(`secret CryptoKey extractable: ${extractable ?? 'default (false)'}`, async (t) => {
1414
const expected = extractable ?? false
15-
const secret = <CryptoKey>await keys.generateSecret('HS256', { extractable })
15+
const secret = (await keys.generateSecret('HS256', { extractable })) as CryptoKey
1616
t.equal(secret.extractable, expected)
1717
})
1818
}
1919

2020
for (const extractable of [undefined, true, false]) {
2121
test(`CryptoKeyPair extractable: ${extractable ?? 'default (false)'}`, async (t) => {
2222
const expected = extractable ?? false
23-
const kp = <CryptoKeyPair>await keys.generateKeyPair('ES256', { extractable })
23+
const kp = (await keys.generateKeyPair('ES256', { extractable })) as CryptoKeyPair
2424
t.equal(kp.privateKey.extractable, expected)
2525
t.equal(kp.publicKey.extractable, true)
2626
})
@@ -30,10 +30,12 @@ export default async (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
3030
for (const modulusLength of [undefined, 2048, 3072]) {
3131
test(`RSA modulusLength ${modulusLength ?? 'default (2048)'}`, async (t) => {
3232
const expected = modulusLength ?? 2048
33-
const { publicKey } = <CryptoKeyPair>await keys.generateKeyPair('RS256', { modulusLength })
33+
const { publicKey } = (await keys.generateKeyPair('RS256', {
34+
modulusLength,
35+
})) as CryptoKeyPair
3436

3537
if (isWebCrypto) {
36-
t.equal((<RsaHashedKeyAlgorithm>publicKey.algorithm).modulusLength, expected)
38+
t.equal((publicKey.algorithm as RsaHashedKeyAlgorithm).modulusLength, expected)
3739
// @ts-ignore
3840
} else if (publicKey.asymmetricKeyDetails) {
3941
// @ts-ignore

0 commit comments

Comments
 (0)