Skip to content
Myr

fix(jwt): support single-line PEM keys (#4889)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(jwt): support single-line PEM keys * test: remove useless tests for pem

authored by Hiển Đào Vinh · committed by GitHub · parent cf2d2b7 · Browse files · 2 files+34 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+34 added−1 removed

  • tests:+33 added−0 removed
  • other:+1 added−1 removed

2 files+34 added−1 removed

modified:src/utils/jwt/jws.ts+1 added-1 removed
46 unmodified lines
47 return await crypto.subtle.verify(algorithm, cryptoKey, signature, data)48}4950function pemToBinary(pem: string): Uint8Array<ArrayBuffer> {51 return decodeBase64(pem.replace(/-+(BEGIN|END).*/g, '').replace(/\s/g, ''))51 return decodeBase64(pem.replace(/-+(BEGIN|END).*?-+/g, '').replace(/\s/g, ''))52}5354async function importPrivateKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise<CryptoKey> {55 if (!crypto.subtle || !crypto.subtle.importKey) {
179 unmodified lines
modified:src/utils/jwt/jwt.test.ts+33 added
1571 unmodified lines
1572 expect(header.alg).toBe('HS256')1573 expect(header.typ).toBe('JWT')1574 })1575})15761577describe('PEM parsing', async () => {1578 const keyPair = await crypto.subtle.generateKey(1579 {1580 name: 'Ed25519',1581 },1582 true,1583 ['sign', 'verify']1584 )15851586 const exported = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey)1587 const base64Key = Buffer.from(exported).toString('base64')1588 const privateKey = `-----BEGIN PRIVATE KEY-----\n${base64Key}\n-----END PRIVATE KEY-----`15891590 it('should sign & verify with a normal private PEM key', async () => {1591 const payload = { sub: '123' }15921593 const token = await JWT.sign(payload, privateKey, 'EdDSA')1594 const verified = await JWT.verify(token, privateKey, 'EdDSA')15951596 expect(verified).toEqual(payload)1597 })15981599 it('should sign & verify with a single-line private PEM key', async () => {1600 const singleLinePrivateKey = privateKey.replace(/\n/g, '')1601 const payload = { sub: '123' }16021603 const token = await JWT.sign(payload, singleLinePrivateKey, 'EdDSA')1604 const verified = await JWT.verify(token, privateKey, 'EdDSA')16051606 expect(verified).toEqual(payload)1607 })1608})