refactor: create `utils/crypto.ts` (#118)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 4822077 · Browse files · 5 files·+93 added−73 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+93 added−73 removed
- tests:+26 added−27 removed
- other:+67 added−46 removed
Provenance
- Commit
bea8aef- Tree
3235462- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
4822077
5 files changed+93 added−73 removed
modified:src/middleware/basic-auth/basic-auth.ts+2 added-1 removed
1223456764 unmodified linesimport type { Context } from '../../context'import { timingSafeEqual, decodeBase64 } from '../../utils/buffer'import { timingSafeEqual } from '../../utils/buffer'import { decodeBase64 } from '../../utils/crypto'
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/const USER_PASS_REGEXP = /^([^:]*):(.*)$/
64 unmodified linesmodified:src/utils/buffer.test.ts+1 added-27 removed
11234567891011121314151617181920212223242526272829456734 unmodified linesimport { timingSafeEqual, sha256, decodeBase64 } from './buffer'import { timingSafeEqual } from './buffer'
describe('buffer', () => { const crypto = global.crypto beforeAll(() => { global.crypto = require('crypto').webcrypto }) 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',34 unmodified linesmodified:src/utils/buffer.ts+2 added-45 removed
12345613 unmodified lines20212223222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566242526274 unmodified linesimport { sha256 } from './crypto'
export const equal = (a: ArrayBuffer, b: ArrayBuffer) => { if (a === b) { return true }13 unmodified lines
return true}
export const decodeBase64 = (str: string) => { try { 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) } catch {}
try { const { Buffer } = require('buffer') return Buffer.from(str, 'base64').toString() } catch (e) { console.error('If you want to do "decodeBase64", polyfill "buffer" module.') throw e }}
export const sha256 = async (a: string | object | boolean): Promise<string> => { if (crypto && crypto.subtle) { const buffer = await crypto.subtle.digest( { name: 'SHA-256', }, new TextEncoder().encode(String(a)) ) const hash = Array.prototype.map .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2)) .join('') return hash }
try { const crypto = require('crypto') const hash = crypto.createHash('sha256').update(a).digest('hex') return hash } catch (e) { console.error('If you want to do "sha256", polyfill "crypto" module.') throw e }}
export const timingSafeEqual = async ( a: string | object | boolean, b: string | object | boolean) => {4 unmodified linesadded:src/utils/crypto.test.ts+25 added
12345678910111213141516171819202122232425import { sha256, sha1, decodeBase64 } from './crypto'
describe('crypto', () => { it('sha256', async () => { expect(await sha256('hono')).toBe( '8b3dc17add91b7e8f0b5109a389927d66001139cd9b03fa7b95f83126e1b2b23' ) expect(await sha256('炎')).toBe( '1fddc5a562ee1fbeb4fc6def7d4be4911fcdae4273b02ae3a507b170ba0ea169' ) expect(await sha256('abcdedf')).not.toBe('abcdef') })
it('sha1', async () => { expect(await sha1('hono')).toBe('28c7e86f5732391917876b45c06c626c04d77f39') expect(await sha1('炎')).toBe('d56e09ae2421b2b8a0b5ee5fdceaed663c8c9472') expect(await sha1('abcdedf')).not.toBe('abcdef') })
it('decodeBaes64', async () => { expect(await decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo') expect(await decodeBase64('54KO')).toBe('炎') expect(await decodeBase64('abcdedf')).not.toBe('abcdef') })})added:src/utils/crypto.ts+63 added
1+type Algorithm = {2+ name: string3+ alias: string4+}5+6+type Data = string | object | boolean7+8+export const sha256 = async (data: Data) => {9+ const algorithm: Algorithm = { name: 'SHA-256', alias: 'sha256' }10+ const hash = await createHash(data, algorithm)11+ return hash12+}13+14+export const sha1 = async (data: Data) => {15+ const algorithm: Algorithm = { name: 'SHA-1', alias: 'sha1' }16+ const hash = await createHash(data, algorithm)17+ return hash18+}19+20+export const createHash = async (data: Data, algorithm: Algorithm): Promise<string> => {21+ if (crypto && crypto.subtle) {22+ const buffer = await crypto.subtle.digest(23+ {24+ name: algorithm.name,25+ },26+ new TextEncoder().encode(String(data))27+ )28+ const hash = Array.prototype.map29+ .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))30+ .join('')31+ return hash32+ }33+34+ try {35+ const crypto = require('crypto')36+ const hash = crypto.createHash(algorithm.alias).update(data).digest('hex')37+ return hash38+ } catch (e) {39+ console.error(`If you want to create hash ${algorithm.name}, polyfill "crypto" module.`)40+ throw e41+ }42+}43+44+export const decodeBase64 = (str: string) => {45+ try {46+ const text = atob(str)47+ const length = text.length48+ const bytes = new Uint8Array(length)49+ for (let i = 0; i < length; i++) {50+ bytes[i] = text.charCodeAt(i)51+ }52+ const decoder = new TextDecoder()53+ return decoder.decode(bytes)54+ } catch {}55+56+ try {57+ const { Buffer } = require('buffer')58+ return Buffer.from(str, 'base64').toString()59+ } catch (e) {60+ console.error('If you want to do "decodeBase64", polyfill "buffer" module.')61+ throw e62+ }63+}