buffer.ts
This file
Path
src/utils/buffer.ts
80 lines · 1.9 KiB · TypeScript
Last changed by
fix(validator): cache `arrayBuffer` to use after validation (#1393)Yusuke Wadabefore adoption5cbd89c
History of this fileTake it
The walk stopped after 200 commits: lines older than d273210 point at it.
v3.0.4Yusuke Wadabefore adoptiond273210
lines 1–49why, one step back1import { sha256 } from './crypto'23export const equal = (a: ArrayBuffer, b: ArrayBuffer) => {4 if (a === b) {5 return true6 }7 if (a.byteLength !== b.byteLength) {8 return false9 }1011 const va = new DataView(a)12 const vb = new DataView(b)1314 let i = va.byteLength15 while (i--) {16 if (va.getUint8(i) !== vb.getUint8(i)) {17 return false18 }19 }2021 return true22}2324export const timingSafeEqual = async (25 a: string | object | boolean,26 b: string | object | boolean,27 hashFunction?: Function28) => {29 if (!hashFunction) {30 hashFunction = sha25631 }3233 const sa = await hashFunction(a)34 const sb = await hashFunction(b)3536 if (!sa || !sb) {37 return false38 }3940 return sa === sb && a === b41}4243export const bufferToString = (buffer: ArrayBuffer): string => {44 if (buffer instanceof ArrayBuffer) {45 const enc = new TextDecoder('utf-8')46 return enc.decode(buffer)47 }48 return buffer49}fix(validator): cache `arrayBuffer` to use after validation (#1393)Yusuke Wadabefore adoption5cbd89c
lines 50–80why, one step back5051const _decodeURIComponent = decodeURIComponent5253export const bufferToFormData = (arrayBuffer: ArrayBuffer, contentType: string) => {54 const decoder = new TextDecoder('utf-8')55 const content = decoder.decode(arrayBuffer)56 const formData = new FormData()5758 const boundaryMatch = contentType.match(/boundary=(.+)/)59 const boundary = boundaryMatch ? boundaryMatch[1] : ''6061 if (contentType.startsWith('multipart/form-data') && boundary) {62 const parts = content.split('--' + boundary).slice(1, -1)63 for (const part of parts) {64 const [header, body] = part.split('\r\n\r\n')65 const nameMatch = header.match(/name="([^"]+)"/)66 if (nameMatch) {67 const name = nameMatch[1]68 formData.append(name, body.trim())69 }70 }71 } else if (contentType.startsWith('application/x-www-form-urlencoded')) {72 const pairs = content.split('&')73 for (const pair of pairs) {74 const [key, value] = pair.split('=')75 formData.append(_decodeURIComponent(key), _decodeURIComponent(value))76 }77 }7879 return formData80}