Skip to content

Commit

Permalink
ecdsa key generator & jwt exp verification
Browse files Browse the repository at this point in the history
  • Loading branch information
dmonad committed Mar 4, 2024
1 parent 3feec72 commit 3b2c642
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
14 changes: 14 additions & 0 deletions bin/0ecdsa-generate-keypair.js
@@ -0,0 +1,14 @@
import * as ecdsa from 'lib0/crypto/ecdsa'
import * as json from 'lib0/json'
import * as env from 'lib0/environment'

const prefix = env.getConf('name')

const keypair = await ecdsa.generateKeyPair({ extractable: true })
const privateJwk = json.stringify(await ecdsa.exportKeyJwk(keypair.privateKey))
const publicJwk = json.stringify(await ecdsa.exportKeyJwk(keypair.publicKey))

console.log(`
${prefix ? prefix.toUpperCase() + '_' : ''}PUBLIC="${publicJwk.replaceAll('"', '\\"')}"
${prefix ? prefix.toUpperCase() + '_' : ''}PRIVATE="${privateJwk.replaceAll('"', '\\"')}"
`)
13 changes: 13 additions & 0 deletions crypto.test.js
@@ -1,3 +1,4 @@
import * as time from './time.js'
import * as jose from 'lib0/crypto/jwt'
import * as aes from 'lib0/crypto/aes-gcm'
import * as rsa from 'lib0/crypto/rsa-oaep'
Expand Down Expand Up @@ -25,6 +26,18 @@ export const testJwt = async _tc => {
t.compare(verified.payload, payload)
const unverified = jose.unsafeDecode(jwt)
t.compare(verified, unverified)
t.info('expired jwt should not parse')
const payloadExpired = {
sub: '1234567890',
name: 'John Doe',
iat: 1516239022,
exp: time.getUnixTime() - 10
}
const jwtExpired = await jose.encodeJwt(privateKey, payloadExpired)
jose.unsafeDecode(jwtExpired)
t.failsAsync(async () => {
await jose.verifyJwt(publicKey, jwtExpired)
})
}

/**
Expand Down
7 changes: 6 additions & 1 deletion crypto/jwt.js
Expand Up @@ -3,6 +3,7 @@ import * as buffer from '../buffer.js'
import * as string from '../string.js'
import * as json from '../json.js'
import * as ecdsa from '../crypto/ecdsa.js'
import * as time from '../time.js'

/**
* @param {Object} data
Expand Down Expand Up @@ -45,9 +46,13 @@ export const verifyJwt = async (publicKey, jwt) => {
if (!verified) {
throw new Error('Invalid JWT')
}
const payload = _parse(payloadBase64)
if (payload.exp != null && time.getUnixTime() > payload.exp) {
throw new Error('Expired JWT')
}
return {
header: _parse(headerBase64),
payload: _parse(payloadBase64)
payload
}
}

Expand Down
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -13,7 +13,8 @@
},
"bin": {
"0gentesthtml": "./bin/gentesthtml.js",
"0serve": "./bin/0serve.js"
"0serve": "./bin/0serve.js",
"0ecdsa-generate-keypair": "./bin/0ecdsa-generate-keypair.js"
},
"exports": {
"./package.json": "./package.json",
Expand Down

0 comments on commit 3b2c642

Please sign in to comment.