@cubicecho/server-kit 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_agents/docs/06-http.md +30 -0
- package/dist/http/auth-redirects.d.ts +42 -0
- package/dist/http/auth-redirects.js +93 -0
- package/dist/http/defaults.d.ts +13 -0
- package/dist/http/defaults.js +8 -0
- package/dist/http/health.d.ts +17 -0
- package/dist/http/health.js +19 -0
- package/dist/http/index.d.ts +6 -0
- package/dist/http/index.js +6 -0
- package/dist/http/shutdown.d.ts +25 -0
- package/dist/http/shutdown.js +58 -0
- package/dist/http/static.d.ts +13 -0
- package/dist/http/static.js +112 -0
- package/dist/http/status.d.ts +13 -0
- package/dist/http/status.js +12 -0
- package/llms.txt +19 -1
- package/package.json +7 -1
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# HTTP
|
|
2
|
+
|
|
3
|
+
`@cubicecho/server-kit/http` has what surrounds an Express app: a clean stop, the health check, serving the built app, and the two OIDC redirects.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { checkHealth, createStaticHandler, HTTP_DEFAULTS, HttpStatus, mountAuthRedirects } from '@cubicecho/server-kit/http';
|
|
7
|
+
import express from 'express';
|
|
8
|
+
|
|
9
|
+
const app = express();
|
|
10
|
+
app.use('/graphql', express.json({ limit: HTTP_DEFAULTS.bodyLimit }));
|
|
11
|
+
app.get('/healthz', async (_req, res) => {
|
|
12
|
+
const health = await checkHealth(db, version());
|
|
13
|
+
res.status(health.ok ? HttpStatus.Ok : HttpStatus.ServiceUnavailable).json(health);
|
|
14
|
+
});
|
|
15
|
+
mountAuthRedirects(app, { auth, serverUrl: serverUrl(), appUrl: appUrl() });
|
|
16
|
+
app.use(createStaticHandler(staticDir));
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { stopOnSignals } from '@cubicecho/server-kit/http';
|
|
21
|
+
|
|
22
|
+
const server = app.listen(port());
|
|
23
|
+
stopOnSignals(server, { before: () => scheduler.stop(), after: closeDatabase });
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- Mount `/healthz` and `mountAuthRedirects` before the static handler, which answers every path.
|
|
27
|
+
- `checkHealth` logs why Postgres did not answer and never says it: anyone may ask, and a driver's error names hosts.
|
|
28
|
+
- `createStaticHandler` keeps `/assets/` and `/_expo/` files for a year, and answers 404 for one that is gone. Anything else that is not a file is `index.html`.
|
|
29
|
+
- `stopOnSignals` drains, runs `after`, and exits within `shutdownDeadlineSeconds`, under Docker's 10. A second signal exits at once.
|
|
30
|
+
- `oidcSignInUrl` and `oidcRedirectUri` name the two OIDC routes for a provider.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Express } from 'express';
|
|
2
|
+
import { type AuthPaths } from '../auth/defaults.ts';
|
|
3
|
+
/** What the two legs of an OIDC sign-in need. */
|
|
4
|
+
export interface AuthRedirectOptions {
|
|
5
|
+
/** The auth instance, whose handler serves both. */
|
|
6
|
+
auth: {
|
|
7
|
+
handler: (request: globalThis.Request) => Promise<globalThis.Response>;
|
|
8
|
+
};
|
|
9
|
+
/** Where a browser reaches this server. */
|
|
10
|
+
serverUrl: string;
|
|
11
|
+
/** Where users reach the app. */
|
|
12
|
+
appUrl: string;
|
|
13
|
+
/**
|
|
14
|
+
* Pages that are somewhere else in this app.
|
|
15
|
+
*
|
|
16
|
+
* @defaultValue `AUTH_PATHS`
|
|
17
|
+
*/
|
|
18
|
+
paths?: Partial<Pick<AuthPaths, 'login'>>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Names where a login button sends the browser.
|
|
22
|
+
*
|
|
23
|
+
* @param serverUrl - Where a browser reaches the server.
|
|
24
|
+
* @param providerId - The provider's id.
|
|
25
|
+
* @returns The URL. Absolute, because in development the app is on another origin.
|
|
26
|
+
*/
|
|
27
|
+
export declare function oidcSignInUrl(serverUrl: string, providerId: string): string;
|
|
28
|
+
/**
|
|
29
|
+
* Names the redirect URI a provider has to have registered.
|
|
30
|
+
*
|
|
31
|
+
* @param serverUrl - Where a browser reaches the server.
|
|
32
|
+
* @param providerId - The provider's id.
|
|
33
|
+
* @returns The URL.
|
|
34
|
+
*/
|
|
35
|
+
export declare function oidcRedirectUri(serverUrl: string, providerId: string): string;
|
|
36
|
+
/**
|
|
37
|
+
* Mounts the two legs of an OIDC sign-in, the only better-auth routes a browser has to be redirected through.
|
|
38
|
+
*
|
|
39
|
+
* @param app - The Express app. Mount before the static handler, whose fallback would answer both.
|
|
40
|
+
* @param options - The auth instance, and where it and the app are.
|
|
41
|
+
*/
|
|
42
|
+
export declare function mountAuthRedirects(app: Express, options: AuthRedirectOptions): void;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { AUTH_PATHS } from '../auth/defaults.js';
|
|
2
|
+
import { HttpStatus } from './status.js';
|
|
3
|
+
/** better-auth's routes, where Express hands them over. */
|
|
4
|
+
const AUTH_BASE_PATH = '/api/auth';
|
|
5
|
+
/** Where a login button sends the browser, before the provider's id. */
|
|
6
|
+
const SIGN_IN_PATH = `${AUTH_BASE_PATH}/oidc-pairing/sign-in`;
|
|
7
|
+
/** Where a provider sends the browser back, before its id. */
|
|
8
|
+
const CALLBACK_PATH = `${AUTH_BASE_PATH}/sso/callback`;
|
|
9
|
+
/** What the login page is told when the hop to better-auth itself failed. */
|
|
10
|
+
const SIGN_IN_FAILED = 'sign_in_failed';
|
|
11
|
+
/**
|
|
12
|
+
* Names where a login button sends the browser.
|
|
13
|
+
*
|
|
14
|
+
* @param serverUrl - Where a browser reaches the server.
|
|
15
|
+
* @param providerId - The provider's id.
|
|
16
|
+
* @returns The URL. Absolute, because in development the app is on another origin.
|
|
17
|
+
*/
|
|
18
|
+
export function oidcSignInUrl(serverUrl, providerId) {
|
|
19
|
+
return `${serverUrl}${SIGN_IN_PATH}/${encodeURIComponent(providerId)}`;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Names the redirect URI a provider has to have registered.
|
|
23
|
+
*
|
|
24
|
+
* @param serverUrl - Where a browser reaches the server.
|
|
25
|
+
* @param providerId - The provider's id.
|
|
26
|
+
* @returns The URL.
|
|
27
|
+
*/
|
|
28
|
+
export function oidcRedirectUri(serverUrl, providerId) {
|
|
29
|
+
return `${serverUrl}${CALLBACK_PATH}/${encodeURIComponent(providerId)}`;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Mounts the two legs of an OIDC sign-in, the only better-auth routes a browser has to be redirected through.
|
|
33
|
+
*
|
|
34
|
+
* @param app - The Express app. Mount before the static handler, whose fallback would answer both.
|
|
35
|
+
* @param options - The auth instance, and where it and the app are.
|
|
36
|
+
*/
|
|
37
|
+
export function mountAuthRedirects(app, options) {
|
|
38
|
+
for (const path of [SIGN_IN_PATH, CALLBACK_PATH]) {
|
|
39
|
+
app.get(`${path}/:providerId`, (req, res) => {
|
|
40
|
+
forward(options, req, res).catch((error) => fail(options, res, error));
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Copies Express's headers into fetch `Headers`, which better-auth reads cookies from.
|
|
46
|
+
*
|
|
47
|
+
* @param raw - The request's headers as Node parsed them.
|
|
48
|
+
* @returns The same headers, repeated ones appended.
|
|
49
|
+
*/
|
|
50
|
+
function toHeaders(raw) {
|
|
51
|
+
const headers = new Headers();
|
|
52
|
+
for (const [name, value] of Object.entries(raw)) {
|
|
53
|
+
for (const one of [value ?? []].flat()) {
|
|
54
|
+
headers.append(name, one);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return headers;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Hands a browser request to better-auth, and carries its redirect back.
|
|
61
|
+
*
|
|
62
|
+
* @param options - The auth instance, and where the server is.
|
|
63
|
+
* @param req - The request.
|
|
64
|
+
* @param res - The response.
|
|
65
|
+
* @throws If better-auth answers without a redirect.
|
|
66
|
+
*/
|
|
67
|
+
async function forward({ auth, serverUrl }, req, res) {
|
|
68
|
+
// Only its path and query: a request line may hold a whole URL, and the origin is ours to say.
|
|
69
|
+
const { pathname, search } = new URL(req.originalUrl, serverUrl);
|
|
70
|
+
const url = Object.assign(new URL(serverUrl), { pathname, search });
|
|
71
|
+
const response = await auth.handler(new globalThis.Request(url, { headers: toHeaders(req.headers) }));
|
|
72
|
+
const location = response.headers.get('location');
|
|
73
|
+
if (location === null) {
|
|
74
|
+
throw new Error(`better-auth answered ${response.status} with no redirect`);
|
|
75
|
+
}
|
|
76
|
+
for (const cookie of response.headers.getSetCookie()) {
|
|
77
|
+
res.append('set-cookie', cookie);
|
|
78
|
+
}
|
|
79
|
+
res.redirect(HttpStatus.Found, location);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Sends the browser back to the login page, which says that signing in failed.
|
|
83
|
+
*
|
|
84
|
+
* @param options - Where the app is.
|
|
85
|
+
* @param res - The response.
|
|
86
|
+
* @param error - What went wrong, for the log.
|
|
87
|
+
*/
|
|
88
|
+
function fail({ appUrl, paths }, res, error) {
|
|
89
|
+
console.error(`[auth] OIDC ${SIGN_IN_FAILED}:`, error);
|
|
90
|
+
if (res.headersSent === false) {
|
|
91
|
+
res.redirect(HttpStatus.Found, `${appUrl}${{ ...AUTH_PATHS, ...paths }.login}?error=${SIGN_IN_FAILED}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Settings for the HTTP doors and the process behind them. */
|
|
2
|
+
export interface HttpSettings {
|
|
3
|
+
/** Largest JSON body /graphql and /mcp accept, as `express.json` reads it. Real operations are a few kB. */
|
|
4
|
+
bodyLimit: string;
|
|
5
|
+
/** How long shutdown lets open requests finish before it cuts them. */
|
|
6
|
+
drainSeconds: number;
|
|
7
|
+
/** How long shutdown may take in all before a hard exit. Keep it under Docker's 10 s. */
|
|
8
|
+
shutdownDeadlineSeconds: number;
|
|
9
|
+
/** How long a browser may keep a hashed bundle without asking again. */
|
|
10
|
+
immutableCacheSeconds: number;
|
|
11
|
+
}
|
|
12
|
+
/** What the HTTP helpers use when the app overrides nothing. */
|
|
13
|
+
export declare const HTTP_DEFAULTS: Readonly<HttpSettings>;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Every value someone might tune, as plain data. Nothing here computes, reads the environment or imports.
|
|
2
|
+
/** What the HTTP helpers use when the app overrides nothing. */
|
|
3
|
+
export const HTTP_DEFAULTS = Object.freeze({
|
|
4
|
+
bodyLimit: '1mb',
|
|
5
|
+
drainSeconds: 5,
|
|
6
|
+
shutdownDeadlineSeconds: 8,
|
|
7
|
+
immutableCacheSeconds: 31_536_000,
|
|
8
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Queryable } from '../db/wait.ts';
|
|
2
|
+
/** What `/healthz` answers. */
|
|
3
|
+
export interface Health {
|
|
4
|
+
/** Whether Postgres answered a query just now. */
|
|
5
|
+
ok: boolean;
|
|
6
|
+
/** The release this instance is running. */
|
|
7
|
+
version: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Round-trips to Postgres. A live process with a dead database is not healthy.
|
|
11
|
+
*
|
|
12
|
+
* @param db - Drizzle client.
|
|
13
|
+
* @param version - The release this instance is running.
|
|
14
|
+
* @param [log] - Told why it is not ok.
|
|
15
|
+
* @returns The report. It never says why, since anyone may ask and a driver's error names hosts and users.
|
|
16
|
+
*/
|
|
17
|
+
export declare function checkHealth(db: Queryable, version: string, log?: (message: string, error: unknown) => void): Promise<Health>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { sql } from 'drizzle-orm';
|
|
2
|
+
/**
|
|
3
|
+
* Round-trips to Postgres. A live process with a dead database is not healthy.
|
|
4
|
+
*
|
|
5
|
+
* @param db - Drizzle client.
|
|
6
|
+
* @param version - The release this instance is running.
|
|
7
|
+
* @param [log] - Told why it is not ok.
|
|
8
|
+
* @returns The report. It never says why, since anyone may ask and a driver's error names hosts and users.
|
|
9
|
+
*/
|
|
10
|
+
export async function checkHealth(db, version, log = console.error) {
|
|
11
|
+
try {
|
|
12
|
+
await db.execute(sql `select 1`);
|
|
13
|
+
return { ok: true, version };
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
log('[health] Postgres did not answer:', error);
|
|
17
|
+
return { ok: false, version };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { type AuthRedirectOptions, mountAuthRedirects, oidcRedirectUri, oidcSignInUrl } from './auth-redirects.ts';
|
|
2
|
+
export { HTTP_DEFAULTS, type HttpSettings } from './defaults.ts';
|
|
3
|
+
export { checkHealth, type Health } from './health.ts';
|
|
4
|
+
export { drain, type ShutdownSteps, stopOnSignals } from './shutdown.ts';
|
|
5
|
+
export { createStaticHandler, type StaticHandler } from './static.ts';
|
|
6
|
+
export { HttpStatus } from './status.ts';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { mountAuthRedirects, oidcRedirectUri, oidcSignInUrl } from './auth-redirects.js';
|
|
2
|
+
export { HTTP_DEFAULTS } from './defaults.js';
|
|
3
|
+
export { checkHealth } from './health.js';
|
|
4
|
+
export { drain, stopOnSignals } from './shutdown.js';
|
|
5
|
+
export { createStaticHandler } from './static.js';
|
|
6
|
+
export { HttpStatus } from './status.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Server } from 'node:http';
|
|
2
|
+
import { type HttpSettings } from './defaults.ts';
|
|
3
|
+
/** What runs around the drain. */
|
|
4
|
+
export interface ShutdownSteps {
|
|
5
|
+
/** Stops starting new work (timers, queue pollers). Runs as soon as the signal arrives. */
|
|
6
|
+
before?: () => unknown;
|
|
7
|
+
/** Closes what requests were using (MCP sessions, the pool). Runs once the server has drained. */
|
|
8
|
+
after?: () => unknown;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Stops accepting connections, and waits for every request to finish.
|
|
12
|
+
*
|
|
13
|
+
* @param server - The HTTP server.
|
|
14
|
+
* @param drainSeconds - How long requests in flight get before their sockets are closed.
|
|
15
|
+
* @returns Resolves once the server has closed.
|
|
16
|
+
*/
|
|
17
|
+
export declare function drain(server: Server, drainSeconds: number): Promise<void>;
|
|
18
|
+
/**
|
|
19
|
+
* On SIGTERM or SIGINT: stops accepting, lets in-flight requests finish, closes, exits. A second signal exits at once.
|
|
20
|
+
*
|
|
21
|
+
* @param server - The listening server.
|
|
22
|
+
* @param [steps] - Work to stop before the drain, and resources to close after it.
|
|
23
|
+
* @param [overrides] - Settings that differ from `HTTP_DEFAULTS`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function stopOnSignals(server: Server, { before, after }?: ShutdownSteps, overrides?: Partial<Pick<HttpSettings, 'drainSeconds' | 'shutdownDeadlineSeconds'>>): void;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { HTTP_DEFAULTS } from './defaults.js';
|
|
2
|
+
const MS_PER_SECOND = 1000;
|
|
3
|
+
/** What an orchestrator, or Ctrl-C, sends to ask for a stop. */
|
|
4
|
+
const STOP_SIGNALS = ['SIGTERM', 'SIGINT'];
|
|
5
|
+
/**
|
|
6
|
+
* Stops accepting connections, and waits for every request to finish.
|
|
7
|
+
*
|
|
8
|
+
* @param server - The HTTP server.
|
|
9
|
+
* @param drainSeconds - How long requests in flight get before their sockets are closed.
|
|
10
|
+
* @returns Resolves once the server has closed.
|
|
11
|
+
*/
|
|
12
|
+
export function drain(server, drainSeconds) {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
// Subscriptions never finish on their own.
|
|
15
|
+
const cutOff = setTimeout(() => server.closeAllConnections(), drainSeconds * MS_PER_SECOND);
|
|
16
|
+
server.close(() => {
|
|
17
|
+
clearTimeout(cutOff);
|
|
18
|
+
resolve();
|
|
19
|
+
});
|
|
20
|
+
server.closeIdleConnections();
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* On SIGTERM or SIGINT: stops accepting, lets in-flight requests finish, closes, exits. A second signal exits at once.
|
|
25
|
+
*
|
|
26
|
+
* @param server - The listening server.
|
|
27
|
+
* @param [steps] - Work to stop before the drain, and resources to close after it.
|
|
28
|
+
* @param [overrides] - Settings that differ from `HTTP_DEFAULTS`.
|
|
29
|
+
*/
|
|
30
|
+
export function stopOnSignals(server, { before, after } = {}, overrides = {}) {
|
|
31
|
+
const { drainSeconds, shutdownDeadlineSeconds } = { ...HTTP_DEFAULTS, ...overrides };
|
|
32
|
+
let isStopping = false;
|
|
33
|
+
const stop = async (signal) => {
|
|
34
|
+
if (isStopping) {
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
isStopping = true;
|
|
38
|
+
console.log(`[server] ${signal}: draining`);
|
|
39
|
+
setTimeout(() => {
|
|
40
|
+
console.error('[server] shutdown took too long, exiting');
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}, shutdownDeadlineSeconds * MS_PER_SECOND).unref();
|
|
43
|
+
try {
|
|
44
|
+
await before?.();
|
|
45
|
+
await drain(server, drainSeconds);
|
|
46
|
+
await after?.();
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
console.error('[server] shutdown failed:', error);
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
console.log('[server] stopped');
|
|
53
|
+
process.exit(0);
|
|
54
|
+
};
|
|
55
|
+
for (const signal of STOP_SIGNALS) {
|
|
56
|
+
process.on(signal, (received) => void stop(received));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
/** A request handler, for Express or plain `node:http`. */
|
|
3
|
+
export type StaticHandler = (request: IncomingMessage, response: ServerResponse) => void;
|
|
4
|
+
/**
|
|
5
|
+
* Serves a built single-page app, whose `index.html` answers every path that is not a file.
|
|
6
|
+
*
|
|
7
|
+
* @param root - The directory holding the built app.
|
|
8
|
+
* @returns The handler.
|
|
9
|
+
*
|
|
10
|
+
* @remarks
|
|
11
|
+
* A hashed file that is missing is a 404, never the index: a browser would keep that page under the bundle's name.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createStaticHandler(root: string): StaticHandler;
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { createReadStream, statSync } from 'node:fs';
|
|
2
|
+
import { extname, join, normalize, resolve, sep } from 'node:path';
|
|
3
|
+
import { HTTP_DEFAULTS } from './defaults.js';
|
|
4
|
+
import { HttpStatus } from './status.js';
|
|
5
|
+
const CONTENT_TYPES = {
|
|
6
|
+
'.html': 'text/html; charset=utf-8',
|
|
7
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
8
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
9
|
+
'.css': 'text/css; charset=utf-8',
|
|
10
|
+
'.svg': 'image/svg+xml',
|
|
11
|
+
'.json': 'application/json',
|
|
12
|
+
'.map': 'application/json',
|
|
13
|
+
'.webmanifest': 'application/manifest+json',
|
|
14
|
+
'.png': 'image/png',
|
|
15
|
+
'.jpg': 'image/jpeg',
|
|
16
|
+
'.webp': 'image/webp',
|
|
17
|
+
'.ico': 'image/x-icon',
|
|
18
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
19
|
+
'.woff2': 'font/woff2',
|
|
20
|
+
'.ttf': 'font/ttf',
|
|
21
|
+
'.wasm': 'application/wasm',
|
|
22
|
+
};
|
|
23
|
+
const UNKNOWN_TYPE = 'application/octet-stream';
|
|
24
|
+
/** Where Vite and Expo put files named by their contents. */
|
|
25
|
+
const HASHED_PREFIXES = ['/assets/', '/_expo/'];
|
|
26
|
+
/**
|
|
27
|
+
* Decodes a request's path.
|
|
28
|
+
*
|
|
29
|
+
* @param url - The request's URL.
|
|
30
|
+
* @returns The path, or null when its escapes are malformed.
|
|
31
|
+
*/
|
|
32
|
+
function decodedPathname(url) {
|
|
33
|
+
try {
|
|
34
|
+
return decodeURIComponent(new URL(url ?? '/', 'http://host').pathname);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Whether a path names a file.
|
|
42
|
+
*
|
|
43
|
+
* @param path - The path.
|
|
44
|
+
* @returns false for a directory, and for nothing.
|
|
45
|
+
*/
|
|
46
|
+
function isFileAt(path) {
|
|
47
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Serves a built single-page app, whose `index.html` answers every path that is not a file.
|
|
51
|
+
*
|
|
52
|
+
* @param root - The directory holding the built app.
|
|
53
|
+
* @returns The handler.
|
|
54
|
+
*
|
|
55
|
+
* @remarks
|
|
56
|
+
* A hashed file that is missing is a 404, never the index: a browser would keep that page under the bundle's name.
|
|
57
|
+
*/
|
|
58
|
+
export function createStaticHandler(root) {
|
|
59
|
+
const rootDir = resolve(root);
|
|
60
|
+
return (request, response) => {
|
|
61
|
+
const isRead = request.method === 'GET' || request.method === 'HEAD';
|
|
62
|
+
if (isRead === false) {
|
|
63
|
+
response.writeHead(HttpStatus.MethodNotAllowed, { allow: 'GET, HEAD' }).end();
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const pathname = decodedPathname(request.url);
|
|
67
|
+
// A NUL names no file, and `stat` throws on one.
|
|
68
|
+
if (pathname === null || pathname.includes('\0')) {
|
|
69
|
+
response.writeHead(HttpStatus.BadRequest).end();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const requested = resolve(join(rootDir, normalize(pathname)));
|
|
73
|
+
// `normalize` does not stop a decoded `..` walking out of the root, so the resolved path is compared.
|
|
74
|
+
const isOutside = requested !== rootDir && requested.startsWith(rootDir + sep) === false;
|
|
75
|
+
if (isOutside) {
|
|
76
|
+
response.writeHead(HttpStatus.Forbidden).end();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
const isHashed = HASHED_PREFIXES.some((prefix) => pathname.startsWith(prefix));
|
|
80
|
+
const isFile = isFileAt(requested);
|
|
81
|
+
const filePath = isFile ? requested : join(rootDir, 'index.html');
|
|
82
|
+
const isMissing = isFile === false && (isHashed || isFileAt(filePath) === false);
|
|
83
|
+
if (isMissing) {
|
|
84
|
+
response.writeHead(HttpStatus.NotFound).end();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const headers = {
|
|
88
|
+
'content-type': CONTENT_TYPES[extname(filePath)] ?? UNKNOWN_TYPE,
|
|
89
|
+
'cache-control': isHashed ? `public, max-age=${HTTP_DEFAULTS.immutableCacheSeconds}, immutable` : 'no-cache',
|
|
90
|
+
'x-content-type-options': 'nosniff',
|
|
91
|
+
};
|
|
92
|
+
if (request.method === 'HEAD') {
|
|
93
|
+
response.writeHead(HttpStatus.Ok, headers).end();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const file = createReadStream(filePath);
|
|
97
|
+
// Headers wait for the file to open, so one that cannot be read is a 500 and not half an answer.
|
|
98
|
+
file.once('open', () => {
|
|
99
|
+
response.writeHead(HttpStatus.Ok, headers);
|
|
100
|
+
file.pipe(response);
|
|
101
|
+
});
|
|
102
|
+
file.once('error', (error) => {
|
|
103
|
+
console.error('[static] could not read a file:', error);
|
|
104
|
+
if (response.headersSent) {
|
|
105
|
+
response.destroy();
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
response.writeHead(HttpStatus.InternalServerError).end();
|
|
109
|
+
});
|
|
110
|
+
response.once('close', () => file.destroy());
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The HTTP statuses a server sends, and its tests expect. */
|
|
2
|
+
export declare const HttpStatus: {
|
|
3
|
+
readonly Ok: 200;
|
|
4
|
+
readonly Found: 302;
|
|
5
|
+
readonly BadRequest: 400;
|
|
6
|
+
readonly Forbidden: 403;
|
|
7
|
+
readonly NotFound: 404;
|
|
8
|
+
readonly MethodNotAllowed: 405;
|
|
9
|
+
readonly PayloadTooLarge: 413;
|
|
10
|
+
readonly InternalServerError: 500;
|
|
11
|
+
readonly ServiceUnavailable: 503;
|
|
12
|
+
};
|
|
13
|
+
export type HttpStatus = (typeof HttpStatus)[keyof typeof HttpStatus];
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** The HTTP statuses a server sends, and its tests expect. */
|
|
2
|
+
export const HttpStatus = {
|
|
3
|
+
Ok: 200,
|
|
4
|
+
Found: 302,
|
|
5
|
+
BadRequest: 400,
|
|
6
|
+
Forbidden: 403,
|
|
7
|
+
NotFound: 404,
|
|
8
|
+
MethodNotAllowed: 405,
|
|
9
|
+
PayloadTooLarge: 413,
|
|
10
|
+
InternalServerError: 500,
|
|
11
|
+
ServiceUnavailable: 503,
|
|
12
|
+
};
|
package/llms.txt
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
Agent-facing docs for @cubicecho/server-kit: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
|
|
6
6
|
|
|
7
|
-
Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0, `drizzle-orm` 1.0.0-rc.5, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0, `vitest` ^5.0.0 (optional).
|
|
7
|
+
Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@electric-sql/pglite` ^0.5.0 (optional), `better-auth` >=1.7.28 <1.8.0, `drizzle-orm` 1.0.0-rc.5, `express` ^5.0.0, `graphql` ^16.0.0, `graphql-yoga` ^6.0.0, `postgres` ^3.4.0, `vitest` ^5.0.0 (optional).
|
|
8
8
|
|
|
9
9
|
## Docs
|
|
10
10
|
|
|
@@ -13,6 +13,7 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@ele
|
|
|
13
13
|
- [Test checks](_agents/docs/03-testing.md): `@cubicecho/server-kit/testing` registers Vitest tests that hold an app to the backend standard: its tables, and the Postgres it runs.
|
|
14
14
|
- [Auth preset](_agents/docs/04-auth.md): `@cubicecho/server-kit/auth` has the better-auth options and sign-in plugins every server shares: sessions in Postgres, bearer tokens, emailed links, and OIDC with pairing. The app still calls `betterAuth`, so it adds its own plugins and hooks and keeps exact types.
|
|
15
15
|
- [GraphQL](_agents/docs/05-graphql.md): `@cubicecho/server-kit/graphql` has what every Yoga 6 server shares: operation limits, coded errors, input validation and a logger that never prints a request's variables.
|
|
16
|
+
- [HTTP](_agents/docs/06-http.md): `@cubicecho/server-kit/http` has what surrounds an Express app: a clean stop, the health check, serving the built app, and the two OIDC redirects.
|
|
16
17
|
- [Common mistakes](_agents/docs/common-mistakes.md): What goes wrong when the kit is wired up slightly differently, and the fix for each.
|
|
17
18
|
|
|
18
19
|
## Exports: @cubicecho/server-kit/auth
|
|
@@ -87,6 +88,23 @@ Requires Node >=22. Peer dependencies: `@better-auth/sso` >=1.7.28 <1.8.0, `@ele
|
|
|
87
88
|
- `Parser` (type): A zod schema, by the one method used here.
|
|
88
89
|
- `parseOrThrow`: Parses with zod, turning a failure into BAD_USER_INPUT.
|
|
89
90
|
|
|
91
|
+
## Exports: @cubicecho/server-kit/http
|
|
92
|
+
|
|
93
|
+
- `AuthRedirectOptions` (type): What the two legs of an OIDC sign-in need.
|
|
94
|
+
- `mountAuthRedirects`: Mounts the two legs of an OIDC sign-in, the only better-auth routes a browser has to be redirected through.
|
|
95
|
+
- `oidcRedirectUri`: Names the redirect URI a provider has to have registered.
|
|
96
|
+
- `oidcSignInUrl`: Names where a login button sends the browser.
|
|
97
|
+
- `HTTP_DEFAULTS`: What the HTTP helpers use when the app overrides nothing.
|
|
98
|
+
- `HttpSettings` (type): Settings for the HTTP doors and the process behind them.
|
|
99
|
+
- `checkHealth`: Round-trips to Postgres.
|
|
100
|
+
- `Health` (type): What `/healthz` answers.
|
|
101
|
+
- `drain`: Stops accepting connections, and waits for every request to finish.
|
|
102
|
+
- `ShutdownSteps` (type): What runs around the drain.
|
|
103
|
+
- `stopOnSignals`: On SIGTERM or SIGINT: stops accepting, lets in-flight requests finish, closes, exits.
|
|
104
|
+
- `createStaticHandler`: Serves a built single-page app, whose `index.html` answers every path that is not a file.
|
|
105
|
+
- `StaticHandler` (type): A request handler, for Express or plain `node:http`.
|
|
106
|
+
- `HttpStatus`: The HTTP statuses a server sends, and its tests expect.
|
|
107
|
+
|
|
90
108
|
## Exports: @cubicecho/server-kit/testing
|
|
91
109
|
|
|
92
110
|
- `PostgresFiles` (type): Where a repo says which Postgres it runs.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cubicecho/server-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "The server code every cubicecho GraphQL backend shares: database boot, id columns and the checks that keep a schema to the standard.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Benjamin Van Treese",
|
|
@@ -39,6 +39,10 @@
|
|
|
39
39
|
"types": "./dist/graphql/index.d.ts",
|
|
40
40
|
"import": "./dist/graphql/index.js"
|
|
41
41
|
},
|
|
42
|
+
"./http": {
|
|
43
|
+
"types": "./dist/http/index.d.ts",
|
|
44
|
+
"import": "./dist/http/index.js"
|
|
45
|
+
},
|
|
42
46
|
"./testing": {
|
|
43
47
|
"types": "./dist/testing/index.d.ts",
|
|
44
48
|
"import": "./dist/testing/index.js"
|
|
@@ -67,6 +71,7 @@
|
|
|
67
71
|
"@electric-sql/pglite": "^0.5.0",
|
|
68
72
|
"better-auth": ">=1.7.28 <1.8.0",
|
|
69
73
|
"drizzle-orm": "1.0.0-rc.5",
|
|
74
|
+
"express": "^5.0.0",
|
|
70
75
|
"graphql": "^16.0.0",
|
|
71
76
|
"graphql-yoga": "^6.0.0",
|
|
72
77
|
"postgres": "^3.4.0",
|
|
@@ -91,6 +96,7 @@
|
|
|
91
96
|
"@semantic-release/github": "^12.0.11",
|
|
92
97
|
"@semantic-release/npm": "^13.2.0",
|
|
93
98
|
"@semantic-release/release-notes-generator": "^14.1.1",
|
|
99
|
+
"@types/express": "^5.0.6",
|
|
94
100
|
"@types/node": "^24.19.4",
|
|
95
101
|
"better-auth": "^1.7.28",
|
|
96
102
|
"drizzle-kit": "^1.0.0-rc.5",
|