-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathserver.ts
More file actions
356 lines (316 loc) · 12 KB
/
Copy pathserver.ts
File metadata and controls
356 lines (316 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import { createCsrfMiddleware } from '@constructive-io/csrf';
import { getEnvOptions } from '@constructive-io/graphql-env';
import type { ConstructiveOptions } from '@constructive-io/graphql-types';
import { Logger } from '@pgpmjs/logger';
import { healthz, poweredBy, svcCache, trustProxy } from '@pgpmjs/server-utils';
import { PgpmOptions } from '@pgpmjs/types';
import { middleware as parseDomains } from '@constructive-io/url-domains';
import cookieParser from 'cookie-parser';
import express, { Express, NextFunction, Request, RequestHandler, Response } from 'express';
import type { Server as HttpServer } from 'http';
import graphqlUpload from 'graphql-upload';
import { Pool, PoolClient } from 'pg';
import { graphileCache, closeAllCaches } from 'graphile-cache';
import { getPgPool } from 'pg-cache';
import requestIp from 'request-ip';
import type { DebugSamplerHandle } from './diagnostics/debug-sampler';
import { closeDebugDatabasePools } from './diagnostics/debug-db-snapshot';
import {
isDevelopmentObservabilityMode,
isGraphqlObservabilityEnabled,
isGraphqlObservabilityRequested,
isLoopbackHost,
} from './diagnostics/observability';
import { createApiMiddleware } from './middleware/api';
import { createAuthenticateMiddleware } from './middleware/auth';
import { cors } from './middleware/cors';
import { errorHandler, notFoundHandler } from './middleware/error-handler';
import { favicon } from './middleware/favicon';
import { flush, flushService } from './middleware/flush';
import { graphile } from './middleware/graphile';
import { multipartBridge } from './middleware/multipart-bridge';
import { createDebugDatabaseMiddleware } from './middleware/observability/debug-db';
import { debugMemory } from './middleware/observability/debug-memory';
import { localObservabilityOnly } from './middleware/observability/guard';
import { createRequestLogger } from './middleware/observability/request-logger';
// Auth cookie handling is done via AuthCookiePlugin in grafserv
import { createCaptchaMiddleware } from './middleware/captcha';
import { parseCookieValue, SESSION_COOKIE_NAME } from './middleware/cookie';
import { createAgenticRouter } from 'agentic-server';
import { createContextMiddleware, requestIdMiddleware } from '@constructive-io/express-context';
import { startDebugSampler } from './diagnostics/debug-sampler';
const log = new Logger('server');
/**
* Creates and starts a GraphQL server instance
*
* Accepts ConstructiveOptions or PgpmOptions.
* Options are normalized using normalizeServerOptions to apply defaults.
*
* @param rawOpts - Server configuration options
* @returns void (server runs until shutdown)
*
* @example
* ```typescript
* // Using ConstructiveOptions (recommended)
* GraphQLServer({
* pg: { database: 'myapp' },
* server: { port: 4000 }
* });
*
* // Using PgpmOptions
* GraphQLServer(pgpmOptions);
* ```
*/
export const GraphQLServer = (rawOpts: ConstructiveOptions | PgpmOptions = {}) => {
const opts = getEnvOptions(rawOpts);
const app = new Server(opts);
app.addEventListener();
app.listen();
};
class Server {
private app: Express;
private opts: ConstructiveOptions;
private listenClient: PoolClient | null = null;
private listenRelease: (() => void) | null = null;
private shuttingDown = false;
private closed = false;
private httpServer: HttpServer | null = null;
private debugSampler: DebugSamplerHandle | null = null;
constructor(opts: ConstructiveOptions) {
this.opts = getEnvOptions(opts);
const effectiveOpts = this.opts;
const observabilityRequested = isGraphqlObservabilityRequested();
const observabilityEnabled = isGraphqlObservabilityEnabled(effectiveOpts.server?.host);
const app = express();
const api = createApiMiddleware(effectiveOpts);
const authenticate = createAuthenticateMiddleware(effectiveOpts);
const requestLogger = createRequestLogger({ observabilityEnabled });
// Log startup configuration (non-sensitive values only)
const apiOpts = (effectiveOpts as any).api || {};
log.info('[server] Starting with config:', {
database: effectiveOpts.pg?.database,
host: effectiveOpts.pg?.host,
port: effectiveOpts.pg?.port,
serverHost: effectiveOpts.server?.host,
serverPort: effectiveOpts.server?.port,
apiIsPublic: apiOpts.isPublic,
enableServicesApi: apiOpts.enableServicesApi,
metaSchemas: apiOpts.metaSchemas?.join(',') || 'default',
exposedSchemas: apiOpts.exposedSchemas?.join(',') || 'none',
anonRole: apiOpts.anonRole,
roleName: apiOpts.roleName,
observabilityEnabled,
});
if (observabilityRequested && !observabilityEnabled) {
const reasons = [];
if (!isDevelopmentObservabilityMode()) {
reasons.push('NODE_ENV must be development');
}
if (!isLoopbackHost(effectiveOpts.server?.host)) {
reasons.push('server host must be localhost, 127.0.0.1, or ::1');
}
log.warn(
`GRAPHQL_OBSERVABILITY_ENABLED was requested but observability remains disabled${
reasons.length > 0 ? `: ${reasons.join('; ')}` : ''
}`,
);
}
healthz(app);
if (observabilityEnabled) {
app.get('/debug/memory', localObservabilityOnly, debugMemory);
app.get('/debug/db', localObservabilityOnly, createDebugDatabaseMiddleware(effectiveOpts));
} else {
app.use('/debug', (_req, res) => {
res.status(404).send('Not found');
});
}
app.use(favicon);
trustProxy(app, effectiveOpts.server.trustProxy);
// Warn if a global CORS override is set in production
const fallbackOrigin = effectiveOpts.server?.origin?.trim();
if (fallbackOrigin && process.env.NODE_ENV === 'production') {
if (fallbackOrigin === '*') {
log.warn(
'CORS wildcard ("*") is enabled in production; this effectively disables CORS and is not recommended. Prefer per-API CORS via meta schema.',
);
} else {
log.warn(`CORS override origin set to ${fallbackOrigin} in production. Prefer per-API CORS via meta schema.`);
}
}
app.use(poweredBy('constructive'));
app.use(cookieParser());
app.use(cors(fallbackOrigin));
const uploadMaxFileSize = effectiveOpts.upload?.maxFileSize ?? 10 * 1024 * 1024;
app.use('/graphql', graphqlUpload.graphqlUploadExpress({
maxFileSize: uploadMaxFileSize,
maxFiles: 10,
}));
// Rewrite Content-Type after graphql-upload so grafserv accepts the request
app.use('/graphql', multipartBridge);
app.use(parseDomains() as RequestHandler);
app.use(requestIp.mw());
app.use(requestIdMiddleware());
app.use(requestLogger);
app.use(api);
app.use(authenticate);
app.use(createContextMiddleware({ pg: effectiveOpts.pg }));
app.use(createCaptchaMiddleware({
recaptchaSecretKey: effectiveOpts.captcha?.recaptchaSecretKey,
}));
// CSRF protection for cookie-authenticated requests
// Skip CSRF for Bearer token auth (not vulnerable to CSRF) and anonymous requests
const csrf = createCsrfMiddleware({
cookieOptions: {
httpOnly: false, // SPA clients need to read this via document.cookie
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
},
});
const csrfProtect: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
// Skip CSRF for Bearer token auth
const auth = req.headers.authorization;
if (auth?.toLowerCase().startsWith('bearer ')) {
return next();
}
// Skip if no session cookie (anonymous requests)
const sessionCookie = parseCookieValue(req, SESSION_COOKIE_NAME);
if (!sessionCookie) {
return next();
}
// Apply CSRF protection for cookie-authenticated requests
csrf.protect(req as any, res as any, next);
};
const csrfSetToken: RequestHandler = (req: Request, res: Response, next: NextFunction) => {
csrf.setToken(req as any, res as any, next);
};
app.use(csrfSetToken); // Set CSRF token cookie on all requests
app.use('/graphql', csrfProtect); // Enforce CSRF on GraphQL mutations
// LLM Agent REST API — mounted before graphile so SSE streaming
// routes are handled without going through PostGraphile
app.use(createAgenticRouter());
app.use(graphile(effectiveOpts));
app.use(flush);
// Error handling - MUST be LAST
app.use(notFoundHandler); // Catches unmatched routes (404)
app.use(errorHandler); // Catches all thrown errors
this.app = app;
this.debugSampler = observabilityEnabled ? startDebugSampler(effectiveOpts) : null;
}
listen(): HttpServer {
const { server } = this.opts;
const httpServer = this.app.listen(server?.port, server?.host, () =>
log.info(`listening at http://${server?.host}:${server?.port}`),
);
httpServer.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE') {
this.error(`Port ${server?.port ?? 'unknown'} is already in use`, err);
} else {
this.error('Server failed to start', err);
}
throw err;
});
this.httpServer = httpServer;
return httpServer;
}
async flush(databaseId: string): Promise<void> {
await flushService(this.opts, databaseId);
}
getPool(): Pool {
return getPgPool(this.opts.pg);
}
addEventListener(): void {
if (this.shuttingDown) return;
const pgPool = this.getPool();
pgPool.connect(this.listenForChanges.bind(this));
}
listenForChanges(err: Error | null, client: PoolClient, release: () => void): void {
if (err) {
this.error('Error connecting with notify listener', err);
if (!this.shuttingDown) {
setTimeout(() => this.addEventListener(), 5000);
}
return;
}
if (this.shuttingDown) {
release();
return;
}
this.listenClient = client;
this.listenRelease = release;
client.on('notification', ({ channel, payload }) => {
if (channel === 'schema:update' && payload) {
log.info('schema:update', payload);
this.flush(payload);
}
});
client.query('LISTEN "schema:update"');
client.on('error', (e) => {
if (this.shuttingDown) {
release();
return;
}
this.error('Error with database notify listener', e);
release();
this.addEventListener();
});
this.log('connected and listening for changes...');
}
async removeEventListener(): Promise<void> {
if (!this.listenClient || !this.listenRelease) {
return;
}
const client = this.listenClient;
const release = this.listenRelease;
this.listenClient = null;
this.listenRelease = null;
client.removeAllListeners('notification');
client.removeAllListeners('error');
try {
await client.query('UNLISTEN "schema:update"');
} catch {
// Ignore listener cleanup errors during shutdown.
}
release();
}
async close(opts: { closeCaches?: boolean } = {}): Promise<void> {
const { closeCaches = false } = opts;
if (this.closed) {
if (closeCaches) {
await Server.closeCaches({ closePools: true });
}
return;
}
this.closed = true;
this.shuttingDown = true;
await this.removeEventListener();
if (this.debugSampler) {
await this.debugSampler.stop();
this.debugSampler = null;
}
if (this.httpServer?.listening) {
await new Promise<void>((resolve) => this.httpServer!.close(() => resolve()));
}
await closeDebugDatabasePools();
if (closeCaches) {
await Server.closeCaches({ closePools: true });
}
}
static async closeCaches(opts: { closePools?: boolean } = {}): Promise<void> {
const { closePools = false } = opts;
svcCache.clear();
// Use closeAllCaches to properly await async disposal of PostGraphile instances
// before closing pg pools - this ensures all connections are released
if (closePools) {
await closeAllCaches();
} else {
graphileCache.clear();
}
}
log(text: string): void {
log.info(text);
}
error(text: string, err?: unknown): void {
log.error(text, err);
}
}
export { Server };