Skip to content

Commit

Permalink
refactor: use as Type for type assertions instead of <Type>
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Sep 22, 2024
1 parent e932007 commit c4dc24d
Show file tree
Hide file tree
Showing 34 changed files with 78 additions and 70 deletions.
2 changes: 1 addition & 1 deletion src/jwe/compact/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export async function compactDecrypt(
tag: tag || undefined,
encrypted_key: encryptedKey || undefined,
},
<Parameters<typeof flattenedDecrypt>[1]>key,
key as Parameters<typeof flattenedDecrypt>[1],
options,
)

Expand Down
2 changes: 1 addition & 1 deletion src/jwe/general/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export async function generalDecrypt(
tag: jwe.tag,
unprotected: jwe.unprotected,
},
<Parameters<typeof flattenedDecrypt>[1]>key,
key as Parameters<typeof flattenedDecrypt>[1],
options,
)
} catch {
Expand Down
2 changes: 1 addition & 1 deletion src/jwe/general/encrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,6 @@ export class GeneralEncrypt {
target.header = { ...recipient.unprotectedHeader, ...parameters }
}

return <GeneralJWE>jwe
return jwe as GeneralJWE
}
}
4 changes: 2 additions & 2 deletions src/jwks/remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,10 @@ class RemoteJWKSet<KeyLikeType extends KeyLike = KeyLike> {

this._pendingFetch ||= fetchJwks(this._url, this._timeoutDuration, this._options)
.then((json) => {
this._local = createLocalJWKSet(<JSONWebKeySet>(<unknown>json))
this._local = createLocalJWKSet(json as unknown as JSONWebKeySet)
if (this._cache) {
this._cache.uat = Date.now()
this._cache.jwks = <JSONWebKeySet>(<unknown>json)
this._cache.jwks = json as unknown as JSONWebKeySet
}
this._jwksTimestamp = Date.now()
this._pendingFetch = undefined
Expand Down
2 changes: 1 addition & 1 deletion src/jws/compact/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export async function compactVerify(

const verified = await flattenedVerify(
{ payload, protected: protectedHeader, signature },
<Parameters<typeof flattenedVerify>[1]>key,
key as Parameters<typeof flattenedVerify>[1],
options,
)

Expand Down
2 changes: 1 addition & 1 deletion src/jws/general/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export async function generalVerify(
protected: signature.protected,
signature: signature.signature,
},
<Parameters<typeof flattenedVerify>[1]>key,
key as Parameters<typeof flattenedVerify>[1],
options,
)
} catch {
Expand Down
2 changes: 1 addition & 1 deletion src/jwt/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export async function jwtDecrypt(
key: KeyLike | Uint8Array | JWTDecryptGetKey,
options?: JWTDecryptOptions,
) {
const decrypted = await compactDecrypt(jwt, <Parameters<typeof compactDecrypt>[1]>key, options)
const decrypted = await compactDecrypt(jwt, key as Parameters<typeof compactDecrypt>[1], options)
const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options)

const { protectedHeader } = decrypted
Expand Down
2 changes: 1 addition & 1 deletion src/jwt/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export async function jwtVerify(
key: KeyLike | Uint8Array | JWK | JWTVerifyGetKey,
options?: JWTVerifyOptions,
) {
const verified = await compactVerify(jwt, <Parameters<typeof compactVerify>[1]>key, options)
const verified = await compactVerify(jwt, key as Parameters<typeof compactVerify>[1], options)
if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {
throw new JWTInvalid('JWTs MUST NOT use unencoded payload')
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib/check_key_type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ const asymmetricTypeCheck = (alg: string, key: unknown, usage: Usage, allowJwk:
}

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

// KeyObject allows this but CryptoKey does not.
if ((<CryptoKey>key).algorithm && usage === 'encrypt' && key.type === 'private') {
if ((key as CryptoKey).algorithm && usage === 'encrypt' && key.type === 'private') {
throw new TypeError(
`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`,
)
Expand Down
2 changes: 1 addition & 1 deletion src/lib/is_disjoint.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const isDisjoint = (...headers: Array<object | undefined>) => {
const sources = <object[]>headers.filter(Boolean)
const sources = headers.filter(Boolean) as object[]

if (sources.length === 0 || sources.length === 1) {
return true
Expand Down
7 changes: 5 additions & 2 deletions src/lib/jwt_claims_set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,10 @@ export default (
}
}

if (issuer && !(<unknown[]>(Array.isArray(issuer) ? issuer : [issuer])).includes(payload.iss!)) {
if (
issuer &&
!((Array.isArray(issuer) ? issuer : [issuer]) as unknown[]).includes(payload.iss!)
) {
throw new JWTClaimValidationFailed(
'unexpected "iss" claim value',
payload,
Expand Down Expand Up @@ -174,5 +177,5 @@ export default (
}
}

return <JWTPayload>payload
return payload as JWTPayload
}
2 changes: 1 addition & 1 deletion src/runtime/browser/aeskw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import invalidKeyInput from '../../lib/invalid_key_input.js'
import { types } from './is_key_like.js'

function checkKeySize(key: CryptoKey, alg: string) {
if ((<AesKeyAlgorithm>key.algorithm).length !== parseInt(alg.slice(1, 4), 10)) {
if ((key.algorithm as AesKeyAlgorithm).length !== parseInt(alg.slice(1, 4), 10)) {
throw new TypeError(`Invalid key size for alg: ${alg}`)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/browser/check_key_length.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export default (alg: string, key: CryptoKey) => {
if (alg.startsWith('RS') || alg.startsWith('PS')) {
const { modulusLength } = <RsaKeyAlgorithm>key.algorithm
const { modulusLength } = key.algorithm as RsaKeyAlgorithm
if (typeof modulusLength !== 'number' || modulusLength < 2048) {
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`)
}
Expand Down
7 changes: 4 additions & 3 deletions src/runtime/browser/ecdhes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ export async function deriveKey(
length = 448
} else {
length =
Math.ceil(parseInt((<EcKeyAlgorithm>publicKey.algorithm).namedCurve.substr(-3), 10) / 8) << 3
Math.ceil(parseInt((publicKey.algorithm as EcKeyAlgorithm).namedCurve.substr(-3), 10) / 8) <<
3
}

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

return crypto.subtle.generateKey(<EcKeyAlgorithm>key.algorithm, true, ['deriveBits'])
return crypto.subtle.generateKey(key.algorithm as EcKeyAlgorithm, true, ['deriveBits'])
}

export function ecdhAllowed(key: unknown) {
if (!isCryptoKey(key)) {
throw new TypeError(invalidKeyInput(key, ...types))
}
return (
['P-256', 'P-384', 'P-521'].includes((<EcKeyAlgorithm>key.algorithm).namedCurve) ||
['P-256', 'P-384', 'P-521'].includes((key.algorithm as EcKeyAlgorithm).namedCurve) ||
key.algorithm.name === 'X25519' ||
key.algorithm.name === 'X448'
)
Expand Down
15 changes: 9 additions & 6 deletions src/runtime/browser/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,11 @@ export async function generateSecret(alg: string, options?: GenerateSecretOption
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')
}

return <Promise<CryptoKey>>(
(<unknown>crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages))
)
return crypto.subtle.generateKey(
algorithm,
options?.extractable ?? false,
keyUsages,
) as unknown as Promise<CryptoKey>
}

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

return <Promise<{ publicKey: CryptoKey; privateKey: CryptoKey }>>(
crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages)
)
return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages) as Promise<{
publicKey: CryptoKey
privateKey: CryptoKey
}>
}
2 changes: 1 addition & 1 deletion src/runtime/browser/jwk_to_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const parse = async (jwk: JWK): Promise<CryptoKey> => {
const rest: [RsaHashedImportParams | EcKeyAlgorithm | Algorithm, boolean, KeyUsage[]] = [
algorithm,
jwk.ext ?? false,
<KeyUsage[]>jwk.key_ops ?? keyUsages,
(jwk.key_ops as KeyUsage[]) ?? keyUsages,
]

const keyData: JWK = { ...jwk }
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/browser/key_to_jwk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ const keyToJWK: JWKExportFunction = async (key: unknown): Promise<JWK> => {
}
const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key)

return <JWK>jwk
return jwk as JWK
}
export default keyToJWK
4 changes: 2 additions & 2 deletions src/runtime/browser/normalize_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const normalizePublicKey = (key: KeyLike | Uint8Array | JWK | unknown, alg: stri
return cryptoKey
}

return <KeyLike | Uint8Array>key
return key as KeyLike | Uint8Array
}

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

return <KeyLike | Uint8Array>key
return key as KeyLike | Uint8Array
}

export default { normalizePublicKey, normalizePrivateKey }
2 changes: 1 addition & 1 deletion src/runtime/browser/subtle_dsa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default function subtleDsa(alg: string, algorithm: KeyAlgorithm | EcKeyAl
case 'ES256':
case 'ES384':
case 'ES512':
return { hash, name: 'ECDSA', namedCurve: (<EcKeyAlgorithm>algorithm).namedCurve }
return { hash, name: 'ECDSA', namedCurve: (algorithm as EcKeyAlgorithm).namedCurve }
case 'EdDSA':
return { name: algorithm.name }
default:
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/asn1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const genericExport = (
throw new TypeError(`key is not a ${keyType} key`)
}

return <string>keyObject.export({ format: 'pem', type: keyFormat })
return keyObject.export({ format: 'pem', type: keyFormat }) as string
}

export const toSPKI: PEMExportFunction = (key) => {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/decrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ function gcmDecrypt(
) {
const keySize = parseInt(enc.slice(1, 4), 10)

const algorithm = <CipherGCMTypes>`aes-${keySize}-gcm`
const algorithm = `aes-${keySize}-gcm` as CipherGCMTypes
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`)
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/encrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function gcmEncrypt(
) {
const keySize = parseInt(enc.slice(1, 4), 10)

const algorithm = <CipherGCMTypes>`aes-${keySize}-gcm`
const algorithm = `aes-${keySize}-gcm` as CipherGCMTypes
if (!supported(algorithm)) {
throw new JOSENotSupported(`alg ${enc} is not supported by your javascript runtime`)
}
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/node/fetch_jwks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ const fetchJwks: FetchFunction = async (
headers,
})

const [response] = <[IncomingMessage]>(
await Promise.race([once(req, 'response'), once(req, 'timeout')])
)
const [response] = (await Promise.race([once(req, 'response'), once(req, 'timeout')])) as [
IncomingMessage,
]

// timeout reached
if (!response) {
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/node/jwk_to_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import type { JWK } from '../../types.d'

const parse = (key: JWK): KeyObject => {
if (key.d) {
return createPrivateKey(<JsonWebKeyInput>{ format: 'jwk', key })
return createPrivateKey({ format: 'jwk', key } as JsonWebKeyInput)
}
return createPublicKey(<JsonWebKeyInput>{ format: 'jwk', key })
return createPublicKey({ format: 'jwk', key } as JsonWebKeyInput)
}
export default parse
2 changes: 1 addition & 1 deletion src/runtime/node/key_to_jwk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ const keyToJWK: JWKExportFunction = (key: unknown): JWK => {
) {
throw new JOSENotSupported('Unsupported key asymmetricKeyType')
}
return <JWK>keyObject.export({ format: 'jwk' })
return keyObject.export({ format: 'jwk' }) as JWK
}
export default keyToJWK
4 changes: 2 additions & 2 deletions src/runtime/node/node_key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ export default function keyForCrypto<KeyObjectOptions, JWKOptions>(
}

if (isJWK) {
return <JWKOptions>{ format: 'jwk', key, ...options }
return { format: 'jwk', key, ...options } as JWKOptions
}

return options ? <KeyObjectOptions>{ ...options, key } : <KeyObject>key
return options ? ({ ...options, key } as KeyObjectOptions) : (key as KeyObject)
}
2 changes: 1 addition & 1 deletion src/runtime/node/sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const sign: SignFunction = async (alg, key: unknown, data) => {
const k = getSignKey(alg, key, 'sign')

if (alg.startsWith('HS')) {
const hmac = crypto.createHmac(hmacDigest(alg), <KeyObject>k)
const hmac = crypto.createHmac(hmacDigest(alg), k as KeyObject)
hmac.update(data)
return hmac.digest()
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/node/webcrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as crypto from 'node:crypto'
import * as util from 'node:util'

// @ts-ignore
const webcrypto = <Crypto>crypto.webcrypto
const webcrypto = crypto.webcrypto as Crypto

export default webcrypto

Expand Down
2 changes: 1 addition & 1 deletion src/util/decode_protected_header.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function decodeProtectedHeader(token: string | object): ProtectedHeaderPa
if (!isObject(result)) {
throw new Error()
}
return <ProtectedHeaderParameters>result
return result as ProtectedHeaderParameters
} catch {
throw new TypeError('Invalid Token or Protected Header formatting')
}
Expand Down
17 changes: 8 additions & 9 deletions tap/cookbook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,10 @@ export default (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
}

if (vector.encrypting_key && vector.encrypting_key.epk) {
keyManagementParameters.epk = <jose.KeyLike>(
await keys.importJWK(vector.encrypting_key.epk, vector.input.alg)
)
keyManagementParameters.epk = (await keys.importJWK(
vector.encrypting_key.epk,
vector.input.alg,
)) as jose.KeyLike
}

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

const privateKey = <jose.KeyLike>(
await keys.importJWK(
toJWK(vector.input.pwd || vector.input.key),
dir ? vector.input.enc : vector.input.alg,
)
)
const privateKey = (await keys.importJWK(
toJWK(vector.input.pwd || vector.input.key),
dir ? vector.input.enc : vector.input.alg,
)) as jose.KeyLike
let publicKey
if (privateKey.type === 'secret') {
publicKey = privateKey
Expand Down
10 changes: 6 additions & 4 deletions tap/generate_options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ export default async (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
for (const extractable of [undefined, true, false]) {
test(`secret CryptoKey extractable: ${extractable ?? 'default (false)'}`, async (t) => {
const expected = extractable ?? false
const secret = <CryptoKey>await keys.generateSecret('HS256', { extractable })
const secret = (await keys.generateSecret('HS256', { extractable })) as CryptoKey
t.equal(secret.extractable, expected)
})
}

for (const extractable of [undefined, true, false]) {
test(`CryptoKeyPair extractable: ${extractable ?? 'default (false)'}`, async (t) => {
const expected = extractable ?? false
const kp = <CryptoKeyPair>await keys.generateKeyPair('ES256', { extractable })
const kp = (await keys.generateKeyPair('ES256', { extractable })) as CryptoKeyPair
t.equal(kp.privateKey.extractable, expected)
t.equal(kp.publicKey.extractable, true)
})
Expand All @@ -30,10 +30,12 @@ export default async (QUnit: QUnit, lib: typeof jose, keys: typeof jose) => {
for (const modulusLength of [undefined, 2048, 3072]) {
test(`RSA modulusLength ${modulusLength ?? 'default (2048)'}`, async (t) => {
const expected = modulusLength ?? 2048
const { publicKey } = <CryptoKeyPair>await keys.generateKeyPair('RS256', { modulusLength })
const { publicKey } = (await keys.generateKeyPair('RS256', {
modulusLength,
})) as CryptoKeyPair

if (isWebCrypto) {
t.equal((<RsaHashedKeyAlgorithm>publicKey.algorithm).modulusLength, expected)
t.equal((publicKey.algorithm as RsaHashedKeyAlgorithm).modulusLength, expected)
// @ts-ignore
} else if (publicKey.asymmetricKeyDetails) {
// @ts-ignore
Expand Down
Loading

0 comments on commit c4dc24d

Please sign in to comment.