|
| 1 | +import type { Request, Response, NextFunction } from 'express'; |
| 2 | +import * as crypto from 'crypto'; |
| 3 | +import * as StellarSdk from '@stellar/stellar-sdk'; |
| 4 | +import type { AuthenticatedRequest } from '../types/auth.types.js'; |
| 5 | +import logger from '../logger.js'; |
| 6 | + |
| 7 | +const JWT_SECRET = process.env.JWT_SECRET ?? crypto.randomBytes(32).toString('hex'); |
| 8 | +const JWT_EXPIRY_SECONDS = 3600; // 1 hour max per spec |
| 9 | + |
| 10 | +const STELLAR_NETWORK = |
| 11 | + process.env.STELLAR_NETWORK === 'mainnet' |
| 12 | + ? StellarSdk.Networks.PUBLIC |
| 13 | + : StellarSdk.Networks.TESTNET; |
| 14 | + |
| 15 | +// In-memory challenge store: publicKey -> { nonce, expiresAt } |
| 16 | +const challenges = new Map<string, { nonce: string; expiresAt: number }>(); |
| 17 | + |
| 18 | +// ─── Minimal JWT (no external dep) ────────────────────────────────────────── |
| 19 | + |
| 20 | +function b64url(buf: Buffer | string): string { |
| 21 | + const b = typeof buf === 'string' ? Buffer.from(buf) : buf; |
| 22 | + return b.toString('base64url'); |
| 23 | +} |
| 24 | + |
| 25 | +function signJwt(payload: object): string { |
| 26 | + const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' })); |
| 27 | + const body = b64url(JSON.stringify(payload)); |
| 28 | + const sig = crypto |
| 29 | + .createHmac('sha256', JWT_SECRET) |
| 30 | + .update(`${header}.${body}`) |
| 31 | + .digest(); |
| 32 | + return `${header}.${body}.${b64url(sig)}`; |
| 33 | +} |
| 34 | + |
| 35 | +function verifyJwt(token: string): { publicKey: string } | null { |
| 36 | + try { |
| 37 | + const [header, body, sig] = token.split('.'); |
| 38 | + if (!header || !body || !sig) return null; |
| 39 | + const expected = crypto |
| 40 | + .createHmac('sha256', JWT_SECRET) |
| 41 | + .update(`${header}.${body}`) |
| 42 | + .digest(); |
| 43 | + if (!crypto.timingSafeEqual(Buffer.from(sig, 'base64url'), expected)) return null; |
| 44 | + const payload = JSON.parse(Buffer.from(body, 'base64url').toString()); |
| 45 | + if (payload.exp < Math.floor(Date.now() / 1000)) return null; |
| 46 | + return { publicKey: payload.sub }; |
| 47 | + } catch { |
| 48 | + return null; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +// ─── Challenge / Verify handlers ──────────────────────────────────────────── |
| 53 | + |
| 54 | +export function issueChallenge(req: Request, res: Response): void { |
| 55 | + const { publicKey } = req.body as { publicKey?: string }; |
| 56 | + if (!publicKey || !StellarSdk.StrKey.isValidEd25519PublicKey(publicKey)) { |
| 57 | + res.status(400).json({ error: 'Invalid publicKey' }); |
| 58 | + return; |
| 59 | + } |
| 60 | + const nonce = crypto.randomBytes(32).toString('hex'); |
| 61 | + challenges.set(publicKey, { nonce, expiresAt: Date.now() + 60_000 }); // 60s to sign |
| 62 | + res.json({ nonce, expiresAt: Date.now() + 60_000 }); |
| 63 | +} |
| 64 | + |
| 65 | +export function verifyChallenge(req: Request, res: Response): void { |
| 66 | + const { publicKey, signedTransaction } = req.body as { |
| 67 | + publicKey?: string; |
| 68 | + signedTransaction?: string; |
| 69 | + }; |
| 70 | + |
| 71 | + if (!publicKey || !signedTransaction) { |
| 72 | + res.status(400).json({ error: 'publicKey and signedTransaction required' }); |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + const challenge = challenges.get(publicKey); |
| 77 | + if (!challenge || challenge.expiresAt < Date.now()) { |
| 78 | + res.status(401).json({ error: 'Challenge expired or not found' }); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + try { |
| 83 | + const tx = StellarSdk.TransactionBuilder.fromXDR( |
| 84 | + signedTransaction, |
| 85 | + STELLAR_NETWORK, |
| 86 | + ) as StellarSdk.Transaction; |
| 87 | + |
| 88 | + if (tx.source !== publicKey) { |
| 89 | + res.status(401).json({ error: 'Transaction source does not match publicKey' }); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + // Verify the manage_data op contains our nonce |
| 94 | + const op = tx.operations[0] as StellarSdk.Operation.ManageData | undefined; |
| 95 | + if (!op || op.type !== 'manageData' || op.value?.toString('hex') !== challenge.nonce) { |
| 96 | + res.status(401).json({ error: 'Invalid challenge nonce in transaction' }); |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + const keypair = StellarSdk.Keypair.fromPublicKey(publicKey); |
| 101 | + const txHash = tx.hash(); |
| 102 | + const valid = tx.signatures.some((s) => { |
| 103 | + try { return keypair.verify(txHash, s.signature()); } catch { return false; } |
| 104 | + }); |
| 105 | + |
| 106 | + if (!valid) { |
| 107 | + res.status(401).json({ error: 'Invalid signature' }); |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + challenges.delete(publicKey); |
| 112 | + |
| 113 | + const now = Math.floor(Date.now() / 1000); |
| 114 | + const token = signJwt({ sub: publicKey, iat: now, exp: now + JWT_EXPIRY_SECONDS }); |
| 115 | + res.json({ token, expiresIn: JWT_EXPIRY_SECONDS }); |
| 116 | + } catch (err) { |
| 117 | + logger.error('[Auth] verifyChallenge error:', err); |
| 118 | + res.status(401).json({ error: 'Invalid signed transaction' }); |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +// ─── Auth middleware ───────────────────────────────────────────────────────── |
| 123 | + |
| 124 | +export function requireAuth(req: Request, res: Response, next: NextFunction): void { |
| 125 | + const header = req.headers.authorization; |
| 126 | + if (!header?.startsWith('Bearer ')) { |
| 127 | + res.status(401).json({ error: 'Unauthorized', message: 'Missing Bearer token' }); |
| 128 | + return; |
| 129 | + } |
| 130 | + const payload = verifyJwt(header.slice(7)); |
| 131 | + if (!payload) { |
| 132 | + res.status(401).json({ error: 'Unauthorized', message: 'Invalid or expired token' }); |
| 133 | + return; |
| 134 | + } |
| 135 | + (req as AuthenticatedRequest).user = { publicKey: payload.publicKey }; |
| 136 | + next(); |
| 137 | +} |
| 138 | + |
| 139 | +export function requireAdmin(req: Request, res: Response, next: NextFunction): void { |
| 140 | + requireAuth(req, res, () => { |
| 141 | + const user = (req as AuthenticatedRequest).user; |
| 142 | + const adminKey = process.env.ADMIN_PUBLIC_KEY; |
| 143 | + if (!adminKey || user.publicKey !== adminKey) { |
| 144 | + res.status(403).json({ error: 'Forbidden', message: 'Admin access required' }); |
| 145 | + return; |
| 146 | + } |
| 147 | + next(); |
| 148 | + }); |
| 149 | +} |
0 commit comments