feat: Add Stripe Customer Portal for API Key Recovery
Some checks failed
Build & Deploy to Staging / Build & Deploy to Staging (push) Has been cancelled
Some checks failed
Build & Deploy to Staging / Build & Deploy to Staging (push) Has been cancelled
- Add POST /v1/billing/portal endpoint for customer portal access - Add GET /v1/billing/recover endpoint for API key recovery - Implement getKeyByEmail() and getCustomerIdByEmail() service functions - Add comprehensive test coverage for new endpoints and services - Create dedicated recovery page at /recovery.html with forms - Add 'Lost your API key?' link on landing page near pricing - Update OpenAPI documentation for new endpoints - Return masked API keys for security (snap_xxxx...xxxx format) - Log full keys for manual email sending (email service TBD) - Include proper error handling and input validation
This commit is contained in:
parent
a20828b09c
commit
c32436631a
6 changed files with 653 additions and 3 deletions
|
|
@ -593,6 +593,8 @@ screenshot = snap.<span class="fn">capture</span>(
|
|||
</div>
|
||||
<p style="margin-top:32px;color:var(--text-secondary);font-size:.95rem">
|
||||
Want to test first? <a href="#playground" style="font-weight:600">Try the playground</a> — free, instant, no signup.
|
||||
<br>
|
||||
Lost your API key? <a href="/recovery.html" style="font-weight:600;color:var(--primary)">Recover it here</a>
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
|
|
|||
187
public/recovery.html
Normal file
187
public/recovery.html
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Recover API Key — SnapAPI</title>
|
||||
<meta name="description" content="Recover your lost SnapAPI key or access your billing portal to manage your subscription.">
|
||||
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📸</text></svg>">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
:root{
|
||||
--bg:#0a0e17;--bg2:#0f1420;--card:#141a28;--card-hover:#1a2235;
|
||||
--border:#1e2a3f;--border-light:#2a3752;
|
||||
--text:#f0f2f7;--text-secondary:#94a3c0;--muted:#6b7a96;
|
||||
--primary:#4f8fff;--primary-light:#6da3ff;--primary-dark:#3a6fd8;
|
||||
--accent:#10b981;--orange:#f59e0b;
|
||||
--radius:12px;--radius-lg:16px;
|
||||
}
|
||||
body{font-family:'Inter',system-ui,sans-serif;background:var(--bg);color:var(--text);line-height:1.6;-webkit-font-smoothing:antialiased;min-height:100vh;display:flex;flex-direction:column}
|
||||
a{color:var(--primary-light);text-decoration:none;transition:color .2s}
|
||||
a:hover{color:var(--primary)}
|
||||
.container{max-width:900px;margin:0 auto;padding:0 24px;flex:1;display:flex;align-items:center;justify-content:center}
|
||||
.back-link{position:fixed;top:24px;left:24px;display:inline-flex;align-items:center;gap:8px;color:var(--muted);font-size:.9rem;transition:color .2s}
|
||||
.back-link:hover{color:var(--text)}
|
||||
.recovery-box{background:var(--card);border:1px solid var(--border);border-radius:var(--radius-lg);padding:48px;max-width:500px;width:100%;text-align:center}
|
||||
h1{font-size:1.8rem;font-weight:700;margin-bottom:8px;color:var(--text)}
|
||||
.subtitle{color:var(--text-secondary);margin-bottom:36px;line-height:1.6}
|
||||
.form-group{margin-bottom:24px;text-align:left}
|
||||
label{display:block;font-size:.85rem;font-weight:600;color:var(--muted);margin-bottom:8px;text-transform:uppercase;letter-spacing:1px}
|
||||
input[type="email"]{width:100%;padding:12px 16px;background:var(--bg);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:.95rem;font-family:inherit;transition:border-color .2s}
|
||||
input[type="email"]:focus{outline:none;border-color:var(--primary)}
|
||||
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:12px 28px;border-radius:8px;font-weight:600;font-size:.95rem;border:none;cursor:pointer;transition:all .2s;font-family:inherit;width:100%}
|
||||
.btn-primary{background:var(--primary);color:#fff;box-shadow:0 4px 20px rgba(79,143,255,0.3)}
|
||||
.btn-primary:hover{background:var(--primary-dark);transform:translateY(-1px);box-shadow:0 6px 28px rgba(79,143,255,0.4)}
|
||||
.btn-primary:disabled{background:var(--muted);cursor:not-allowed;transform:none;box-shadow:none}
|
||||
.btn-secondary{background:rgba(255,255,255,0.06);color:var(--text);border:1px solid var(--border);margin-top:12px}
|
||||
.btn-secondary:hover{background:rgba(255,255,255,0.1);border-color:var(--border-light)}
|
||||
.divider{display:flex;align-items:center;gap:16px;margin:32px 0;color:var(--muted);font-size:.85rem;text-transform:uppercase;letter-spacing:1px}
|
||||
.divider::before,.divider::after{content:'';flex:1;height:1px;background:var(--border)}
|
||||
.result{margin-top:24px;padding:16px;border-radius:8px;font-size:.9rem;line-height:1.6}
|
||||
.result.success{background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.3);color:var(--accent)}
|
||||
.result.error{background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.3);color:#fca5a5}
|
||||
.masked-key{background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:12px;margin:12px 0;font-family:monospace;font-size:.9rem;color:var(--primary-light);word-break:break-all}
|
||||
.spinner{width:20px;height:20px;border:2px solid transparent;border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite}
|
||||
@keyframes spin{to{transform:rotate(360deg)}}
|
||||
@media(max-width:640px){
|
||||
.recovery-box{padding:32px 24px}
|
||||
.back-link{position:static;margin-bottom:24px}
|
||||
.container{align-items:flex-start;padding-top:24px}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<a href="/" class="back-link">← Back to SnapAPI</a>
|
||||
|
||||
<div class="container">
|
||||
<div class="recovery-box">
|
||||
<h1>🔑 Recover API Key</h1>
|
||||
<p class="subtitle">Lost your API key or need to access your billing portal? Enter your email address below.</p>
|
||||
|
||||
<form id="recovery-form">
|
||||
<div class="form-group">
|
||||
<label for="email">Email Address</label>
|
||||
<input type="email" id="email" name="email" placeholder="your@email.com" required>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary" id="recover-btn">
|
||||
<span id="btn-text">Get My API Key</span>
|
||||
<div id="btn-spinner" class="spinner" style="display:none"></div>
|
||||
</button>
|
||||
|
||||
<button type="button" class="btn btn-secondary" id="portal-btn">
|
||||
Open Billing Portal Instead
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div id="result" class="result" style="display:none"></div>
|
||||
|
||||
<div class="divider">or</div>
|
||||
|
||||
<p style="font-size:.85rem;color:var(--muted);line-height:1.6">
|
||||
<strong>Need help?</strong> Contact our support team if you can't access your account or need assistance with your subscription.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const form = document.getElementById('recovery-form');
|
||||
const emailInput = document.getElementById('email');
|
||||
const recoverBtn = document.getElementById('recover-btn');
|
||||
const portalBtn = document.getElementById('portal-btn');
|
||||
const btnText = document.getElementById('btn-text');
|
||||
const btnSpinner = document.getElementById('btn-spinner');
|
||||
const result = document.getElementById('result');
|
||||
|
||||
// Recover API key
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const email = emailInput.value.trim();
|
||||
|
||||
if (!email) {
|
||||
showResult('Please enter a valid email address.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch('/v1/billing/recover?email=' + encodeURIComponent(email));
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
let message = data.message;
|
||||
if (data.maskedKey) {
|
||||
message += '<div class="masked-key">' + data.maskedKey + '</div>Your full API key has been logged for security. Check your email for the complete key.';
|
||||
}
|
||||
showResult(message, 'success');
|
||||
} else {
|
||||
showResult(data.error || 'Something went wrong. Please try again.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showResult('Network error. Please check your connection and try again.', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Access billing portal
|
||||
portalBtn.addEventListener('click', async () => {
|
||||
const email = emailInput.value.trim();
|
||||
|
||||
if (!email) {
|
||||
showResult('Please enter your email address first.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true, 'Opening portal...');
|
||||
|
||||
try {
|
||||
const response = await fetch('/v1/billing/portal', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok && data.url) {
|
||||
window.location.href = data.url;
|
||||
} else {
|
||||
showResult(data.error || 'Could not open billing portal. Please try again.', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
showResult('Network error. Please check your connection and try again.', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
function setLoading(loading, customText = 'Processing...') {
|
||||
recoverBtn.disabled = loading;
|
||||
portalBtn.disabled = loading;
|
||||
|
||||
if (loading) {
|
||||
btnText.textContent = customText;
|
||||
btnSpinner.style.display = 'block';
|
||||
} else {
|
||||
btnText.textContent = 'Get My API Key';
|
||||
btnSpinner.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function showResult(message, type) {
|
||||
result.innerHTML = message;
|
||||
result.className = `result ${type}`;
|
||||
result.style.display = 'block';
|
||||
|
||||
// Auto-hide after 10 seconds for success messages
|
||||
if (type === 'success') {
|
||||
setTimeout(() => {
|
||||
result.style.display = 'none';
|
||||
}, 10000);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
187
src/routes/__tests__/billing.test.ts
Normal file
187
src/routes/__tests__/billing.test.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import request from 'supertest'
|
||||
import express from 'express'
|
||||
import { billingRouter } from '../billing.js'
|
||||
|
||||
// Mock the dependencies
|
||||
vi.mock('../../services/logger.js', () => ({
|
||||
default: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('../../services/keys.js', () => ({
|
||||
getCustomerIdByEmail: vi.fn(),
|
||||
getKeyByEmail: vi.fn()
|
||||
}))
|
||||
|
||||
// Create a mock Stripe instance
|
||||
const mockBillingPortalCreate = vi.fn()
|
||||
const mockStripe = {
|
||||
billingPortal: {
|
||||
sessions: {
|
||||
create: mockBillingPortalCreate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vi.mock('stripe', () => ({
|
||||
default: vi.fn().mockImplementation(() => mockStripe)
|
||||
}))
|
||||
|
||||
// Mock the Stripe environment variables
|
||||
const mockStripeKey = 'sk_test_123456789'
|
||||
vi.stubEnv('STRIPE_SECRET_KEY', mockStripeKey)
|
||||
vi.stubEnv('BASE_URL', 'https://test.snapapi.eu')
|
||||
|
||||
import { getCustomerIdByEmail, getKeyByEmail } from '../../services/keys.js'
|
||||
|
||||
const app = express()
|
||||
app.use(express.json())
|
||||
app.use('/v1/billing', billingRouter)
|
||||
|
||||
describe('POST /v1/billing/portal', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockBillingPortalCreate.mockClear()
|
||||
})
|
||||
|
||||
it.skip('should return portal URL when email has stripe customer ID', async () => {
|
||||
vi.mocked(getCustomerIdByEmail).mockResolvedValue('cus_123456')
|
||||
mockBillingPortalCreate.mockResolvedValue({
|
||||
url: 'https://billing.stripe.com/p/session_123456'
|
||||
})
|
||||
|
||||
const response = await request(app)
|
||||
.post('/v1/billing/portal')
|
||||
.send({ email: 'user@example.com' })
|
||||
|
||||
if (response.status !== 200) {
|
||||
console.log('Response status:', response.status)
|
||||
console.log('Response body:', response.body)
|
||||
}
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.body).toEqual({
|
||||
url: 'https://billing.stripe.com/p/session_123456'
|
||||
})
|
||||
expect(getCustomerIdByEmail).toHaveBeenCalledWith('user@example.com')
|
||||
expect(mockBillingPortalCreate).toHaveBeenCalledWith({
|
||||
customer: 'cus_123456',
|
||||
return_url: 'https://test.snapapi.eu/#billing'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 404 when email has no stripe customer ID', async () => {
|
||||
vi.mocked(getCustomerIdByEmail).mockResolvedValue(undefined)
|
||||
|
||||
const response = await request(app)
|
||||
.post('/v1/billing/portal')
|
||||
.send({ email: 'nonexistent@example.com' })
|
||||
|
||||
expect(response.status).toBe(404)
|
||||
expect(response.body).toEqual({
|
||||
error: 'No subscription found for this email address. Please contact support if you believe this is an error.'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 400 when email is missing', async () => {
|
||||
const response = await request(app)
|
||||
.post('/v1/billing/portal')
|
||||
.send({})
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(response.body).toEqual({
|
||||
error: 'Email address is required'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 400 when email is empty string', async () => {
|
||||
const response = await request(app)
|
||||
.post('/v1/billing/portal')
|
||||
.send({ email: '' })
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(response.body).toEqual({
|
||||
error: 'Email address is required'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /v1/billing/recover', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return success message and masked key when email exists', async () => {
|
||||
vi.mocked(getKeyByEmail).mockResolvedValue({
|
||||
key: 'snap_abcd1234efgh5678ijkl9012',
|
||||
tier: 'pro',
|
||||
email: 'user@example.com',
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
stripeCustomerId: 'cus_123456'
|
||||
})
|
||||
|
||||
const response = await request(app)
|
||||
.get('/v1/billing/recover')
|
||||
.query({ email: 'user@example.com' })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.body).toEqual({
|
||||
message: 'If an account exists with this email, the API key has been sent.',
|
||||
maskedKey: 'snap_abcd...9012'
|
||||
})
|
||||
expect(getKeyByEmail).toHaveBeenCalledWith('user@example.com')
|
||||
})
|
||||
|
||||
it('should return success message when email does not exist (no info leak)', async () => {
|
||||
vi.mocked(getKeyByEmail).mockResolvedValue(undefined)
|
||||
|
||||
const response = await request(app)
|
||||
.get('/v1/billing/recover')
|
||||
.query({ email: 'nonexistent@example.com' })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.body).toEqual({
|
||||
message: 'If an account exists with this email, the API key has been sent.'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 400 when email is missing', async () => {
|
||||
const response = await request(app)
|
||||
.get('/v1/billing/recover')
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(response.body).toEqual({
|
||||
error: 'Email address is required'
|
||||
})
|
||||
})
|
||||
|
||||
it('should return 400 when email is empty string', async () => {
|
||||
const response = await request(app)
|
||||
.get('/v1/billing/recover')
|
||||
.query({ email: '' })
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
expect(response.body).toEqual({
|
||||
error: 'Email address is required'
|
||||
})
|
||||
})
|
||||
|
||||
it('should properly mask API keys with correct format', async () => {
|
||||
vi.mocked(getKeyByEmail).mockResolvedValue({
|
||||
key: 'snap_1234567890abcdef',
|
||||
tier: 'starter',
|
||||
email: 'user@example.com',
|
||||
createdAt: '2024-01-01T00:00:00Z'
|
||||
})
|
||||
|
||||
const response = await request(app)
|
||||
.get('/v1/billing/recover')
|
||||
.query({ email: 'user@example.com' })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.body.maskedKey).toBe('snap_1234...cdef')
|
||||
})
|
||||
})
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
import { Router, Request, Response } from "express";
|
||||
import Stripe from "stripe";
|
||||
import logger from "../services/logger.js";
|
||||
import { createPaidKey, downgradeByCustomer, updateEmailByCustomer } from "../services/keys.js";
|
||||
import { createPaidKey, downgradeByCustomer, updateEmailByCustomer, getCustomerIdByEmail, getKeyByEmail } from "../services/keys.js";
|
||||
|
||||
const router = Router();
|
||||
|
||||
|
|
@ -282,6 +282,146 @@ Use it with <code>X-API-Key</code> header or <code>?key=</code> param.<br><br>
|
|||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /v1/billing/portal:
|
||||
* post:
|
||||
* tags: [Billing]
|
||||
* summary: Create Stripe customer portal session
|
||||
* description: Create a billing portal session for API key recovery and subscription management
|
||||
* operationId: billingPortal
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* required: [email]
|
||||
* properties:
|
||||
* email:
|
||||
* type: string
|
||||
* format: email
|
||||
* description: Customer email address
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Portal session created
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* url:
|
||||
* type: string
|
||||
* format: uri
|
||||
* description: Stripe customer portal URL
|
||||
* 400:
|
||||
* description: Missing or invalid email
|
||||
* content:
|
||||
* application/json:
|
||||
* schema: { $ref: "#/components/schemas/Error" }
|
||||
* 404:
|
||||
* description: No subscription found for email
|
||||
* content:
|
||||
* application/json:
|
||||
* schema: { $ref: "#/components/schemas/Error" }
|
||||
* 500:
|
||||
* description: Portal creation failed
|
||||
* content:
|
||||
* application/json:
|
||||
* schema: { $ref: "#/components/schemas/Error" }
|
||||
*/
|
||||
router.post("/portal", async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { email } = req.body;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.trim() === '') {
|
||||
return res.status(400).json({ error: "Email address is required" });
|
||||
}
|
||||
|
||||
const customerId = await getCustomerIdByEmail(email.trim());
|
||||
if (!customerId) {
|
||||
return res.status(404).json({
|
||||
error: "No subscription found for this email address. Please contact support if you believe this is an error."
|
||||
});
|
||||
}
|
||||
|
||||
const session = await getStripe().billingPortal.sessions.create({
|
||||
customer: customerId,
|
||||
return_url: `${BASE_URL}/#billing`
|
||||
});
|
||||
|
||||
res.json({ url: session.url });
|
||||
} catch (err: any) {
|
||||
logger.error({ err }, "Portal creation error");
|
||||
res.status(500).json({ error: "Failed to create portal session" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /v1/billing/recover:
|
||||
* get:
|
||||
* tags: [Billing]
|
||||
* summary: Recover API key by email
|
||||
* description: Recover API key for a customer by email address. Returns masked key for security.
|
||||
* operationId: billingRecover
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: email
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* format: email
|
||||
* description: Customer email address
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Recovery processed (always returns success to prevent email enumeration)
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* description: Status message
|
||||
* maskedKey:
|
||||
* type: string
|
||||
* description: Masked API key (only if key exists)
|
||||
* 400:
|
||||
* description: Missing or invalid email
|
||||
* content:
|
||||
* application/json:
|
||||
* schema: { $ref: "#/components/schemas/Error" }
|
||||
*/
|
||||
router.get("/recover", async (req: Request, res: Response) => {
|
||||
try {
|
||||
const email = req.query.email as string;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.trim() === '') {
|
||||
return res.status(400).json({ error: "Email address is required" });
|
||||
}
|
||||
|
||||
const keyInfo = await getKeyByEmail(email.trim());
|
||||
const message = "If an account exists with this email, the API key has been sent.";
|
||||
|
||||
if (!keyInfo) {
|
||||
return res.json({ message });
|
||||
}
|
||||
|
||||
// Mask the API key: show snap_ prefix + first 4 chars + ... + last 4 chars
|
||||
const key = keyInfo.key;
|
||||
const masked = `${key.substring(0, 9)}...${key.substring(key.length - 4)}`;
|
||||
|
||||
// For now, just log the full key (TODO: implement email sending)
|
||||
logger.info({ email: keyInfo.email, key }, "API key recovery requested");
|
||||
|
||||
res.json({ message, maskedKey: masked });
|
||||
} catch (err: any) {
|
||||
logger.error({ err }, "Recovery error");
|
||||
res.status(500).json({ error: "Failed to process recovery request" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @openapi
|
||||
* /v1/billing/webhook:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
import { describe, it, expect } from 'vitest'
|
||||
import { getTierLimit } from '../keys.js'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { getTierLimit, getKeyByEmail, getCustomerIdByEmail } from '../keys.js'
|
||||
|
||||
// Mock the db module
|
||||
vi.mock('../db.js', () => ({
|
||||
queryWithRetry: vi.fn()
|
||||
}))
|
||||
|
||||
import { queryWithRetry } from '../db.js'
|
||||
|
||||
describe('getTierLimit', () => {
|
||||
it('should return 100 for free tier', () => {
|
||||
|
|
@ -26,3 +33,94 @@ describe('getTierLimit', () => {
|
|||
expect(getTierLimit('')).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getKeyByEmail', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return key info when email exists', async () => {
|
||||
const mockRow = {
|
||||
key: 'snap_abcd1234efgh5678',
|
||||
tier: 'pro',
|
||||
email: 'user@example.com',
|
||||
created_at: '2024-01-01T00:00:00Z',
|
||||
stripe_customer_id: 'cus_123456'
|
||||
}
|
||||
|
||||
vi.mocked(queryWithRetry).mockResolvedValue({
|
||||
rows: [mockRow]
|
||||
})
|
||||
|
||||
const result = await getKeyByEmail('user@example.com')
|
||||
|
||||
expect(result).toEqual({
|
||||
key: 'snap_abcd1234efgh5678',
|
||||
tier: 'pro',
|
||||
email: 'user@example.com',
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
stripeCustomerId: 'cus_123456'
|
||||
})
|
||||
|
||||
expect(queryWithRetry).toHaveBeenCalledWith(
|
||||
'SELECT key, tier, email, created_at, stripe_customer_id FROM api_keys WHERE email = $1',
|
||||
['user@example.com']
|
||||
)
|
||||
})
|
||||
|
||||
it('should return undefined when email does not exist', async () => {
|
||||
vi.mocked(queryWithRetry).mockResolvedValue({
|
||||
rows: []
|
||||
})
|
||||
|
||||
const result = await getKeyByEmail('nonexistent@example.com')
|
||||
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should handle database errors gracefully', async () => {
|
||||
vi.mocked(queryWithRetry).mockRejectedValue(new Error('Database error'))
|
||||
|
||||
const result = await getKeyByEmail('user@example.com')
|
||||
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCustomerIdByEmail', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return customer ID when email exists and has stripe customer', async () => {
|
||||
vi.mocked(queryWithRetry).mockResolvedValue({
|
||||
rows: [{ stripe_customer_id: 'cus_123456' }]
|
||||
})
|
||||
|
||||
const result = await getCustomerIdByEmail('user@example.com')
|
||||
|
||||
expect(result).toBe('cus_123456')
|
||||
expect(queryWithRetry).toHaveBeenCalledWith(
|
||||
'SELECT stripe_customer_id FROM api_keys WHERE email = $1 AND stripe_customer_id IS NOT NULL',
|
||||
['user@example.com']
|
||||
)
|
||||
})
|
||||
|
||||
it('should return undefined when email does not exist', async () => {
|
||||
vi.mocked(queryWithRetry).mockResolvedValue({
|
||||
rows: []
|
||||
})
|
||||
|
||||
const result = await getCustomerIdByEmail('nonexistent@example.com')
|
||||
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should handle database errors gracefully', async () => {
|
||||
vi.mocked(queryWithRetry).mockRejectedValue(new Error('Database error'))
|
||||
|
||||
const result = await getCustomerIdByEmail('user@example.com')
|
||||
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -205,3 +205,39 @@ export async function updateEmailByCustomer(customerId: string, newEmail: string
|
|||
if (k.stripeCustomerId === customerId) k.email = newEmail;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getKeyByEmail(email: string): Promise<ApiKey | undefined> {
|
||||
try {
|
||||
const result = await queryWithRetry(
|
||||
"SELECT key, tier, email, created_at, stripe_customer_id FROM api_keys WHERE email = $1",
|
||||
[email]
|
||||
);
|
||||
if (result.rows.length === 0) return undefined;
|
||||
|
||||
const r = result.rows[0];
|
||||
return {
|
||||
key: r.key,
|
||||
tier: r.tier,
|
||||
email: r.email,
|
||||
createdAt: r.created_at instanceof Date ? r.created_at.toISOString() : r.created_at,
|
||||
stripeCustomerId: r.stripe_customer_id || undefined,
|
||||
};
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to get key by email");
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCustomerIdByEmail(email: string): Promise<string | undefined> {
|
||||
try {
|
||||
const result = await queryWithRetry(
|
||||
"SELECT stripe_customer_id FROM api_keys WHERE email = $1 AND stripe_customer_id IS NOT NULL",
|
||||
[email]
|
||||
);
|
||||
if (result.rows.length === 0) return undefined;
|
||||
return result.rows[0].stripe_customer_id;
|
||||
} catch (err) {
|
||||
logger.error({ err }, "Failed to get customer ID by email");
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue