From 79155ef4e6b0f49373ee7a4dcfb1dd00a730433f Mon Sep 17 00:00:00 2001 From: Yi-Jyun Pan Date: Thu, 25 Sep 2025 01:14:03 +0800 Subject: [PATCH] refactor: use browser-native crypto.subtle to hash --- lib/apollo.ts | 2 +- lib/sha256.ts | 25 +++++++++++++++++++++++++ package.json | 1 - pnpm-lock.yaml | 9 --------- 4 files changed, 26 insertions(+), 11 deletions(-) create mode 100644 lib/sha256.ts diff --git a/lib/apollo.ts b/lib/apollo.ts index 9fa6a4d..af48ceb 100644 --- a/lib/apollo.ts +++ b/lib/apollo.ts @@ -1,8 +1,8 @@ import { HttpLink } from "@apollo/client"; import { ApolloClient, InMemoryCache } from "@apollo/client-integration-nextjs"; import { PersistedQueryLink } from "@apollo/client/link/persisted-queries"; -import { sha256 } from "crypto-hash"; import buildUri from "./build-uri"; +import { sha256 } from "./sha256"; /** * Create an Apollo Client instance that uses the upstream GraphQL API. diff --git a/lib/sha256.ts b/lib/sha256.ts new file mode 100644 index 0000000..dd3fa17 --- /dev/null +++ b/lib/sha256.ts @@ -0,0 +1,25 @@ +/** + * Ported from + */ + +export async function sha256(data: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(data)); + return bufferToHex(digest); +} + +// Pre-computed hex lookup table for fast conversion +const HEX_CHARS = "0123456789abcdef"; +const HEX_LUT: string[] = []; +for (let index = 0; index < 256; index++) { + HEX_LUT[index] = HEX_CHARS[(index >>> 4) & 0xF] + HEX_CHARS[index & 0xF]; +} + +export function bufferToHex(buffer: ArrayBuffer): string { + const bytes = new Uint8Array(buffer); + let hex = ""; + for (let index = 0; index < bytes.length; index++) { + hex += HEX_LUT[bytes[index]]; + } + + return hex; +} diff --git a/package.json b/package.json index c2cb471..834a252 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,6 @@ "babel-plugin-react-compiler": "19.1.0-rc.3", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", - "crypto-hash": "^4.0.0", "graphql": "^16.11.0", "lucide-react": "^0.544.0", "next": "15.6.0-canary.20", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ed7bbea..e2f174f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -79,9 +79,6 @@ importers: clsx: specifier: ^2.1.1 version: 2.1.1 - crypto-hash: - specifier: ^4.0.0 - version: 4.0.0 graphql: specifier: ^16.11.0 version: 16.11.0 @@ -2275,10 +2272,6 @@ packages: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} - crypto-hash@4.0.0: - resolution: {integrity: sha512-KkkFriWj2teXIJOmftIRavBL4q8A7EZV24Nn9sWhIR4hdeS8u+q2A2p0tWZ1m4xVoP1zs3VJjVwwAUnztBb8uw==} - engines: {node: '>=20'} - cssesc@3.0.0: resolution: {integrity: sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==} engines: {node: '>=4'} @@ -6575,8 +6568,6 @@ snapshots: shebang-command: 2.0.0 which: 2.0.2 - crypto-hash@4.0.0: {} - cssesc@3.0.0: {} csstype@3.1.3: {}