Merge branch 'feat/api-prefix'
# Conflicts: # apps/events/CHANGELOG.md
This commit is contained in:
@@ -153,8 +153,12 @@ app.use((req, res, next) => {
|
||||
// Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js).
|
||||
app.use(require('./hub/readOnly').licenceReadOnly);
|
||||
|
||||
// Everything the backend serves is under /api (2.3.0), so the site and its API can share one
|
||||
// address: the web server sends /api to the backend and everything else to the frontend. The old
|
||||
// paths (/, /health, /docs/v2, /uploads) still work for sites with a separate API address.
|
||||
|
||||
// Health for monitoring (and the Hub): no secrets, no personal information.
|
||||
app.get('/health', async (req, res) => {
|
||||
app.get(['/api/health', '/health'], async (req, res) => {
|
||||
const report = require('./hub/report');
|
||||
let db = true;
|
||||
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
|
||||
@@ -174,11 +178,11 @@ app.use('/api/v2', linksRouter);
|
||||
app.use('/api/v2', require('./v2').v2Router());
|
||||
// Links in messages already sent: v1 addresses answer 308 with their v2 one.
|
||||
app.use(legacyLinkRedirects);
|
||||
app.use('/docs/v2', require('./v2').v2DocsRouter());
|
||||
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
||||
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
||||
app.use('/api', legacyV1Router);
|
||||
app.use('/api', v1Removed);
|
||||
app.use('/api/docs/v2', require('./v2').v2DocsRouter());
|
||||
app.get('/api/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||
// Before 2.3.0 the reference was at /docs/v2 (bookmarks, the old status page).
|
||||
app.use('/docs/v2', (req, res) => res.redirect(301, `/api${req.originalUrl}`));
|
||||
app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||
|
||||
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
||||
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
||||
@@ -187,12 +191,16 @@ warmCache().catch(() => {});
|
||||
// handlers. Serving them inline lets a compromised/malicious upload run script
|
||||
// in the site's origin if opened directly, so pin the safe response headers
|
||||
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
|
||||
app.use('/uploads', express.static('public/uploads', {
|
||||
// Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl).
|
||||
// /uploads still answers for links made before 2.3.0.
|
||||
const uploads = express.static('public/uploads', {
|
||||
setHeaders: (res) => {
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
},
|
||||
}));
|
||||
});
|
||||
app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed"
|
||||
app.use('/uploads', uploads);
|
||||
|
||||
// ── Shared page helpers ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -268,8 +276,9 @@ app.get('/favicon.ico', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico'));
|
||||
});
|
||||
|
||||
// ── Root route — status page ────────────────────────────────────────────────
|
||||
app.get('/', async (req, res) => {
|
||||
// ── Status page, at /api (2.3.0); / sends you there ─────────────────────────
|
||||
app.get('/', (req, res) => res.redirect(302, '/api'));
|
||||
app.get('/api', async (req, res) => {
|
||||
const mem = process.memoryUsage();
|
||||
const uptimeSec = process.uptime();
|
||||
const now = new Date().toISOString();
|
||||
@@ -335,15 +344,18 @@ app.get('/', async (req, res) => {
|
||||
</div>
|
||||
|
||||
<div class="note">
|
||||
API documentation (OpenAPI) is at <a href="/docs/v2">/docs/v2</a> — it needs an admin account token.
|
||||
API documentation (OpenAPI) is at <a href="/api/docs/v2">/api/docs/v2</a> — it needs an admin account token.
|
||||
</div>
|
||||
`);
|
||||
|
||||
res.send(html);
|
||||
});
|
||||
|
||||
// /docs: the v1 reference went with v1 in 2.0; the API is documented at /docs/v2 (OpenAPI).
|
||||
app.get('/docs', (req, res) => res.redirect(301, '/docs/v2'));
|
||||
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
||||
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
||||
// Mounted after everything else under /api, since v1Removed answers 410 for any other /api path.
|
||||
app.use('/api', legacyV1Router);
|
||||
app.use('/api', v1Removed);
|
||||
|
||||
// Error middleware
|
||||
app.use(notFound);
|
||||
|
||||
@@ -45,9 +45,10 @@ function toAbsoluteUrl(req, url) {
|
||||
}
|
||||
return raw; // keep as-is if already absolute and not localhost
|
||||
}
|
||||
// Relative path like /uploads/... => prefix with request origin
|
||||
// Relative path like /uploads/... => prefix with request origin; uploads are served under
|
||||
// /api/uploads (2.3.0) so they reach the backend when the site and API share one address
|
||||
if (raw.startsWith('/')) {
|
||||
return `${req.protocol}://${req.get('host')}${raw}`;
|
||||
return `${req.protocol}://${req.get('host')}${raw.startsWith('/uploads/') ? `/api${raw}` : raw}`;
|
||||
}
|
||||
// Any other case, return as-is
|
||||
return raw;
|
||||
|
||||
@@ -269,7 +269,7 @@ async function sendPdf(toPhone, localPdfPath, filename, caption) {
|
||||
`Set BACKEND_URL to your public backend URL (e.g. https://api.yourdomain.com) in your .env file.`
|
||||
);
|
||||
}
|
||||
const pdfUrl = `${backendUrl}/uploads/tickets-temp/${tempName}`;
|
||||
const pdfUrl = `${backendUrl}/api/uploads/tickets-temp/${tempName}`;
|
||||
|
||||
const { token, instanceId } = await getConfig();
|
||||
try {
|
||||
|
||||
@@ -43,7 +43,7 @@ export function v2Router(): Router {
|
||||
}
|
||||
|
||||
/**
|
||||
* /docs/v2: Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
||||
* /api/docs/v2 (2.3.0; /docs/v2 before, which now redirects): Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
||||
* public; it asks for an admin token and uses it to load openapi.json and to try requests.
|
||||
*/
|
||||
export function v2DocsRouter(): Router {
|
||||
@@ -62,7 +62,7 @@ const DOCS_HTML = `<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Cross Events API v2</title>
|
||||
<link rel="stylesheet" href="/docs/v2/assets/swagger-ui.css">
|
||||
<link rel="stylesheet" href="/api/docs/v2/assets/swagger-ui.css">
|
||||
<style>
|
||||
body { margin: 0; font-family: system-ui, sans-serif; }
|
||||
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
||||
@@ -81,7 +81,7 @@ const DOCS_HTML = `<!doctype html>
|
||||
<p class="err" id="err" role="alert"></p>
|
||||
</main>
|
||||
<div id="ui"></div>
|
||||
<script src="/docs/v2/assets/swagger-ui-bundle.js"></script>
|
||||
<script src="/api/docs/v2/assets/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
var params = new URLSearchParams(location.search);
|
||||
|
||||
@@ -55,7 +55,7 @@ legacyV1Router.post('/privacy/unsubscribe/:token/one-click', express.urlencoded(
|
||||
/** Any other v1 address: gone since 2.0 (410, pointing at v2). /api/v2 misses fall through to 404. */
|
||||
export const v1Removed: RequestHandler = (req, res, next) => {
|
||||
if (req.path === '/v2' || req.path.startsWith('/v2/')) return next();
|
||||
res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /docs/v2.' });
|
||||
res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /api/docs/v2.' });
|
||||
};
|
||||
|
||||
export const legacyLinkRedirects: RequestHandler = (req, res, next) => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { PATH_HELP, QUERY_HELP } from './docs';
|
||||
|
||||
/**
|
||||
* The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is
|
||||
* always what the code does. Served at /api/v2/openapi.json, shown at /docs/v2.
|
||||
* always what the code does. Served at /api/v2/openapi.json, shown at /api/docs/v2.
|
||||
*/
|
||||
|
||||
type JsonSchema = Record<string, unknown>;
|
||||
|
||||
@@ -14,12 +14,20 @@ export function iso(d: Date | string | null | undefined): string | null {
|
||||
return d == null ? null : new Date(d).toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a stored upload path is served: "/uploads/…" (as stored) → "/api/uploads/…" (2.3.0), so it
|
||||
* reaches the backend when the site and its API share one address. Anything else is unchanged.
|
||||
*/
|
||||
export function uploadPath(raw: string): string {
|
||||
return /^\/uploads\//.test(raw) ? `/api${raw}` : raw;
|
||||
}
|
||||
|
||||
/** A stored picture path ("/uploads/…") as an absolute URL on the host the request came to. */
|
||||
export function absoluteUrl(req: Request, url: string | null | undefined): string | null {
|
||||
const raw = String(url || '').trim();
|
||||
if (!raw) return null;
|
||||
if (/^https?:\/\//.test(raw)) return raw;
|
||||
return `${req.protocol}://${req.get('host')}${raw.startsWith('/') ? '' : '/'}${raw}`;
|
||||
return `${req.protocol}://${req.get('host')}${uploadPath(raw.startsWith('/') ? raw : `/${raw}`)}`;
|
||||
}
|
||||
|
||||
export const campusRef = z.object({ id, name: z.string(), slug: z.string() });
|
||||
|
||||
@@ -108,6 +108,7 @@ import { v2Router } from '../src/v2';
|
||||
import { ServiceError } from '../src/services/errors';
|
||||
import { routes } from '../src/v2/route';
|
||||
import { buildOpenApi } from '../src/v2/openapi';
|
||||
import { absoluteUrl, uploadPath } from '../src/v2/schemas';
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
@@ -129,7 +130,7 @@ describe('GET /api/v2/events', () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.meta).toEqual({ page: 2, limit: 10, total: 31, pages: 4 });
|
||||
expect(res.body.data[0]).toMatchObject({ id: 'e1', startDate: '2026-12-04T16:00:00.000Z', series: { slug: 'camps' } });
|
||||
expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/uploads\/events\/camp\.jpg$/);
|
||||
expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/api\/uploads\/events\/camp\.jpg$/);
|
||||
const args = mockDb.event.findMany.mock.calls[0][0];
|
||||
expect(args).toMatchObject({ skip: 10, take: 10 });
|
||||
expect(args.where.AND).toEqual(expect.arrayContaining([{ isActive: true, isHidden: false, goLiveAt: { lte: expect.any(Date) } }, { title: { contains: 'camp', mode: 'insensitive' } }]));
|
||||
@@ -424,7 +425,7 @@ describe('events (staff)', () => {
|
||||
const res = await request(app).get('/api/v2/events/manage?past=true');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.data[0]).toMatchObject({ id: 'e1', isHidden: true, waitlistEnabled: true, startDate: '2026-12-04T16:00:00.000Z' });
|
||||
expect(res.body.data[0].picture).toMatch(/^http:\/\/.*\/uploads\/events\/c\.jpg$/);
|
||||
expect(res.body.data[0].picture).toMatch(/^http:\/\/[^/]+\/api\/uploads\/events\/c\.jpg$/);
|
||||
expect(mockEvents.listManagedEvents).toHaveBeenCalledWith({ includePast: true, includeInactive: false, excludeClosed: false, campus: undefined }, expect.objectContaining({ scope: null }));
|
||||
});
|
||||
|
||||
@@ -554,7 +555,16 @@ describe('sections, costs, image uploads', () => {
|
||||
mockImage.file = { filename: 'event-123.jpg' };
|
||||
const res = await request(app).post('/api/v2/uploads/event-image');
|
||||
expect(res.body.data.path).toBe('/uploads/events/event-123.jpg');
|
||||
expect(res.body.data.url).toMatch(/^http:\/\/.*\/uploads\/events\/event-123\.jpg$/);
|
||||
expect(res.body.data.url).toMatch(/^http:\/\/[^/]+\/api\/uploads\/events\/event-123\.jpg$/);
|
||||
});
|
||||
|
||||
test('stored uploads are given out under /api/uploads (2.3.0); other addresses are left alone', () => {
|
||||
expect(uploadPath('/uploads/branding/logo.png')).toBe('/api/uploads/branding/logo.png');
|
||||
expect(uploadPath('/api/uploads/x.png')).toBe('/api/uploads/x.png');
|
||||
expect(uploadPath('/images/x.png')).toBe('/images/x.png');
|
||||
const req = { protocol: 'https', get: () => 'events.church.co.za' } as unknown as Parameters<typeof absoluteUrl>[0];
|
||||
expect(absoluteUrl(req, 'uploads/events/a.jpg')).toBe('https://events.church.co.za/api/uploads/events/a.jpg');
|
||||
expect(absoluteUrl(req, 'https://cdn.example.org/uploads/a.jpg')).toBe('https://cdn.example.org/uploads/a.jpg');
|
||||
});
|
||||
|
||||
test('branding images are for admins once accounts exist', async () => {
|
||||
|
||||
Reference in New Issue
Block a user