Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use asynchronous hashing #478

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
42 changes: 34 additions & 8 deletions src/lib/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { randomBytes, scryptSync, subtle } from "node:crypto";
import {
type BinaryLike,
randomBytes,
scrypt,
subtle,
timingSafeEqual,
} from "node:crypto";
import { customId } from "@/common/id";

export const createHash = async (key: string) => {
Expand All @@ -25,18 +31,38 @@ export const initializeAccessToken = ({
};
};

export const createSecureHash = (secret: string) => {
const scryptAsync = (
password: BinaryLike,
salt: BinaryLike,
keylen: number,
): Promise<Buffer> => {
return new Promise((resolve, reject) => {
scrypt(password, salt, keylen, (err, derivedKey) => {
if (err) reject(err);
else resolve(derivedKey);
});
});
};

export const createSecureHash = async (secret: string) => {
const data = new TextEncoder().encode(secret);
const salt = randomBytes(32).toString("hex");
const derivedKey = scryptSync(data, salt, 64);
const derivedKey = await scryptAsync(data, salt, 64);

return `${salt}:${derivedKey.toString("hex")}`;
};

export const verifySecureHash = (secret: string, hash: string) => {
const data = new TextEncoder().encode(secret);
const [salt, storedHash] = hash.split(":");
const derivedKey = scryptSync(data, String(salt), 64);
export const verifySecureHash = async (secret: string, hash: string) => {
try {
const data = new TextEncoder().encode(secret);
const [salt, storedHash] = hash.split(":");

const derivedKey = await scryptAsync(data, salt ?? "", 64);

return storedHash === derivedKey.toString("hex");
const derivedKeyBuffer = Buffer.from(derivedKey);
const storedHashBuffer = Buffer.from(storedHash ?? "", "hex");
return timingSafeEqual(derivedKeyBuffer, storedHashBuffer);
} catch (_error) {
return false;
}
};
14 changes: 5 additions & 9 deletions src/server/api/middlewares/bearer-token.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { verifySecureHash } from "@/lib/crypto";
import type { Context } from "hono";
import { createMiddleware } from "hono/factory";
import { nanoid } from "nanoid";
import { ApiError } from "../error";

export type accessTokenAuthMiddlewareOptions =
Expand Down Expand Up @@ -46,21 +47,16 @@ async function authenticateWithAccessToken(
});
}

const accessToken = await findAccessToken(clientId, c);
const randomId = nanoid();

if (!accessToken) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The early bailout is vulnerable to timing attacks because the attacker can verify whether the ID exists in the database based on the timing.

throw new ApiError({
code: "UNAUTHORIZED",
message: "Bearer token is invalid",
});
}
const accessToken = await findAccessToken(clientId, c);

const isAccessTokenValid = await verifySecureHash(
clientSecret,
accessToken.clientSecret,
accessToken?.clientSecret ?? randomId,
);

if (!isAccessTokenValid) {
if (!isAccessTokenValid || !accessToken) {
throw new ApiError({
code: "UNAUTHORIZED",
message: "Bearer token is invalid",
Expand Down