feat: Basic-auth with polyfill (#86)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: Basic-auth with polyfill Basic auth support Fastly Compute@Edge with polyfills * Try-cache * Add negative tests
authored by Yusuke Wada · committed by GitHub · parent 0297e17 · Browse files · 7 files·+83 added−55 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+83 added−55 removed
- tests:+17 added−13 removed
- other:+66 added−42 removed
Provenance
- Commit
d5280a1- Tree
a49771c- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
0297e17
7 files changed+83 added−55 removed
modified:examples/compute-at-edge/index.js+4 added-5 removed
11234556786789101112132 unmodified linesimport { Hono } from 'hono'import { Hono } from '../../dist/hono'import { basicAuth } from '../../dist/middleware/basic-auth/basic-auth'
const app = new Hono()
app.use('*', async (c, next) => { console.log(`[${c.req.method}] ${c.req.url}`) next()})app.use('/auth/*', basicAuth({ username: 'hono', password: 'acoolproject' }))
app.get('/', (c) => c.text('Hono!! Compute@Edge!!'))app.get('/auth/*', (c) => c.text('Your authorized!'))
app.get('/hello/:name', (c) => { return c.text(`Hello ${c.req.param('name')}!!!!!`)})2 unmodified linesmodified:examples/compute-at-edge/package.json+6 added-4 removed
7 unmodified lines8910111213141213141516171718192021222324252627282930317 unmodified lines "type": "git", "url": "https://github.com/yusukebe/hono.git" }, "homepage": "https://github.com/yusukebe/hono", "engines": { "node": "^16" }, "devDependencies": { "buffer": "^6.0.3", "core-js": "^3.19.1", "crypto-browserify": "^3.12.0", "process": "^0.11.10", "stream-browserify": "^3.0.0", "webpack": "^5.64.0", "webpack": "^5.68.0", "webpack-cli": "^4.9.1" }, "dependencies": { "@fastly/js-compute": "^0.2.1", "hono": "*" }, "scripts": { "prebuild": "webpack", "dev": "fastly compute serve", "build": "js-compute-runtime --skip-pkg bin/index.js bin/main.wasm", "deploy": "npm run build && fastly compute deploy" }}No newline at end of fileNo newline at end of filemodified:examples/compute-at-edge/webpack.config.js+9 added-1 removed
3 unmodified lines456788910111213141516171819202122233 unmodified lines entry: './index.js', optimization: { minimize: true, }, target: 'webworker', target: ['webworker'], output: { filename: 'index.js', path: path.resolve(__dirname, 'bin'), libraryTarget: 'this', }, resolve: { fallback: { buffer: require.resolve('buffer/'), crypto: require.resolve('crypto-browserify'), stream: require.resolve('stream-browserify'), process: require.resolve('process/browser'), }, }, mode: 'production',}modified:src/middleware/basic-auth/basic-auth.ts+1 added-17 removed
122345623 unmodified lines30313233343536373839404142434445464748493435363718 unmodified linesimport type { Context } from '../../context'import { timingSafeEqual } from '../../utils/buffer'import { timingSafeEqual, decodeBase64 } from '../../utils/buffer'
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/const USER_PASS_REGEXP = /^([^:]*):(.*)$/
23 unmodified lines
return { username: userPass[1], password: userPass[2] }}
function decodeBase64(str: string) { 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() }}
export const basicAuth = (options: { username: string; password: string; realm?: string }) => { if (!options.realm) { options.realm = 'Secure Area' }18 unmodified linesmodified:src/utils/buffer.test.ts+17 added-13 removed
1123452 unmodified lines8910111213141516171819202122232425262728298 unmodified lines3839404128293031323334353637383942434445464712 unmodified linesimport { timingSafeEqual } from './buffer'import { timingSafeEqual, sha256, decodeBase64 } from './buffer'
describe('buffer', () => { const crypto = global.crypto beforeAll(() => {2 unmodified lines afterAll(() => { global.crypto = crypto })
it('decodeBaes64', async () => { expect(await decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo') expect(await decodeBase64('54KO')).toBe('炎')
expect(await decodeBase64('abcdedf')).not.toBe('abcdef') })
it('sha256', async () => { expect(await sha256('hono')).toBe('8b3dc17add91b7e8f0b5109a389927d66001139cd9b03fa7b95f83126e1b2b23') expect(await sha256('炎')).toBe('1fddc5a562ee1fbeb4fc6def7d4be4911fcdae4273b02ae3a507b170ba0ea169')
expect(await sha256('abcdedf')).not.toBe('abcdef') })
it('positive', async () => { expect( await timingSafeEqual( '127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935',8 unmodified lines })
it('negative', async () => { expect(await timingSafeEqual('a', 'b')).toBe(false) expect( await timingSafeEqual( 'a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ) ).toBe(false) expect( await timingSafeEqual( 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a' ) ).toBe(false) expect(await timingSafeEqual('a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')).toBe(false) expect(await timingSafeEqual('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a')).toBe(false) expect(await timingSafeEqual('alpha', 'beta')).toBe(false) expect(await timingSafeEqual(false, true)).toBe(false) expect(await timingSafeEqual(false, undefined)).toBe(false) expect(12 unmodified linesmodified:src/utils/buffer.ts+45 added-14 removed
17 unmodified lines18 19 return true20 }21 22-export const timingSafeEqual = async (a: any, b: any) => {23- const sa = await crypto.subtle.digest(24- {25- name: 'SHA-256',26- },27- new TextEncoder().encode(String(a))28- )22+export const decodeBase64 = (str: string) => {23+ try {24+ const text = atob(str)25+ const length = text.length26+ const bytes = new Uint8Array(length)27+ for (let i = 0; i < length; i++) {28+ bytes[i] = text.charCodeAt(i)29+ }30+ const decoder = new TextDecoder()31+ return decoder.decode(bytes)32+ } catch {}33 30- const sb = await crypto.subtle.digest(31- {32- name: 'SHA-256',33- },34- new TextEncoder().encode(String(b))35- )34+ try {35+ const { Buffer } = require('buffer')36+ return Buffer.from(str, 'base64').toString()37+ } catch (e) {38+ console.error('If you want to do "decodeBase64", polyfill "buffer" module.')39+ throw e40+ }41+}42 37- return equal(sa, sb) && a === b43+export const sha256 = async (a: string): Promise<string> => {44+ if (crypto && crypto.subtle) {45+ const buffer = await crypto.subtle.digest(46+ {47+ name: 'SHA-256',48+ },49+ new TextEncoder().encode(String(a))50+ )51+ const hash = Array.prototype.map.call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2)).join('')52+ return hash53+ }54+55+ try {56+ const crypto = await import('crypto')57+ const hash = crypto.createHash('sha256').update(a).digest('hex')58+ return hash59+ } catch (e) {60+ console.error('If you want to do "sha256", polyfill "crypto" module.')61+ throw e62+ }63 }64+65+export const timingSafeEqual = async (a: any, b: any) => {66+ const sa = await sha256(a)67+ const sb = await sha256(b)68+ return sa === sb && a === b69+}modified:package.json+1 added-1 removed
1 {2 "name": "hono",3- "version": "0.3.2",3+ "version": "0.3.3-pre",4 "description": "[炎] Ultrafast web framework for Cloudflare Workers.",5 "main": "dist/index.js",6 "types": "dist/index.d.ts",7 "files": [95 unmodified lines