-
Notifications
You must be signed in to change notification settings - Fork 7
feat(merchant): API key management service #22
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
Merged
codebestia
merged 2 commits into
ShadeProtocol:main
from
stiven-skyward:issue-14-api-keys
Jun 29, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
2 changes: 2 additions & 0 deletions
2
prisma/migrations/20260627120000_add_api_key_prefix/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| -- AlterTable | ||
| ALTER TABLE "ApiKey" ADD COLUMN "prefix" TEXT; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } 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' }); | ||
| } | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' }); | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| }; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.