zappier-edge/tests/auth.test.ts

51 lines
1.8 KiB
TypeScript

import express from 'express';
import request from 'supertest';
import { apiKeyAuth, InMemoryCustomerRepo } from '../src/auth';
const repo = new InMemoryCustomerRepo([
{ id: 'cust_1', name: 'Ada', tierId: 'pro', apiKey: 'key-ada' },
{ id: 'cust_2', name: 'Grace', tierId: 'business', apiKey: 'key-grace', stripeCustomerId: 'cus_123' },
]);
const app = express();
app.use(apiKeyAuth(repo));
app.get('/ping', (req, res) =>
res.json({ customerId: req.customer!.id, tierId: req.customer!.tierId }),
);
describe('apiKeyAuth', () => {
it('rejects a missing key with 401', async () => {
const res = await request(app).get('/ping');
expect(res.status).toBe(401);
expect(res.body.error).toMatch(/API key/);
});
it('rejects an unknown key with 401', async () => {
const res = await request(app).get('/ping').set('x-api-key', 'wrong');
expect(res.status).toBe(401);
});
it('attaches the customer for a valid key', async () => {
const res = await request(app).get('/ping').set('x-api-key', 'key-ada');
expect(res.status).toBe(200);
expect(res.body).toEqual({ customerId: 'cust_1', tierId: 'pro' });
});
});
describe('InMemoryCustomerRepo', () => {
it('lists all customers', () => {
expect(repo.list().map((c) => c.id)).toEqual(['cust_1', 'cust_2']);
});
it('save() upserts by id', () => {
const local = new InMemoryCustomerRepo([
{ id: 'cust_1', name: 'Ada', tierId: 'pro', apiKey: 'key-ada' },
]);
local.save({ id: 'cust_1', name: 'Ada', tierId: 'business', apiKey: 'key-ada', multiplierOverride: 0.4 });
local.save({ id: 'cust_9', name: 'New', tierId: 'free', apiKey: 'key-new' });
expect(local.list()).toHaveLength(2);
const updated = local.findByApiKey('key-ada');
expect(updated?.tierId).toBe('business');
expect(updated?.multiplierOverride).toBe(0.4);
});
});