Skip to content

Instantly share code, notes, and snippets.

@yusukebe
Created May 17, 2025 01:54
Show Gist options
  • Save yusukebe/f0d51a0d1984b325940ec1b1de4c206e to your computer and use it in GitHub Desktop.
Save yusukebe/f0d51a0d1984b325940ec1b1de4c206e to your computer and use it in GitHub Desktop.
import { encodeBase64Url } from '../../utils/encode'
import { utf8Encoder } from '../../utils/jwt/utf8'
import { signing } from './jws'
import { verifyFromJwks } from './jwt'
describe('verifyFromJwks header.alg fallback', () => {
it('Should use header.alg as fallback when matchingKey.alg is missing', async () => {
// Setup: Create a JWT signed with HS384 (different from default HS256)
const payload = { message: 'hello world' }
const headerAlg = 'HS384' // Non-default value
const secret = 'secret'
const kid = 'dummy'
// Create JWT (signed with HS384)
const header = { alg: headerAlg, typ: 'JWT', kid }
const encode = (obj: object) => encodeBase64Url(utf8Encoder.encode(JSON.stringify(obj)).buffer)
const encodedHeader = encode(header)
const encodedPayload = encode(payload)
const signingInput = `${encodedHeader}.${encodedPayload}`
// Use signing function from jws.ts instead of createHmac directly
const signatureBuffer = await signing(secret, headerAlg, utf8Encoder.encode(signingInput))
const signature = encodeBase64Url(signatureBuffer)
const token = `${encodedHeader}.${encodedPayload}.${signature}`
// Create a key without alg property
const keys = [
{
kty: 'oct',
kid,
k: encodeBase64Url(utf8Encoder.encode(secret).buffer),
use: 'sig',
// alg is intentionally omitted
},
]
// Execute: Verify the JWT token signed with HS384
const result = await verifyFromJwks(token, { keys })
// If verification succeeds, it means header.alg was used
expect(result).toEqual(payload)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment