135 lines
7.4 KiB
TypeScript
135 lines
7.4 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import { readFile } from 'node:fs/promises';
|
|
import { once } from 'node:events';
|
|
import test from 'node:test';
|
|
import express from 'express';
|
|
import SwaggerParser from '@apidevtools/swagger-parser';
|
|
import ts from 'typescript';
|
|
import { customerOpenApi } from './openapi.js';
|
|
import { mountApiDocs } from './router.js';
|
|
import { birdSchema, medicationSchema } from '../schemas.js';
|
|
|
|
const appSource = await readFile(new URL('../app.ts', import.meta.url), 'utf8');
|
|
const ast = ts.createSourceFile('app.ts', appSource, ts.ScriptTarget.Latest, true);
|
|
|
|
test('customer specification is valid OpenAPI and has unique operation IDs', async () => {
|
|
await SwaggerParser.validate(JSON.parse(JSON.stringify(customerOpenApi)));
|
|
const ids = Object.values(customerOpenApi.paths).flatMap((path) => Object.values(path!).map((operation) => operation.operationId));
|
|
assert.equal(new Set(ids).size, ids.length);
|
|
assert.deepEqual(customerOpenApi.servers, [{ url: '/api', description: 'This FlockPal instance' }]);
|
|
});
|
|
|
|
test('documented operations exactly match customer integration routes and permissions', () => {
|
|
const expected: string[] = [];
|
|
for (const statement of ast.statements) {
|
|
if (!ts.isExpressionStatement(statement) || !ts.isCallExpression(statement.expression)) continue;
|
|
const call = statement.expression;
|
|
if (!ts.isPropertyAccessExpression(call.expression) || call.expression.expression.getText(ast) !== 'app') continue;
|
|
const method = call.expression.name.text;
|
|
if (!['get', 'post', 'put', 'delete', 'patch'].includes(method)) continue;
|
|
const [pathArg, ...args] = call.arguments;
|
|
if (!pathArg || !ts.isStringLiteral(pathArg)) continue;
|
|
const middleware = args.filter(ts.isIdentifier).map((arg) => arg.text);
|
|
if (!middleware.includes('requireAuth') || middleware.includes('requireSessionAuth') || middleware.includes('requireAdmin')) continue;
|
|
const path = pathArg.text.replace(/^\/api/, '').replace(/:(\w+)/g, '{$1}');
|
|
expected.push(`${method} ${path}`);
|
|
const operation = (customerOpenApi.paths[path] as Record<string, any> | undefined)?.[method];
|
|
assert.ok(operation, `Missing ${method} ${path}`);
|
|
assert.deepEqual(operation.security, [{ IntegrationToken: [] }]);
|
|
if (middleware.includes('requireWriteAccess')) {
|
|
assert.match(operation.description, /read_write/);
|
|
assert.ok(operation.responses['402']);
|
|
assert.ok(operation.responses['403']);
|
|
}
|
|
const roleCall = args.find((arg) => ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole');
|
|
if (roleCall && ts.isCallExpression(roleCall)) {
|
|
for (const match of roleCall.getText(ast).matchAll(/'([^']+)'/g)) assert.ok(operation.description.includes(match[1]));
|
|
}
|
|
}
|
|
const actual = Object.entries(customerOpenApi.paths).flatMap(([path, item]) => Object.keys(item!).map((method) => `${method} ${path}`));
|
|
assert.deepEqual(actual.sort(), expected.sort());
|
|
assert.equal(actual.length, 35);
|
|
});
|
|
|
|
test('response models cover the actual serialized fields', () => {
|
|
const components = customerOpenApi.components!.schemas!;
|
|
const names: Record<string, string> = { normalizeWorkspace: 'workspace', normalizeWorkspaceMember: 'member', normalizeBird: 'bird', normalizeWeight: 'weight', normalizeVetVisit: 'vetVisit', normalizeMedication: 'medication', normalizeMedicationAdministration: 'administration', normalizeFlockNote: 'note', normalizeBirdTimelineEvent: 'timeline' };
|
|
for (const statement of ast.statements) {
|
|
if (!ts.isVariableStatement(statement)) continue;
|
|
for (const declaration of statement.declarationList.declarations) {
|
|
const model = names[declaration.name.getText(ast)];
|
|
if (!model) continue;
|
|
const fn = declaration.initializer;
|
|
assert.ok(fn && ts.isArrowFunction(fn) && ts.isParenthesizedExpression(fn.body));
|
|
const body = fn.body.expression;
|
|
assert.ok(ts.isObjectLiteralExpression(body));
|
|
const keys = body.properties.map((property) => property.name!.getText(ast));
|
|
const schema = components[model];
|
|
assert.ok(schema && !('$ref' in schema));
|
|
assert.deepEqual(Object.keys(schema.properties!).sort(), keys.sort(), model);
|
|
}
|
|
}
|
|
});
|
|
|
|
test('shared validators retain custom rules and document required request fields', () => {
|
|
assert.equal(birdSchema.safeParse({ name: 'Yoda', species: 'Parrot', motivators: 'one\ntwo\nthree\nfour' }).success, false);
|
|
assert.equal(medicationSchema.safeParse({ name: 'Medicine', dosage: '1 ml', frequency: 'once_daily', doseSchedule: [{ key: 'morning', label: 'Morning', time: '08:00' }], startDate: '2026-09-27', endDate: '2026-09-26' }).success, false);
|
|
const bird = customerOpenApi.components!.schemas!.BirdInput;
|
|
assert.ok(!('$ref' in bird));
|
|
assert.deepEqual(bird.required, ['name', 'species']);
|
|
});
|
|
|
|
test('Swagger UI, initialization, assets and specification are served locally with compatible CSP', async (t) => {
|
|
const app = express();
|
|
mountApiDocs(app);
|
|
const server = app.listen(0, '127.0.0.1');
|
|
await once(server, 'listening');
|
|
t.after(() => new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve())));
|
|
const address = server.address();
|
|
assert.ok(address && typeof address !== 'string');
|
|
const base = `http://127.0.0.1:${address.port}`;
|
|
const page = await fetch(`${base}/api/docs/`);
|
|
assert.equal(page.status, 200);
|
|
const html = await page.text();
|
|
assert.match(html, /FlockPal API Reference/);
|
|
const csp = page.headers.get('content-security-policy')!;
|
|
assert.match(csp, /script-src 'self'/);
|
|
assert.match(csp, /connect-src 'self'/);
|
|
assert.ok(!csp.includes('upgrade-insecure-requests'));
|
|
for (const asset of ['swagger-ui.css', 'swagger-ui-bundle.js', 'swagger-ui-standalone-preset.js', 'swagger-ui-init.js']) {
|
|
const response = await fetch(`${base}/api/docs/${asset}`);
|
|
assert.equal(response.status, 200, asset);
|
|
const content = await response.text();
|
|
assert.ok(content.length > 0);
|
|
if (asset === 'swagger-ui-init.js') {
|
|
assert.match(content, /\/api\/openapi.json/);
|
|
assert.match(content, /"persistAuthorization": false/);
|
|
assert.match(content, /"validatorUrl": null/);
|
|
}
|
|
}
|
|
const spec = await fetch(`${base}/api/openapi.json`);
|
|
assert.equal(spec.status, 200);
|
|
assert.match(spec.headers.get('content-type')!, /application\/json/);
|
|
assert.deepEqual(await spec.json(), customerOpenApi);
|
|
const redirect = await fetch(`${base}/api/docs`, { redirect: 'manual' });
|
|
assert.equal(redirect.status, 301);
|
|
assert.equal(redirect.headers.get('location'), '/api/docs/');
|
|
});
|
|
|
|
test('bird removal is restricted to owners and assistants in the API and its documentation', () => {
|
|
const route = ast.statements.find((statement) =>
|
|
ts.isExpressionStatement(statement) && ts.isCallExpression(statement.expression) &&
|
|
statement.expression.expression.getText(ast) === 'app.delete' &&
|
|
statement.expression.arguments[0]?.getText(ast) === "'/api/birds/:birdId'"
|
|
);
|
|
assert.ok(route && ts.isExpressionStatement(route) && ts.isCallExpression(route.expression));
|
|
const guard = route.expression.arguments.find((arg) =>
|
|
ts.isCallExpression(arg) && arg.expression.getText(ast) === 'requireWorkspaceRole'
|
|
);
|
|
assert.ok(guard && ts.isCallExpression(guard));
|
|
assert.equal(guard.arguments[0].getText(ast), "['owner', 'assistant']");
|
|
const description = customerOpenApi.paths['/birds/{birdId}']!.delete!.description!;
|
|
assert.match(description, /Allowed roles: owner, assistant\./);
|
|
assert.doesNotMatch(description, /caregiver/);
|
|
});
|