Use scrypt for api keys (#33)

This commit is contained in:
KM Koushik
2024-06-27 07:42:13 +10:00
committed by GitHub
parent 1beced823e
commit 57fcfbc9b6
10 changed files with 219 additions and 113 deletions

View File

@@ -1,6 +1,5 @@
import { PrismaAdapter } from "@auth/prisma-adapter";
import {
AuthOptions,
getServerSession,
type DefaultSession,
type NextAuthOptions,
@@ -9,7 +8,9 @@ import { type Adapter } from "next-auth/adapters";
import GitHubProvider from "next-auth/providers/github";
import EmailProvider from "next-auth/providers/email";
import GoogleProvider from "next-auth/providers/google";
import { Provider } from "next-auth/providers/index";
import { sendSignUpEmail } from "~/server/mailer";
import { env } from "~/env";
import { db } from "~/server/db";
@@ -116,17 +117,3 @@ export const authOptions: NextAuthOptions = {
* @see https://next-auth.js.org/configuration/nextjs
*/
export const getServerAuthSession = () => getServerSession(authOptions);
import { createHash } from "crypto";
import { sendSignUpEmail } from "./mailer";
import { Provider } from "next-auth/providers/index";
/**
* Hashes a token using SHA-256.
*
* @param {string} token - The token to be hashed.
* @returns {string} The hashed token.
*/
export function hashToken(token: string) {
return createHash("sha256").update(token).digest("hex");
}

View File

@@ -0,0 +1,19 @@
import { randomBytes, scryptSync } from "crypto";
export const createSecureHash = async (key: string) => {
const data = new TextEncoder().encode(key);
const salt = randomBytes(16).toString("hex");
const derivedKey = scryptSync(data, salt, 64);
return `${salt}:${derivedKey.toString("hex")}`;
};
export const verifySecureHash = async (key: string, hash: string) => {
const data = new TextEncoder().encode(key);
const [salt, storedHash] = hash.split(":");
const derivedKey = scryptSync(data, String(salt), 64);
return storedHash === derivedKey.toString("hex");
};

View File

@@ -0,0 +1,6 @@
import { customAlphabet } from "nanoid";
export const smallNanoid = customAlphabet(
"1234567890abcdefghijklmnopqrstuvwxyz",
10
);

View File

@@ -1,9 +1,9 @@
import TTLCache from "@isaacs/ttlcache";
import { Context } from "hono";
import { hashToken } from "../auth";
import { db } from "../db";
import { UnsendApiError } from "./api-error";
import { env } from "~/env";
import { getTeamAndApiKey } from "../service/api-service";
const rateLimitCache = new TTLCache({
ttl: 1000, // 1 second
@@ -34,17 +34,16 @@ export const getTeamFromToken = async (c: Context) => {
checkRateLimit(token);
const hashedToken = hashToken(token);
const teamAndApiKey = await getTeamAndApiKey(token);
const team = await db.team.findFirst({
where: {
apiKeys: {
some: {
tokenHash: hashedToken,
},
},
},
});
if (!teamAndApiKey) {
throw new UnsendApiError({
code: "FORBIDDEN",
message: "Invalid API token",
});
}
const { team, apiKey } = teamAndApiKey;
if (!team) {
throw new UnsendApiError({
@@ -57,7 +56,7 @@ export const getTeamFromToken = async (c: Context) => {
db.apiKey
.update({
where: {
tokenHash: hashedToken,
id: apiKey.id,
},
data: {
lastUsed: new Date(),

View File

@@ -1,7 +1,8 @@
import { ApiPermission } from "@prisma/client";
import { db } from "../db";
import { randomBytes } from "crypto";
import { hashToken } from "../auth";
import { smallNanoid } from "../nanoid";
import { createSecureHash, verifySecureHash } from "../crypto";
export async function addApiKey({
name,
@@ -13,8 +14,11 @@ export async function addApiKey({
teamId: number;
}) {
try {
const token = `us_${randomBytes(20).toString("hex")}`;
const hashedToken = hashToken(token);
const clientId = smallNanoid(10);
const token = randomBytes(16).toString("hex");
const hashedToken = await createSecureHash(token);
const apiKey = `us_${clientId}_${token}`;
await db.apiKey.create({
data: {
@@ -22,39 +26,46 @@ export async function addApiKey({
permission: permission,
teamId,
tokenHash: hashedToken,
partialToken: `${token.slice(0, 8)}...${token.slice(-5)}`,
partialToken: `${apiKey.slice(0, 6)}...${apiKey.slice(-3)}`,
clientId,
},
});
return token;
return apiKey;
} catch (error) {
console.error("Error adding API key:", error);
throw error;
}
}
export async function retrieveApiKey(token: string) {
const hashedToken = hashToken(token);
export async function getTeamAndApiKey(apiKey: string) {
const [, clientId, token] = apiKey.split("_") as [string, string, string];
const apiKeyRow = await db.apiKey.findUnique({
where: {
clientId,
},
});
if (!apiKeyRow) {
return null;
}
try {
const apiKey = await db.apiKey.findUnique({
const isValid = await verifySecureHash(token, apiKeyRow.tokenHash);
if (!isValid) {
return null;
}
const team = await db.team.findUnique({
where: {
tokenHash: hashedToken,
},
select: {
id: true,
name: true,
permission: true,
teamId: true,
partialToken: true,
id: apiKeyRow.teamId,
},
});
if (!apiKey) {
throw new Error("API Key not found");
}
return apiKey;
return { team, apiKey: apiKeyRow };
} catch (error) {
console.error("Error retrieving API key:", error);
throw error;
console.error("Error verifying API key:", error);
return null;
}
}

View File

@@ -1,13 +1,11 @@
import { SesSetting } from "@prisma/client";
import { db } from "../db";
import { env } from "~/env";
import { customAlphabet } from "nanoid";
import * as sns from "~/server/aws/sns";
import * as ses from "~/server/aws/ses";
import { EventType } from "@aws-sdk/client-sesv2";
import { EmailQueueService } from "./email-queue-service";
const nanoid = customAlphabet("1234567890abcdefghijklmnopqrstuvwxyz", 10);
import { smallNanoid } from "../nanoid";
const GENERAL_EVENTS: EventType[] = [
"BOUNCE",
@@ -75,7 +73,7 @@ export class SesSettingsService {
);
}
const idPrefix = nanoid(10);
const idPrefix = smallNanoid(10);
const setting = await db.sesSetting.create({
data: {