Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

fix: add timeSafe checks for signed tokens and api keys

Mohamed Basseme8a138f103d4
diff --git a/packages/shared/signedTokens.test.ts b/packages/shared/signedTokens.test.ts
index 35c3bbf3..1e323ada 100644
--- a/packages/shared/signedTokens.test.ts
+++ b/packages/shared/signedTokens.test.ts
@@ -61,7 +61,19 @@ describe("signed tokens", () => {
const decoded: SignedTokenPayload = JSON.parse(
Buffer.from(token, "base64").toString(),
);
- decoded.signature = "tampered" + decoded.signature;
+ decoded.signature = `${decoded.signature[0] === "0" ? "1" : "0"}${decoded.signature.slice(1)}`;
+ const tampered = Buffer.from(JSON.stringify(decoded)).toString("base64");
+ const verified = verifySignedToken(tampered, SECRET, testSchema);
+ expect(verified).toBeNull();
+ });
+
+ it("should return null for a malformed signature", () => {
+ const token = createSignedToken(testPayload, SECRET);
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ const decoded: SignedTokenPayload = JSON.parse(
+ Buffer.from(token, "base64").toString(),
+ );
+ decoded.signature = "not-a-hex-signature";
const tampered = Buffer.from(JSON.stringify(decoded)).toString("base64");
const verified = verifySignedToken(tampered, SECRET, testSchema);
expect(verified).toBeNull();
diff --git a/packages/shared/signedTokens.ts b/packages/shared/signedTokens.ts
index 14a26f60..d5561232 100644
--- a/packages/shared/signedTokens.ts
+++ b/packages/shared/signedTokens.ts
@@ -88,9 +88,13 @@ export function verifySignedToken<T>(
const expectedSignature = crypto
.createHmac("sha256", secret)
.update(JSON.stringify(payload))
- .digest("hex");
+ .digest();
+ const actualSignature = Buffer.from(signature, "hex");
- if (signature !== expectedSignature) {
+ if (
+ actualSignature.length !== expectedSignature.length ||
+ !crypto.timingSafeEqual(actualSignature, expectedSignature)
+ ) {
return null;
}
// Check expiry
diff --git a/packages/trpc/auth.ts b/packages/trpc/auth.ts
index 2ba5017b..3a4c2c9b 100644
--- a/packages/trpc/auth.ts
+++ b/packages/trpc/auth.ts
@@ -1,4 +1,4 @@
-import { createHash, randomBytes } from "crypto";
+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import * as bcrypt from "bcryptjs";
import { and, eq } from "drizzle-orm";
@@ -124,10 +124,14 @@ export async function authenticateApiKey(key: string, database: Context["db"]) {
case 1:
validation = await bcrypt.compare(keySecret, hash);
break;
- case 2:
+ case 2: {
+ const candidateHash = createHash("sha256").update(keySecret).digest();
+ const expectedHash = Buffer.from(hash, "base64");
validation =
- createHash("sha256").update(keySecret).digest("base64") == hash;
+ candidateHash.length === expectedHash.length &&
+ timingSafeEqual(candidateHash, expectedHash);
break;
+ }
default:
throw new Error("Invalid API Key");
}