Skip to content
Open
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
33 changes: 17 additions & 16 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { jwt } from '../src'

import { describe, expect, it } from 'bun:test'

const req = (path: string) => new Request(`http://localhost${path}`)
const post = (path: string, body = {}) =>
new Request(`http://localhost${path}`, {
method: 'POST',
Expand All @@ -13,34 +12,36 @@ const post = (path: string, body = {}) =>
body: JSON.stringify(body)
})

describe('Static Plugin', () => {
it('sign JWT', async () => {
describe('JWT Plugin', () => {
it('signs and verifies JWTs', async () => {
const app = new Elysia()
.use(
jwt({
name: 'jwt',
secret: 'A'
})
)
.post('/validate', ({ jwt, body }) => jwt.sign(body), {
body: t.Object({
name: t.String()
})
})
.post('/validate', ({ jwt, body: { name } }) => jwt.verify(name), {
.post('/sign', ({ jwt, body }) => jwt.sign(body), {
body: t.Object({ name: t.String() })
})
.post('/verify', ({ jwt, body: { token } }) => jwt.verify(token), {
body: t.Object({ token: t.String() })
})

const name = 'Shirokami'

const _sign = post('/sign', { name })
const token = await _sign.text()
const sign = await app.handle(post('/sign', { name }))
const token = await sign.text()
expect(token).toMatch(/^[A-Za-z0-9_-]{2,}(?:\.[A-Za-z0-9_-]{2,}){2}$/)

const _verified = post('/verify', { name })
const signed = (await _verified.json()) as {
name: string
}
const verify = await app.handle(post('/verify', { token }))
const signed = (await verify.json()) as { name: string } | false
expect(signed).toEqual({ name });

expect(name).toBe(signed.name)
const verifyForged = await app.handle(post("/verify", {
token: "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiU2hpcm9rYW1pIn0.SNUb0H5gYTJYPznYxN36glyJAubUelp8zxy53hYeUt4"
}));
const forged = (await verifyForged.json()) as { name: string } | false
expect(forged).toBe(false);
})
})