Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Better Auth Utils

A simple typescript API for common auth utilities like hashing, encryption, encoding, and OTP generation. Built on top of Web Crypto APIs and it wraps over [uncrypto](https://github.com/unjs/uncrypto) to provide a unified API for both Node.js (using the Crypto module) and web environments (using the Web Crypto API) through Conditional Exports.
A simple typescript API for common auth utilities like hashing, encryption, encoding, and OTP generation. Built on top of Web Crypto APIs to provide a unified API for both Node.js (using the Crypto module) and web environments (using the Web Crypto API) through Conditional Exports.

```bash
pnpm add @better-auth/utils
Expand Down
9 changes: 2 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
"type": "git",
"url": "https://github.com/better-auth/utils"
},
"dependencies": {
"uncrypto": "^0.1.3"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@types/node": "^22.10.1",
Expand Down Expand Up @@ -81,7 +78,5 @@
"require": "./dist/rsa.cjs"
}
},
"files": [
"dist"
]
}
"files": ["dist"]
}
9 changes: 0 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 10 additions & 11 deletions src/ecdsa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@ import type {
SHAFamily,
TypedArray,
} from "./type";
import { getWebcryptoSubtle } from "./index";

export const ecdsa = {
generateKeyPair: async (curve: ECDSACurve = "P-256") => {
const keyPair = await crypto.subtle.generateKey(
const subtle = getWebcryptoSubtle();
const keyPair = await subtle.generateKey(
{
name: "ECDSA",
namedCurve: curve,
},
true,
["sign", "verify"],
);
const privateKey = await crypto.subtle.exportKey(
"pkcs8",
keyPair.privateKey,
);
const publicKey = await crypto.subtle.exportKey("spki", keyPair.publicKey);
const privateKey = await subtle.exportKey("pkcs8", keyPair.privateKey);
const publicKey = await subtle.exportKey("spki", keyPair.publicKey);
return { privateKey, publicKey };
},
importPrivateKey: async (
Expand All @@ -30,7 +29,7 @@ export const ecdsa = {
if (typeof privateKey === "string") {
privateKey = new TextEncoder().encode(privateKey);
}
return await crypto.subtle.importKey(
return await getWebcryptoSubtle().importKey(
"pkcs8",
privateKey,
{
Expand All @@ -49,7 +48,7 @@ export const ecdsa = {
if (typeof publicKey === "string") {
publicKey = new TextEncoder().encode(publicKey);
}
return await crypto.subtle.importKey(
return await getWebcryptoSubtle().importKey(
"spki",
publicKey,
{
Expand All @@ -68,7 +67,7 @@ export const ecdsa = {
if (typeof data === "string") {
data = new TextEncoder().encode(data);
}
const signature = await crypto.subtle.sign(
const signature = await getWebcryptoSubtle().sign(
{
name: "ECDSA",
hash: { name: hash },
Expand Down Expand Up @@ -97,7 +96,7 @@ export const ecdsa = {
if (typeof data === "string") {
data = new TextEncoder().encode(data);
}
return await crypto.subtle.verify(
return await getWebcryptoSubtle().verify(
{
name: "ECDSA",
hash: { name: hash },
Expand All @@ -111,6 +110,6 @@ export const ecdsa = {
key: CryptoKey,
format: E,
): Promise<E extends "jwk" ? JsonWebKey : ArrayBuffer> => {
return (await crypto.subtle.exportKey(format, key)) as any;
return (await getWebcryptoSubtle().exportKey(format, key)) as any;
},
};
4 changes: 2 additions & 2 deletions src/hash.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { subtle } from "uncrypto";
import { base64, base64Url } from "./base64";
import type { EncodingFormat, SHAFamily, TypedArray } from "./type";
import { getWebcryptoSubtle } from "./index";

export function createHash<Encoding extends EncodingFormat = "none">(
algorithm: SHAFamily,
Expand All @@ -12,7 +12,7 @@ export function createHash<Encoding extends EncodingFormat = "none">(
): Promise<Encoding extends "none" ? ArrayBuffer : string> => {
const encoder = new TextEncoder();
const data = typeof input === "string" ? encoder.encode(input) : input;
const hashBuffer = await subtle.digest(algorithm, data);
const hashBuffer = await getWebcryptoSubtle().digest(algorithm, data);

if (encoding === "hex") {
const hashArray = Array.from(new Uint8Array(hashBuffer));
Expand Down
8 changes: 4 additions & 4 deletions src/hmac.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { subtle } from "uncrypto";
import type { EncodingFormat, SHAFamily, TypedArray } from "./type";
import { hex } from "./hex";
import { base64, base64Url } from "./base64";
import { getWebcryptoSubtle } from "./index";

export const createHMAC = <E extends EncodingFormat = "none">(
algorithm: SHAFamily = "SHA-256",
Expand All @@ -12,7 +12,7 @@ export const createHMAC = <E extends EncodingFormat = "none">(
key: string | ArrayBuffer | TypedArray,
keyUsage: "sign" | "verify",
) => {
return subtle.importKey(
return getWebcryptoSubtle().importKey(
"raw",
typeof key === "string" ? new TextEncoder().encode(key) : key,
{ name: "HMAC", hash: { name: algorithm } },
Expand All @@ -27,7 +27,7 @@ export const createHMAC = <E extends EncodingFormat = "none">(
if (typeof hmacKey === "string") {
hmacKey = await hmac.importKey(hmacKey, "sign");
}
const signature = await subtle.sign(
const signature = await getWebcryptoSubtle().sign(
"HMAC",
hmacKey,
typeof data === "string" ? new TextEncoder().encode(data) : data,
Expand Down Expand Up @@ -64,7 +64,7 @@ export const createHMAC = <E extends EncodingFormat = "none">(
) {
signature = await base64.decode(signature);
}
return subtle.verify(
return getWebcryptoSubtle().verify(
"HMAC",
hmacKey,
typeof signature === "string"
Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export * from "uncrypto";
export function getWebcryptoSubtle(): SubtleCrypto {
const cr = typeof globalThis !== "undefined" && (globalThis as any).crypto;
if (cr && typeof cr.subtle === "object" && cr.subtle != null)
return cr.subtle;
throw new Error("crypto.subtle must be defined");
}
9 changes: 4 additions & 5 deletions src/random.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createRandomStringGenerator } from "./random";
import { getRandomValues } from "uncrypto";

// Utility functions for distribution tests
function generateLargeRandomSample(
Expand Down Expand Up @@ -108,7 +107,7 @@ describe("createRandomStringGenerator", () => {

it("combines multiple alphabets when passed during generation", () => {
// Mock getRandomValues to return sequentially increasing values
vi.mock("uncrypto", () => ({
vi.stubGlobal("crypto", {
getRandomValues: vi.fn(
<T extends ArrayBufferView | null>(array: T): T => {
if (array instanceof Uint8Array) {
Expand All @@ -119,7 +118,7 @@ describe("createRandomStringGenerator", () => {
return array;
},
),
}));
});

try {
const generator = createRandomStringGenerator("a-z");
Expand All @@ -138,7 +137,7 @@ describe("createRandomStringGenerator", () => {
expect(randomString).toHaveLength(256);
} finally {
// Restore the original implementation
vi.unmock("uncrypto");
vi.unstubAllGlobals();
}
});

Expand Down
4 changes: 1 addition & 3 deletions src/random.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { getRandomValues } from "uncrypto";

type Alphabet = "a-z" | "A-Z" | "0-9" | "-_";

function expandAlphabet(alphabet: Alphabet): string {
Expand Down Expand Up @@ -52,7 +50,7 @@ export function createRandomStringGenerator<A extends Alphabet>(

while (result.length < length) {
if (bufIndex >= bufLength) {
getRandomValues(buf);
crypto.getRandomValues(buf);
bufIndex = 0;
}

Expand Down
20 changes: 12 additions & 8 deletions src/rsa.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { subtle } from "uncrypto";
import { getWebcryptoSubtle } from "./index";

type ExportFormat = "jwk" | "spki" | "pkcs8";

Expand All @@ -7,7 +7,7 @@ export const rsa = {
modulusLength: 2048 | 4096 = 2048,
hash: "SHA-256" | "SHA-384" | "SHA-512" = "SHA-256",
) => {
return await subtle.generateKey(
return await getWebcryptoSubtle().generateKey(
{
name: "RSA-OAEP",
modulusLength,
Expand All @@ -22,14 +22,14 @@ export const rsa = {
key: CryptoKey,
format: E,
): Promise<E extends "jwk" ? JsonWebKey : ArrayBuffer> => {
return (await subtle.exportKey(format, key)) as any;
return (await getWebcryptoSubtle().exportKey(format, key)) as any;
},
importKey: async (
key: JsonWebKey,
usage: "encrypt" | "decrypt" = "encrypt",
hash: "SHA-256" | "SHA-384" | "SHA-512" = "SHA-256",
) => {
return await subtle.importKey(
return await getWebcryptoSubtle().importKey(
"jwk",
key,
{
Expand All @@ -46,10 +46,14 @@ export const rsa = {
) => {
const encodedData =
typeof data === "string" ? new TextEncoder().encode(data) : data;
return await subtle.encrypt({ name: "RSA-OAEP" }, key, encodedData);
return await getWebcryptoSubtle().encrypt(
{ name: "RSA-OAEP" },
key,
encodedData,
);
},
decrypt: async (key: CryptoKey, data: ArrayBuffer | ArrayBufferView) => {
return await subtle.decrypt({ name: "RSA-OAEP" }, key, data);
return await getWebcryptoSubtle().decrypt({ name: "RSA-OAEP" }, key, data);
},
sign: async (
key: CryptoKey,
Expand All @@ -58,7 +62,7 @@ export const rsa = {
) => {
const encodedData =
typeof data === "string" ? new TextEncoder().encode(data) : data;
return await subtle.sign(
return await getWebcryptoSubtle().sign(
{
name: "RSA-PSS",
saltLength,
Expand All @@ -84,7 +88,7 @@ export const rsa = {
}
const encodedData =
typeof data === "string" ? new TextEncoder().encode(data) : data;
return await subtle.verify(
return await getWebcryptoSubtle().verify(
{
name: "RSA-PSS",
saltLength,
Expand Down