Skip to content

chore: implement unjwt internally #400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@
"defu": "^6.1.4",
"h3": "^1.14.0",
"hookable": "^5.5.3",
"jose": "^5.9.6",
"ofetch": "^1.4.1",
"openid-client": "^6.1.7",
"pathe": "^2.0.2",
"scule": "^1.3.0",
"uncrypto": "^0.1.3"
"uncrypto": "^0.1.3",
"unjwt": "^0.5.5"
},
"peerDependencies": {
"@atproto/api": "^0.13.15",
Expand Down
23 changes: 16 additions & 7 deletions playground/middleware/jwt.global.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { appendResponseHeader } from 'h3'
import { parse, parseSetCookie, serialize } from 'cookie-es'
import type { JwtData } from '@tsndr/cloudflare-worker-jwt'
import { decode } from '@tsndr/cloudflare-worker-jwt'
import type { JWSVerifyResult, JWTClaims } from 'unjwt'
import { jws } from 'unjwt'

export default defineNuxtRouteMiddleware(async () => {
const nuxtApp = useNuxtApp()
Expand All @@ -16,17 +16,26 @@ export default defineNuxtRouteMiddleware(async () => {
const runtimeConfig = useRuntimeConfig()
const { accessToken, refreshToken } = session.value.jwt

const accessPayload = decode(accessToken)
const refreshPayload = decode(refreshToken)
// For demo purposes only, use high entropy secrets or keys in production
const accessTokenKey = new TextEncoder().encode(process.env.NUXT_SESSION_PASSWORD)
const refreshTokenKey = new TextEncoder().encode(`${process.env.NUXT_SESSION_PASSWORD}-secret`)

const [
verifiedAccessToken,
verifiedRefreshToken,
] = await Promise.all([
jws.verify<JWTClaims>(accessToken, accessTokenKey),
jws.verify<JWTClaims>(refreshToken, refreshTokenKey),
])

// Both tokens expired, clearing session
if (isExpired(accessPayload) && isExpired(refreshPayload)) {
if (isExpired(verifiedAccessToken) && isExpired(verifiedRefreshToken)) {
console.info('both tokens expired, clearing session')
await clearSession()
// return navigateTo('/login')
}
// Access token expired, refreshing
else if (isExpired(accessPayload)) {
else if (isExpired(verifiedAccessToken)) {
console.info('access token expired, refreshing')
await useRequestFetch()('/api/jwt/refresh', {
method: 'POST',
Expand Down Expand Up @@ -58,6 +67,6 @@ export default defineNuxtRouteMiddleware(async () => {
}
})

function isExpired(payload: JwtData) {
function isExpired(payload: JWSVerifyResult<JWTClaims>) {
return payload.payload?.exp && payload.payload.exp < (Date.now() / 1000)
}
1 change: 0 additions & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
"@iconify-json/gravity-ui": "^1.2.4",
"@iconify-json/iconoir": "^1.2.7",
"@iconify-json/logos": "^1.2.4",
"@tsndr/cloudflare-worker-jwt": "^3.1.3",
"@vueuse/core": "^12.5.0",
"@vueuse/nuxt": "^12.5.0",
"nuxt": "^3.15.4",
Expand Down
16 changes: 11 additions & 5 deletions playground/server/api/jwt/create.post.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import jwt from '@tsndr/cloudflare-worker-jwt'
import { jws } from 'unjwt'

export default defineEventHandler(async (event) => {
// Get user from session
Expand All @@ -17,20 +17,26 @@ export default defineEventHandler(async (event) => {
})
}

// For demo purposes only, use high entropy secrets or keys in production
const accessTokenKey = new TextEncoder().encode(process.env.NUXT_SESSION_PASSWORD)
const refreshTokenKey = new TextEncoder().encode(`${process.env.NUXT_SESSION_PASSWORD}-secret`)

// Generate tokens
const accessToken = await jwt.sign(
const accessToken = await jws.sign(
{
hello: 'world',
exp: Math.floor(Date.now() / 1000) + 5, // 30 seconds
},
process.env.NUXT_SESSION_PASSWORD,
accessTokenKey,
{ alg: 'HS256' },
)

const refreshToken = await jwt.sign(
const refreshToken = await jws.sign(
{
exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7, // 7 days
},
`${process.env.NUXT_SESSION_PASSWORD}-secret`,
refreshTokenKey,
{ alg: 'HS256' },
)

await setUserSession(event, {
Expand Down
9 changes: 5 additions & 4 deletions playground/server/api/jwt/payload.get.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import jwt from '@tsndr/cloudflare-worker-jwt'
import { verify } from 'unjwt/jws'

export default eventHandler(async (event) => {
const session = await getUserSession(event)
Expand All @@ -9,10 +9,11 @@ export default eventHandler(async (event) => {
})
}

// For demo purposes only, use a high entropy secret or key in production
const accessTokenKey = new TextEncoder().encode(process.env.NUXT_SESSION_PASSWORD)

try {
return await jwt.verify(session.jwt.accessToken, process.env.NUXT_SESSION_PASSWORD!, {
throwError: true,
})
return await verify(session.jwt.accessToken, accessTokenKey)
}
catch (err) {
throw createError({
Expand Down
22 changes: 18 additions & 4 deletions playground/server/api/jwt/refresh.post.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import jwt from '@tsndr/cloudflare-worker-jwt'
import type { JWSVerifyResult, JWTClaims } from 'unjwt'
import { sign, verify } from 'unjwt/jws'

export default eventHandler(async (event) => {
const session = await getUserSession(event)
Expand All @@ -9,19 +10,28 @@ export default eventHandler(async (event) => {
})
}

if (!await jwt.verify(session.jwt.refreshToken, `${process.env.NUXT_SESSION_PASSWORD!}-secret`)) {
// For demo purposes only, use high entropy secrets or keys in production
const accessTokenKey = new TextEncoder().encode(process.env.NUXT_SESSION_PASSWORD)
const refreshTokenKey = new TextEncoder().encode(`${process.env.NUXT_SESSION_PASSWORD}-secret`)

const verifiedRefreshToken = await verify<JWTClaims>(session.jwt.refreshToken, refreshTokenKey).catch(() => false as const)

if (!verifiedRefreshToken || isExpired(verifiedRefreshToken)) {
throw createError({
statusCode: 401,
message: 'refresh token is invalid',
})
}

const accessToken = await jwt.sign(
const accessToken = await sign(
{
hello: 'world',
exp: Math.floor(Date.now() / 1000) + 30, // 30 seconds
},
process.env.NUXT_SESSION_PASSWORD!,
accessTokenKey,
{
alg: 'HS256',
},
)

await setUserSession(event, {
Expand All @@ -37,3 +47,7 @@ export default eventHandler(async (event) => {
refreshToken: session.jwt.refreshToken,
}
})

function isExpired(payload: JWSVerifyResult<JWTClaims>) {
return payload.payload?.exp && payload.payload.exp < (Date.now() / 1000)
}
Loading
Loading