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 ac014f2 commit a0ccf56
Show file tree
Hide file tree
Showing 23 changed files with 100 additions and 99 deletions.
6 changes: 3 additions & 3 deletions conformance/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export async function createTestPlan(
throw new Error(await response.text())
}

return <Plan>await response.json()
return (await response.json()) as Plan
}

export async function getTestPlanInfo(plan: Plan) {
Expand All @@ -70,7 +70,7 @@ export async function getTestPlanInfo(plan: Plan) {
throw new Error(await response.text())
}

return <PlanInfo>await response.json()
return (await response.json()) as PlanInfo
}

export async function getTestExposed(test: Test): Promise<Record<string, string>> {
Expand Down Expand Up @@ -120,7 +120,7 @@ async function getModuleInfo(module: Test) {
throw new Error(await response.text())
}

return <ModuleInfo>await response.json()
return (await response.json()) as ModuleInfo
}

export async function downloadArtifact(plan: Plan) {
Expand Down
28 changes: 14 additions & 14 deletions conformance/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,24 +231,24 @@ export const flow = (options?: MacroOptions) => {

switch (endpoint) {
case 'token':
return <oauth.TokenEndpointRequestOptions>{
return {
[oauth.useMtlsAlias]: mtlsAuth || mtlsConstrain ? true : false,
[oauth.customFetch]: mtlsAuth || mtlsConstrain ? mtlsFetch : undefined,
}
} as oauth.TokenEndpointRequestOptions
case 'par':
return <oauth.PushedAuthorizationRequestOptions>{
return {
[oauth.useMtlsAlias]: mtlsAuth ? true : false,
[oauth.customFetch]: mtlsAuth ? mtlsFetch : undefined,
}
} as oauth.PushedAuthorizationRequestOptions
case 'userinfo':
return <oauth.UserInfoRequestOptions>{
return {
[oauth.useMtlsAlias]: mtlsConstrain ? true : false,
[oauth.customFetch]: mtlsConstrain ? mtlsFetch : undefined,
}
} as oauth.UserInfoRequestOptions
case 'resource':
return <oauth.ProtectedResourceRequestOptions>{
return {
[oauth.customFetch]: mtlsConstrain ? mtlsFetch : undefined,
}
} as oauth.ProtectedResourceRequestOptions
default:
throw new Error()
}
Expand Down Expand Up @@ -310,7 +310,7 @@ export const flow = (options?: MacroOptions) => {

let DPoP!: CryptoKeyPair
if (usesDpop(variant)) {
DPoP = await oauth.generateKeyPair(<oauth.JWSAlgorithm>JWS_ALGORITHM)
DPoP = await oauth.generateKeyPair(JWS_ALGORITHM as oauth.JWSAlgorithm)
authorizationUrl.searchParams.set(
'dpop_jkt',
await calculateJwkThumbprint(await exportJWK(DPoP.publicKey)),
Expand Down Expand Up @@ -379,7 +379,7 @@ export const flow = (options?: MacroOptions) => {
as,
client,
currentUrl,
<string>nonce,
nonce as string,
state,
)
} else {
Expand All @@ -397,7 +397,7 @@ export const flow = (options?: MacroOptions) => {
oauth.authorizationCodeGrantRequest(
as,
client,
<Exclude<typeof params, oauth.OAuth2Error>>params,
params as Exclude<typeof params, oauth.OAuth2Error>,
configuration.client.redirect_uri,
code_verifier,
{
Expand Down Expand Up @@ -570,7 +570,7 @@ export const rejects = (macro: Macro<[module: ModulePrescription], { instance: T
expectedErrorName: string = 'OperationProcessingError',
) {
await t
.throwsAsync(() => <any>macro.exec(t, { ...module, skipLogTestFinished: true }), {
.throwsAsync(() => macro.exec(t, { ...module, skipLogTestFinished: true }) as any, {
message: expectedMessage,
name: expectedErrorName,
})
Expand All @@ -587,7 +587,7 @@ export const rejects = (macro: Macro<[module: ModulePrescription], { instance: T
t.log('Test Finished')
t.pass()
},
title: <any>macro.title,
title: macro.title as any,
})
}

Expand All @@ -600,6 +600,6 @@ export const skippable = (macro: Macro<[module: ModulePrescription], { instance:
t.log('Test Finished')
t.pass()
},
title: <any>macro.title,
title: macro.title as any,
})
}
65 changes: 33 additions & 32 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1521,7 +1521,7 @@ function clientSecretBasic(clientId: string, clientSecret: string) {
* Determines an RSASSA-PSS algorithm identifier from CryptoKey instance properties.
*/
function psAlg(key: CryptoKey): JWSAlgorithm {
switch ((<RsaHashedKeyAlgorithm>key.algorithm).hash.name) {
switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {
case 'SHA-256':
return 'PS256'
case 'SHA-384':
Expand All @@ -1537,7 +1537,7 @@ function psAlg(key: CryptoKey): JWSAlgorithm {
* Determines an RSASSA-PKCS1-v1_5 algorithm identifier from CryptoKey instance properties.
*/
function rsAlg(key: CryptoKey): JWSAlgorithm {
switch ((<RsaHashedKeyAlgorithm>key.algorithm).hash.name) {
switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {
case 'SHA-256':
return 'RS256'
case 'SHA-384':
Expand All @@ -1553,7 +1553,7 @@ function rsAlg(key: CryptoKey): JWSAlgorithm {
* Determines an ECDSA algorithm identifier from CryptoKey instance properties.
*/
function esAlg(key: CryptoKey): JWSAlgorithm {
switch ((<EcKeyAlgorithm>key.algorithm).namedCurve) {
switch ((key.algorithm as EcKeyAlgorithm).namedCurve) {
case 'P-256':
return 'ES256'
case 'P-384':
Expand Down Expand Up @@ -2048,7 +2048,7 @@ export function isOAuth2Error(
| URLSearchParams
| UserInfoResponse,
): input is OAuth2Error {
const value = <unknown>input
const value = input as unknown
if (typeof value !== 'object' || Array.isArray(value) || value === null) {
return false
}
Expand Down Expand Up @@ -2093,7 +2093,7 @@ const SCHEMES_REGEXP = /(?:^|, ?)([0-9a-zA-Z!#$%&'*+\-.^_`|~]+)(?=$|[ ,])/g
function wwwAuth(scheme: string, params: string): WWWAuthenticateChallenge {
const arr = params.split(SPLIT_REGEXP).slice(1)
if (!arr.length) {
return { scheme: <Lowercase<string>>scheme.toLowerCase(), parameters: {} }
return { scheme: scheme.toLowerCase() as Lowercase<string>, parameters: {} }
}
arr[arr.length - 1] = arr[arr.length - 1].replace(/,$/, '')
const parameters: WWWAuthenticateChallenge['parameters'] = {}
Expand All @@ -2104,13 +2104,13 @@ function wwwAuth(scheme: string, params: string): WWWAuthenticateChallenge {
arr[idx] += arr[i]
}
}
const key = <Lowercase<string>>arr[idx - 1].replace(/^(?:, ?)|=$/g, '').toLowerCase()
const key = arr[idx - 1].replace(/^(?:, ?)|=$/g, '').toLowerCase() as Lowercase<string>
// @ts-expect-error
parameters[key] = unquote(arr[idx])
}

return {
scheme: <Lowercase<string>>scheme.toLowerCase(),
scheme: scheme.toLowerCase() as Lowercase<string>,
parameters,
}
}
Expand Down Expand Up @@ -2618,7 +2618,7 @@ export async function processUserInfoResponse(
.then(validateOptionalIssuer.bind(undefined, as.issuer))

jwtResponseBodies.set(response, jwt)
json = <JsonValue>claims
json = claims as JsonValue
} else {
if (client.userinfo_signed_response_alg) {
throw new OPE('JWT UserInfo Response expected')
Expand Down Expand Up @@ -3018,12 +3018,12 @@ async function processGenericAccessTokenResponse(

if (
claims.auth_time !== undefined &&
(!Number.isFinite(claims.auth_time) || Math.sign(<number>claims.auth_time) !== 1)
(!Number.isFinite(claims.auth_time) || Math.sign(claims.auth_time as number) !== 1)
) {
throw new OPE('ID Token "auth_time" (authentication time) must be a positive number')
}

idTokenClaims.set(json, [<IDToken>claims, jwt])
idTokenClaims.set(json, [claims as IDToken, jwt])
}
}

Expand Down Expand Up @@ -3386,7 +3386,7 @@ export async function processAuthorizationCodeOpenIDResponse(
}
}

return <OpenIDTokenEndpointResponse>result
return result as OpenIDTokenEndpointResponse
}

/**
Expand Down Expand Up @@ -3427,7 +3427,7 @@ export async function processAuthorizationCodeOAuth2Response(
delete result.id_token
}

return <OAuth2TokenEndpointResponse>result
return result as OAuth2TokenEndpointResponse
}

function checkJwtType(expected: string, result: Awaited<ReturnType<typeof validateJwt>>) {
Expand Down Expand Up @@ -3534,7 +3534,7 @@ export async function processClientCredentialsResponse(
return result
}

return <ClientCredentialsGrantResponse>result
return result as ClientCredentialsGrantResponse
}

export interface RevocationRequestOptions extends HttpRequestOptions, AuthenticatedRequestOptions {
Expand Down Expand Up @@ -3763,7 +3763,7 @@ export async function processIntrospectionResponse(
.then(validateAudience.bind(undefined, client.client_id))

jwtResponseBodies.set(response, jwt)
json = <JsonValue>claims.token_introspection
json = claims.token_introspection as JsonValue
if (!isJsonObject(json)) {
throw new OPE('JWT "token_introspection" claim must be a JSON object')
}
Expand All @@ -3783,7 +3783,7 @@ export async function processIntrospectionResponse(
throw new OPE('"response" body "active" property must be a boolean')
}

return <IntrospectionResponse>json
return json as IntrospectionResponse
}

async function jwksRequest(
Expand Down Expand Up @@ -3860,15 +3860,15 @@ async function handleOAuthBodyError(response: Response): Promise<OAuth2Error | u
if (json.scope !== undefined && typeof json.scope !== 'string') {
delete json.scope
}
return <OAuth2Error>json
return json as OAuth2Error
}
} catch {}
}
return undefined
}

function checkSupportedJwsAlg(alg: unknown) {
if (!SUPPORTED_JWS_ALGS.includes(<any>alg)) {
if (!SUPPORTED_JWS_ALGS.includes(alg as any)) {
throw new UnsupportedOperationError('unsupported JWS "alg" identifier')
}
return alg
Expand Down Expand Up @@ -3896,27 +3896,27 @@ function ecdsaHashName(namedCurve: string) {
function keyToSubtle(key: CryptoKey): AlgorithmIdentifier | RsaPssParams | EcdsaParams {
switch (key.algorithm.name) {
case 'ECDSA':
return <EcdsaParams>{
return {
name: key.algorithm.name,
hash: ecdsaHashName((<EcKeyAlgorithm>key.algorithm).namedCurve),
}
hash: ecdsaHashName((key.algorithm as EcKeyAlgorithm).namedCurve),
} as EcdsaParams
case 'RSA-PSS': {
checkRsaKeyAlgorithm(<RsaHashedKeyAlgorithm>key.algorithm)
switch ((<RsaHashedKeyAlgorithm>key.algorithm).hash.name) {
checkRsaKeyAlgorithm(key.algorithm as RsaHashedKeyAlgorithm)
switch ((key.algorithm as RsaHashedKeyAlgorithm).hash.name) {
case 'SHA-256': // Fall through
case 'SHA-384': // Fall through
case 'SHA-512':
return <RsaPssParams>{
return {
name: key.algorithm.name,
saltLength:
parseInt((<RsaHashedKeyAlgorithm>key.algorithm).hash.name.slice(-3), 10) >> 3,
}
parseInt((key.algorithm as RsaHashedKeyAlgorithm).hash.name.slice(-3), 10) >> 3,
} as RsaPssParams
default:
throw new UnsupportedOperationError()
}
}
case 'RSASSA-PKCS1-v1_5':
checkRsaKeyAlgorithm(<RsaHashedKeyAlgorithm>key.algorithm)
checkRsaKeyAlgorithm(key.algorithm as RsaHashedKeyAlgorithm)
return key.algorithm.name
case 'Ed448': // Fall through
case 'Ed25519':
Expand Down Expand Up @@ -4290,7 +4290,7 @@ export async function validateDetachedSignatureResponse(

if (
claims.auth_time !== undefined &&
(!Number.isFinite(claims.auth_time) || Math.sign(<number>claims.auth_time) !== 1)
(!Number.isFinite(claims.auth_time) || Math.sign(claims.auth_time as number) !== 1)
) {
throw new OPE('ID Token "auth_time" (authentication time) must be a positive number')
}
Expand All @@ -4310,7 +4310,7 @@ export async function validateDetachedSignatureResponse(

const now = epochTime() + getClockSkew(client)
const tolerance = getClockTolerance(client)
if ((<IDToken>claims).auth_time! + maxAge < now - tolerance) {
if ((claims as IDToken).auth_time! + maxAge < now - tolerance) {
throw new OPE('too much time has elapsed since the last End-User authentication')
}
}
Expand Down Expand Up @@ -4751,9 +4751,10 @@ export async function generateKeyPair(
})
}

return <Promise<CryptoKeyPair>>(
crypto.subtle.generateKey(algorithm, options?.extractable ?? false, ['sign', 'verify'])
)
return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [
'sign',
'verify',
]) as Promise<CryptoKeyPair>
}

export interface JWTAccessTokenClaims extends JWTPayload {
Expand Down Expand Up @@ -5031,7 +5032,7 @@ export async function validateJwtAccessToken(
await validateDPoP(as, request, accessToken, claims, options)
}

return <JWTAccessTokenClaims>claims
return claims as JWTAccessTokenClaims
}

/**
Expand Down
12 changes: 6 additions & 6 deletions tap/callback.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type QUnit from 'qunit'
import * as lib from '../src/index.js'

const client = <lib.Client>{
const client = {
client_id: 'urn:example:client_id',
}
} as lib.Client
const identifier = 'https://op.example.com'
const issuer = <lib.AuthorizationServer>{
const issuer = {
issuer: identifier,
}
} as lib.AuthorizationServer

export default (QUnit: QUnit) => {
const { module, test } = QUnit
Expand Down Expand Up @@ -60,7 +60,7 @@ export default (QUnit: QUnit) => {

test('validateAuthResponse() error conditions', (t) => {
t.throws(
() => lib.validateAuthResponse(issuer, client, <any>null, lib.expectNoState),
() => lib.validateAuthResponse(issuer, client, null as any, lib.expectNoState),
(err: Error) => {
t.propContains(err, {
message: '"parameters" must be an instance of URLSearchParams, or URL',
Expand Down Expand Up @@ -142,7 +142,7 @@ export default (QUnit: QUnit) => {
issuer,
client,
new URLSearchParams('code=foo&state=foo'),
<any>null,
null as any,
),
(err: Error) => {
t.propContains(err, { message: '"expectedState" must be a non-empty string' })
Expand Down
2 changes: 1 addition & 1 deletion tap/end2end-client-credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export default (QUnit: QUnit) => {
['client_credentials'],
encryption,
)
const DPoP = dpop ? await lib.generateKeyPair(<lib.JWSAlgorithm>alg) : undefined
const DPoP = dpop ? await lib.generateKeyPair(alg as lib.JWSAlgorithm) : undefined

const authenticated: lib.AuthenticatedRequestOptions = {
clientPrivateKey: authMethod === 'private_key_jwt' ? clientPrivateKey : undefined,
Expand Down
Loading

0 comments on commit a0ccf56

Please sign in to comment.