Skip to content

Commit

Permalink
fix: Unicode problem about atob/btoa (#85)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored Feb 2, 2022
1 parent ebec91c commit 04bb4bb
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
33 changes: 28 additions & 5 deletions src/middleware/basic-auth/basic-auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,32 @@ describe('Basic Auth by Middleware', () => {
})

const app = new Hono()

const username = 'hono-user-a'
const password = 'hono-password-a'
const unicodePassword = '炎'

app.use(
'*',
'/auth/*',
basicAuth({
username,
password,
})
)
app.get('/', () => new Response('root'))

app.use(
'/auth-unicode/*',
basicAuth({
username: username,
password: unicodePassword,
})
)

app.get('/auth/*', () => new Response('auth'))
app.get('/auth-unicode/*', () => new Response('auth'))

it('Unauthorized', async () => {
const req = new Request('http://localhost/')
const req = new Request('http://localhost/auth/a')
const res = await app.dispatch(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
Expand All @@ -34,11 +46,22 @@ describe('Basic Auth by Middleware', () => {
it('Authorizated', async () => {
const credential = Buffer.from(username + ':' + password).toString('base64')

const req = new Request('http://localhost/')
const req = new Request('http://localhost/auth/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.dispatch(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe('auth')
})

it('Authorizated Unicode', async () => {
const credential = Buffer.from(username + ':' + unicodePassword).toString('base64')

const req = new Request('http://localhost/auth-unicode/a')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.dispatch(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe('root')
expect(await res.text()).toBe('auth')
})
})
11 changes: 9 additions & 2 deletions src/middleware/basic-auth/basic-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,15 @@ const auth = (req: Request) => {
}

function decodeBase64(str: string) {
if (atob && btoa) {
return atob(str)
if (atob) {
const text = atob(str)
const length = text.length
const bytes = new Uint8Array(length)
for (let i = 0; i < length; i++) {
bytes[i] = text.charCodeAt(i)
}
const decoder = new TextDecoder()
return decoder.decode(bytes)
} else {
const { Buffer } = require('buffer')
return Buffer.from(str, 'base64').toString()
Expand Down

0 comments on commit 04bb4bb

Please sign in to comment.