-
Notifications
You must be signed in to change notification settings - Fork 6
create-a-container: MVC manifesto + phases 0-1 (test scaffolding, apikeys pilot migration) #405
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
runleveldev
wants to merge
9
commits into
mieweb:main
Choose a base branch
from
runleveldev:mvc
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f7848d2
docs(create-a-container): add MVC refactor manifesto
runleveldev 4d4f796
test(create-a-container): phase 0 scaffolding for the MVC migration
runleveldev 0078dd1
test(create-a-container): pin /api/v1/apikeys wire contract
runleveldev 42e1b6a
refactor(create-a-container): migrate apikeys to resources/apikeys/
runleveldev 1068d51
refactor(create-a-container): split app construction from process sta…
runleveldev 893dbfd
build: add `make test` to the repo Makefile standard
runleveldev 168da72
test(create-a-container): verbose jest output; fix session-store sche…
runleveldev 7ad1d19
fix(create-a-container): resolve CodeQL alerts on session cookie and …
runleveldev 51ba752
fix(create-a-container): address Copilot review on PR #405
runleveldev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| /** | ||
| * Express app construction, separated from process startup (server.js) so | ||
| * tests can exercise the real app via supertest without binding a port or | ||
| * bootstrapping DB-backed session secrets. | ||
| * | ||
| * Everything HTTP-visible belongs here; server.js only fetches secrets and | ||
| * calls listen(). | ||
| */ | ||
|
|
||
| require('dotenv').config(); | ||
|
|
||
| const express = require('express'); | ||
| const session = require('express-session'); | ||
| const morgan = require('morgan'); | ||
| const fs = require('fs'); | ||
| const SequelizeStore = require('express-session-sequelize')(session.Store); | ||
| const path = require('path'); | ||
| const RateLimit = require('express-rate-limit'); | ||
| const swaggerUi = require('swagger-ui-express'); | ||
| const YAML = require('yamljs'); | ||
| const { sequelize } = require('./models'); | ||
|
|
||
| /** | ||
| * @param {object} options | ||
| * @param {string|string[]} options.sessionSecrets - express-session secret(s); required. | ||
| * @param {boolean} [options.rateLimit=true] - disable in tests: assertions on 4xx | ||
| * responses must not burn the budget. | ||
| * @param {boolean} [options.accessLog=true] - morgan; disable in tests for quiet output. | ||
| */ | ||
| function buildApp({ sessionSecrets, rateLimit = true, accessLog = true } = {}) { | ||
| if (!sessionSecrets || sessionSecrets.length === 0) { | ||
| throw new Error('buildApp: sessionSecrets is required'); | ||
| } | ||
|
|
||
| const app = express(); | ||
|
|
||
| // setup views (still used by templates router for nginx-conf / dnsmasq files) | ||
| app.set('views', path.join(__dirname, 'views')); | ||
| app.set('view engine', 'ejs'); | ||
| app.set('trust proxy', 1); | ||
| // Parse query strings with qs so bracket notation (e.g. `user[0]=alice`) | ||
| // yields real arrays. Express 5 defaults to the 'simple' parser. | ||
| app.set('query parser', 'extended'); | ||
|
|
||
| // setup middleware | ||
| if (accessLog) { | ||
| const accessLogStream = process.env.ACCESS_LOG | ||
| ? fs.createWriteStream(process.env.ACCESS_LOG, { flags: 'a' }) | ||
| : process.stdout; | ||
| app.use(morgan('combined', { stream: accessLogStream })); | ||
| } | ||
| app.use(express.json()); | ||
| app.use(express.urlencoded({ extended: true })); | ||
|
|
||
| // Configure session store | ||
| const sessionStore = new SequelizeStore({ | ||
| db: sequelize, | ||
| }); | ||
| // The store's expired-session sweeper (setInterval, no stop API) must not | ||
| // keep the process alive on its own: in production the listening socket | ||
| // does that, and test runners need the event loop to drain to exit. | ||
| if (sessionStore._expirationInterval?.unref) { | ||
| sessionStore._expirationInterval.unref(); | ||
| } | ||
|
|
||
| app.use(session({ | ||
| secret: sessionSecrets, | ||
| store: sessionStore, | ||
| resave: false, | ||
| saveUninitialized: false, | ||
| cookie: { | ||
| // 'auto' derives `secure` from the request protocol (honoring `trust | ||
| // proxy` and X-Forwarded-Proto from nginx) rather than NODE_ENV, so | ||
| // the flag tracks the actual transport — set on HTTPS, omitted on | ||
| // plain HTTP bootstrap/dev access. Same semantics as the previous | ||
| // per-request function form, but statically analyzable (CodeQL | ||
| // js/clear-text-cookie). | ||
| secure: 'auto', | ||
| maxAge: 24 * 60 * 60 * 1000, // 24 hours | ||
| sameSite: 'lax', | ||
| } | ||
| })); | ||
|
github-advanced-security[bot] marked this conversation as resolved.
Fixed
|
||
|
|
||
| app.use(express.static('public')); | ||
|
|
||
| // We rate limit unsuccessful (4xx/5xx statuses, excluding 404) to only 10 per 5 minutes, this | ||
| // should allow legitimate users a few tries to login or experiment without | ||
| // allowing bad-actors to abuse requests. 404s are excluded because browsers | ||
| // (especially Safari) automatically request favicon/apple-touch-icon paths that | ||
| // don't exist, and those harmless misses should not burn the rate-limit budget. | ||
| if (rateLimit) { | ||
| app.use(RateLimit({ | ||
| windowMs: 5 * 60 * 1000, | ||
| max: 10, | ||
| skipSuccessfulRequests: true, | ||
| requestWasSuccessful: (req, res) => res.statusCode < 400 || res.statusCode === 404, | ||
| })); | ||
| } | ||
|
|
||
| // CSRF guard for every handler that can see the session cookie (CodeQL | ||
| // js/missing-token-validation). Behavior-preserving: csrfGuard skips | ||
| // GET/HEAD/OPTIONS and Bearer-only requests, and every state-changing | ||
| // route lives under /api/v1 where the v1 router already applies it — this | ||
| // additionally covers the GET-only surfaces (templates, swagger, SPA, | ||
| // static) and rejects mutations to unknown paths early. Mounted after the | ||
| // rate limiter so CSRF 403s still count against the failure budget; the | ||
| // v1 router keeps its own csrfGuard so it stays safe mounted standalone. | ||
| const { csrfGuard, jsonErrorHandler } = require('./middlewares/api'); | ||
| app.use(csrfGuard); | ||
|
|
||
| // Set version info once at startup in app.locals | ||
| // Note: Version info is cached at startup. Server restart required to update version. | ||
| const { getVersionInfo } = require('./utils'); | ||
| app.locals.versionInfo = getVersionInfo(); | ||
|
|
||
| // --- Mount Routers --- | ||
| const apiV1Router = require('./routers/api/v1'); | ||
| const templatesRouter = require('./routers/templates'); | ||
|
|
||
| app.use('/api/v1', apiV1Router); | ||
| app.use('/', templatesRouter); // serves /sites/:siteId/nginx and /sites/:siteId/dnsmasq/:file | ||
|
|
||
| // --- API Documentation (Swagger UI) --- | ||
| // Swagger UI at /api documents the versioned v1 API (the spec also served at /api/v1/openapi.*). | ||
| const openapiSpec = YAML.load(path.join(__dirname, 'openapi.v1.yaml')); | ||
| app.get('/api/openapi.json', (req, res) => res.json(openapiSpec)); | ||
| app.get('/api/openapi.yaml', (req, res) => { | ||
| res.type('text/yaml').sendFile(path.join(__dirname, 'openapi.v1.yaml')); | ||
| }); | ||
| app.use('/api', swaggerUi.serve, swaggerUi.setup(openapiSpec, { | ||
| customSiteTitle: 'Create-a-Container API', | ||
| })); | ||
|
|
||
| // --- SPA: serve compiled React app for everything else --- | ||
| const clientDist = path.join(__dirname, 'client', 'dist'); | ||
| app.use(express.static(clientDist)); | ||
| app.get(/^\/(?!api(\/|$)|sites\/[^/]+\/(nginx$|dnsmasq\/)).*$/, (req, res) => { | ||
| res.sendFile(path.join(clientDist, 'index.html')); | ||
| }); | ||
|
|
||
| // Final error handler. Failures inside /api/v1 are already formatted by the | ||
| // v1 router's own jsonErrorHandler; this catches errors raised before the | ||
| // router is reached (notably the app-level csrfGuard) and errors from the | ||
| // non-API surfaces, keeping the JSON error envelope instead of Express's | ||
| // default HTML page with a stack trace. | ||
| app.use(jsonErrorHandler); | ||
|
|
||
| return app; | ||
| } | ||
|
|
||
| module.exports = { buildApp }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.