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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "ApiKey" ADD COLUMN "prefix" TEXT;
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ model ApiKey {
merchantId String
merchant Merchant @relation(fields: [merchantId], references: [id])
keyHash String @unique
prefix String?
name String?
lastUsedAt DateTime?
expiresAt DateTime?
Expand Down
66 changes: 66 additions & 0 deletions src/controllers/api-key.controllers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { Request, Response } from 'express';
import { createApiKey, listApiKeys, revokeApiKey } from '../services/api-key.services.js';
import { AppError } from '../utils/errors.js';

export const createApiKeyController = async (req: Request, res: Response): Promise<void> => {
const merchant = req.merchant;

if (!merchant) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

if (req.body?.label !== undefined && typeof req.body.label !== 'string') {
res.status(400).json({ error: 'label must be a string' });
return;
}

const label = typeof req.body?.label === 'string' ? req.body.label : undefined;

try {
const apiKey = await createApiKey(merchant.id, label);
res.status(201).json(apiKey);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
} catch (error) {
if (error instanceof AppError) {
res.status(error.statusCode).json({ error: error.message });
return;
}
res.status(500).json({ error: 'Internal Server Error' });
}
};

export const listApiKeysController = async (req: Request, res: Response): Promise<void> => {
const merchant = req.merchant;

if (!merchant) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

try {
const apiKeys = await listApiKeys(merchant.id);
res.status(200).json(apiKeys);
} catch {
res.status(500).json({ error: 'Internal Server Error' });
}
};

export const revokeApiKeyController = async (req: Request, res: Response): Promise<void> => {
const merchant = req.merchant;

if (!merchant) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

try {
await revokeApiKey(merchant.id, req.params.id);
res.status(200).json({ message: 'API key revoked' });
} catch (error) {
if (error instanceof AppError) {
res.status(error.statusCode).json({ error: error.message });
return;
}
res.status(500).json({ error: 'Internal Server Error' });
}
};
138 changes: 122 additions & 16 deletions src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,152 @@
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import prisma from '../config/prisma.js';
import { environment } from '../config/environment.js';
import { authenticateApiKey } from '../services/api-key.services.js';
import { isApiKeyToken } from '../utils/api-key.utils.js';

const extractBearerToken = (req: Request): string | null => {
const authHeader = req.headers.authorization;

if (!authHeader || !authHeader.startsWith('Bearer ')) {
return null;
}

const token = authHeader.slice('Bearer '.length).trim();
return token || null;
};

const authenticateRefreshToken = async (token: string) => {
const session = await prisma.refreshToken.findUnique({
where: { token },
include: { merchant: true },
});

if (!session || session.expiresAt.getTime() < Date.now()) {
return null;
}

return session.merchant;
};

const authenticateJwt = async (token: string) => {
try {
const payload = jwt.verify(token, environment.jwtSecret) as { sub?: string };
if (!payload.sub) {
return null;
}

return prisma.merchant.findUnique({ where: { id: payload.sub } });
} catch {
return null;
}
};

const resolveMerchantFromToken = async (token: string) => {
if (isApiKeyToken(token)) {
return authenticateApiKey(token);
}

if (token.split('.').length === 3) {
return authenticateJwt(token);
}

return authenticateRefreshToken(token);
};

/**
* Authenticates a merchant using a session bearer token.
*
* Expects an `Authorization: Bearer <token>` header that maps to a valid,
* non-expired MerchantSession. On success the resolved merchant is attached to
* `req.merchant`. Otherwise the request is rejected with 401.
* Authenticates API key bearer tokens, updates lastUsedAt, and attaches the merchant.
*/
export const authenticateMerchant = async (
export const apiKeyAuth = async (
req: Request,
res: Response,
next: NextFunction,
): Promise<void> => {
try {
const authHeader = req.headers.authorization;
const token = extractBearerToken(req);

if (!authHeader || !authHeader.startsWith('Bearer ')) {
if (!token || !isApiKeyToken(token)) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

const token = authHeader.slice('Bearer '.length).trim();
const merchant = await authenticateApiKey(token);
if (!merchant) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

req.merchant = merchant;
next();
} catch {
res.status(500).json({ error: 'Internal Server Error' });
}
};

/**
* Authenticates a merchant using refresh tokens or JWT access tokens only.
* API keys are rejected to prevent key-management operations via API keys.
*/
export const authenticateSessionOnly = async (
req: Request,
res: Response,
next: NextFunction,
): Promise<void> => {
try {
const token = extractBearerToken(req);

if (!token) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

const session = await prisma.refreshToken.findUnique({
where: { token },
include: { merchant: true },
});
if (isApiKeyToken(token)) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

const merchant =
token.split('.').length === 3
? await authenticateJwt(token)
: await authenticateRefreshToken(token);

if (!merchant) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

req.merchant = merchant;
next();
} catch {
res.status(500).json({ error: 'Internal Server Error' });
}
};

/**
* Authenticates a merchant using refresh tokens, JWT access tokens, or API keys.
*/
export const authenticateMerchant = async (
req: Request,
res: Response,
next: NextFunction,
): Promise<void> => {
try {
const token = extractBearerToken(req);

if (!token) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

if (!session || session.expiresAt.getTime() < Date.now()) {
const merchant = await resolveMerchantFromToken(token);
if (!merchant) {
res.status(401).json({ error: 'Unauthorized' });
return;
}

req.merchant = session.merchant;
req.merchant = merchant;
next();
} catch {
res.status(401).json({ error: 'Unauthorized' });
res.status(500).json({ error: 'Internal Server Error' });
}
};
10 changes: 9 additions & 1 deletion src/routes/merchant.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,19 @@ import {
listMerchantsController,
registerMerchantController,
} from '../controllers/merchant.controllers.js';
import { authenticateMerchant } from '../middlewares/auth.middleware.js';
import {
createApiKeyController,
listApiKeysController,
revokeApiKeyController,
} from '../controllers/api-key.controllers.js';
import { authenticateMerchant, authenticateSessionOnly } from '../middlewares/auth.middleware.js';

const router = Router();

router.post('/register', authenticateMerchant, registerMerchantController);
router.post('/api-keys', authenticateSessionOnly, createApiKeyController);
router.get('/api-keys', authenticateSessionOnly, listApiKeysController);
router.delete('/api-keys/:id', authenticateSessionOnly, revokeApiKeyController);
router.post('/', createMerchantController);
router.get('/:id', getMerchantController);
router.get('/', listMerchantsController);
Expand Down
131 changes: 131 additions & 0 deletions src/services/api-key.services.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { Merchant } from '@prisma/client';
import prisma from '../config/prisma.js';
import { AppError } from '../utils/errors.js';
import { generateApiKeyMaterial, hashApiKey, MAX_ACTIVE_API_KEYS } from '../utils/api-key.utils.js';

export type ApiKeySummary = {
id: string;
prefix: string;
label: string | null;
lastUsedAt: Date | null;
createdAt: Date;
};

export type CreateApiKeyResult = ApiKeySummary & {
key: string;
};

type ApiKeyListRow = {
id: string;
prefix: string | null;
name: string | null;
lastUsedAt: Date | null;
createdAt: Date;
};

const toApiKeySummary = (apiKey: ApiKeyListRow): ApiKeySummary => ({
id: apiKey.id,
prefix: apiKey.prefix ?? '',
label: apiKey.name,
lastUsedAt: apiKey.lastUsedAt,
createdAt: apiKey.createdAt,
});

const activeApiKeyWhere = (merchantId: string) => ({
merchantId,
revokedAt: null,
OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
});

export const createApiKey = async (
merchantId: string,
label?: string,
): Promise<CreateApiKeyResult> => {
const { rawKey, prefix, keyHash } = generateApiKeyMaterial();
const normalizedLabel = label?.trim() || null;

const apiKey = await prisma.$transaction(async tx => {
const activeKeys = await tx.apiKey.count({
where: activeApiKeyWhere(merchantId),
});

if (activeKeys >= MAX_ACTIVE_API_KEYS) {
throw new AppError(400, `Maximum of ${MAX_ACTIVE_API_KEYS} active API keys allowed`);
}

return tx.apiKey.create({
data: {
merchantId,
keyHash,
prefix,
name: normalizedLabel,
},
});
});

return {
...toApiKeySummary(apiKey),
key: rawKey,
};
};

export const listApiKeys = async (merchantId: string): Promise<ApiKeySummary[]> => {
const apiKeys = await prisma.apiKey.findMany({
where: {
merchantId,
revokedAt: null,
},
orderBy: { createdAt: 'desc' },
select: {
id: true,
prefix: true,
name: true,
lastUsedAt: true,
createdAt: true,
},
});

return apiKeys.map(toApiKeySummary);
};

export const revokeApiKey = async (merchantId: string, keyId: string): Promise<void> => {
const apiKey = await prisma.apiKey.findFirst({
where: { id: keyId, merchantId },
});

if (!apiKey) {
throw new AppError(404, 'API key not found');
}

if (apiKey.revokedAt) {
throw new AppError(400, 'API key already revoked');
}

await prisma.apiKey.update({
where: { id: keyId },
data: { revokedAt: new Date() },
});
};

export const authenticateApiKey = async (rawKey: string): Promise<Merchant | null> => {
const keyHash = hashApiKey(rawKey);
const apiKey = await prisma.apiKey.findUnique({
where: { keyHash },
include: { merchant: true },
});

if (!apiKey || apiKey.revokedAt) {
return null;
}

if (apiKey.expiresAt && apiKey.expiresAt.getTime() < Date.now()) {
return null;
}

await prisma.apiKey.update({
where: { id: apiKey.id },
data: { lastUsedAt: new Date() },
});

return apiKey.merchant;
};
Loading
Loading