-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathserver.ts
More file actions
1569 lines (1453 loc) · 65.5 KB
/
Copy pathserver.ts
File metadata and controls
1569 lines (1453 loc) · 65.5 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import compression from 'compression';
import cookieParser from 'cookie-parser';
import express from 'express';
import type { Application, RequestHandler } from 'express';
import helmet from 'helmet';
import uaParser from 'ua-parser-js';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
import http from 'node:http';
import { puterClients } from './clients';
import { puterControllers } from './controllers';
import { createAuthProbe } from './core/http/middleware/authProbe';
import { createRequestContextMiddleware } from './core/http/middleware/requestContext';
import { createFingerprintMiddleware } from './core/http/middleware/fingerprint';
import { createErrorHandler } from './core/http/middleware/errorHandler';
import { isHttpError } from './core/http/HttpError';
import {
adminOnlyGate,
allowedAppIdsGate,
noUserSessionGate,
requireAuthGate,
requireCardVerifiedGate,
requirePhoneVerifiedGate,
requireVerifiedAccount,
requireNonAccessTokenGate,
requireUserActorGate,
requireVerifiedGate,
subdomainGate,
} from './core/http/middleware/gates';
import { guiOriginGate } from './core/http/middleware/originGate';
import { requireCreditsGate } from './core/http/middleware/credits';
import { requireSubscriptionGate } from './core/http/middleware/subscription';
import { validateSubscriptionRequirement } from './services/metering/enforcement';
import { createStepUpGate } from './core/http/middleware/stepUpSession';
import { createNotFoundHandler } from './core/http/middleware/notFoundHandler';
import { installProcessGuards } from './util/processGuards';
import { activeSubdomain, subdomainOffsetForDomain } from './util/subdomains';
import {
requireAntiCsrf,
setAntiCsrfRedis,
} from './core/http/middleware/antiCsrf';
import { captchaGate, setCaptchaRedis } from './core/http/middleware/captcha';
import {
concurrencyGate,
configureRateLimit,
rateLimitGate,
} from './core/http/middleware/rateLimit';
import {
createWwwRedirect,
createUserSubdomainRedirect,
createNativeAppStatic,
} from './core/http/middleware/hostRedirects';
import { createEgressMeteringMiddleware } from './core/http/middleware/egressMetering';
import { createLocalWorkerProxyMiddleware } from './core/http/middleware/localWorkerProxy';
import { createPuterSiteMiddleware } from './core/http/middleware/puterSite';
import { PuterRouter } from './core/http/PuterRouter';
import { createRouteLifecycleMiddleware } from './core/http/routeLifecycle';
import { PREFIX_METADATA_KEY, type RouteDescriptor } from './core/http/types';
import type { AuthService } from './services/auth/AuthService';
import { puterDrivers } from './drivers';
import {
clientsContainers,
configContainer,
controllersContainers,
driversContainers,
servicesContainers,
storesContainers,
} from './exports';
import { extensionStore } from './extensions';
import { puterServices } from './services';
import { puterStores } from './stores';
import type {
IConfig,
LayerInstances,
PagerSeverity,
WithControllerRegistration,
WithLifecycle,
} from './types';
export class PuterServer {
clients!: LayerInstances<typeof puterClients>;
stores!: LayerInstances<typeof puterStores>;
services!: LayerInstances<typeof puterServices>;
controllers!: LayerInstances<typeof puterControllers>;
drivers!: LayerInstances<typeof puterDrivers>;
#config: IConfig;
#app!: ReturnType<typeof express>;
#server: ReturnType<ReturnType<typeof express>['listen']> | null = null;
#removeProcessGuards: (() => void) | null = null;
#ready: Promise<boolean>;
constructor(
config: IConfig,
clients: typeof puterClients = puterClients,
stores: typeof puterStores = puterStores,
services: typeof puterServices = puterServices,
controllers: typeof puterControllers = puterControllers,
drivers: typeof puterDrivers = puterDrivers,
) {
this.#config = config;
// Expose config to the extension API (extension.config)
Object.assign(configContainer, config);
this.#ready = this.#setupServer(
clients,
stores,
services,
controllers,
drivers,
);
}
async #setupServer(
clients: typeof puterClients,
stores: typeof puterStores,
services: typeof puterServices,
controllers: typeof puterControllers,
drivers: typeof puterDrivers,
) {
// Load prod extensions from configured directories (dynamic)
const extensionDirs = this.#config.extensions;
await this.#importExtensions(extensionDirs);
this.clients = {} as typeof this.clients;
for (const [clientName, ClientClass] of Object.entries(clients)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.clients[clientName] =
typeof ClientClass === 'object'
? ClientClass
: (new (ClientClass as any)(this.#config) as any);
// @ts-expect-error implicit any casting to avoid overly complex or circular types
clientsContainers[clientName] = this.clients[clientName];
}
for (const [clientName, ClientClass] of Object.entries(
extensionStore.clients,
)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.clients[clientName] =
typeof ClientClass === 'object'
? ClientClass
: (new (ClientClass as any)(this.#config) as any);
// @ts-expect-error implicit any casting to avoid overly complex or circular types
clientsContainers[clientName] = this.clients[clientName];
}
this.stores = {} as typeof this.stores;
for (const [storeName, StoreClass] of Object.entries(stores)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.stores[storeName] =
typeof StoreClass === 'object'
? StoreClass
: (new (StoreClass as any)(
this.#config,
this.clients,
this.stores,
) as any);
// @ts-expect-error implicit any casting to avoid overly complex or circular types
storesContainers[storeName] = this.stores[storeName];
}
for (const [storeName, StoreClass] of Object.entries(
extensionStore.stores,
)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.stores[storeName] =
typeof StoreClass === 'object'
? StoreClass
: (new (StoreClass as any)(
this.#config,
this.clients,
this.stores,
) as any);
// @ts-expect-error implicit any casting to avoid overly complex or circular types
storesContainers[storeName] = this.stores[storeName];
}
this.services = {} as typeof this.services;
for (const [serviceName, ServiceClass] of Object.entries(services)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.services[serviceName] =
typeof ServiceClass === 'object'
? ServiceClass
: (new (ServiceClass as any)(
this.#config,
this.clients,
this.stores,
this.services,
) as any);
// @ts-expect-error implicit any casting to avoid overly complex or circular types
servicesContainers[serviceName] = this.services[serviceName];
}
for (const [serviceName, ServiceClass] of Object.entries(
extensionStore.services,
)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.services[serviceName] =
typeof ServiceClass === 'object'
? ServiceClass
: (new (ServiceClass as any)(
this.#config,
this.clients,
this.stores,
this.services,
) as any);
// @ts-expect-error implicit any casting to avoid overly complex or circular types
servicesContainers[serviceName] = this.services[serviceName];
}
// Wire the rate-limiter to its configured backend now that clients
// and stores exist. Memory is the default; `redis` needs a redis
// client, `kv` needs the system KV store (DynamoDB-backed).
this.#configureRateLimiter();
// Anti-CSRF tokens live in redis so they survive cross-node hops
// (issue on node A, consume on node B).
setAntiCsrfRedis(this.clients.redis);
setCaptchaRedis(this.clients.redis);
// init express server here
this.#app = express();
// `trust proxy` MUST be set before any middleware reads `req.ip` /
// `req.ips` / `req.protocol`, since express derives those from XFF
// only when this flag is set. Default is `false` (no proxy trusted)
// — deployments behind a reverse proxy chain must set
// `config.trust_proxy` to the hop count (e.g. `1` for a single
// Cloudflare/nginx hop). Never `true` in prod: that trusts every hop
// and makes XFF forgeable.
this.#app.set('trust proxy', this.#config.trust_proxy ?? false);
// Every subdomain gate reads `req.subdomains`, which express derives by
// dropping `subdomain offset` labels from the right of the hostname.
// The offset is the root domain's own label count, so a deployment on
// `puter.example.com` doesn't read `puter` as an active subdomain.
this.#app.set(
'subdomain offset',
subdomainOffsetForDomain(this.#config.domain),
);
this.#installGlobalMiddleware();
// Instantiate drivers BEFORE controllers so controllers can receive
// a typed `drivers` reference. The `/drivers/*` HTTP surface lives
// on `DriverController` (a regular controller) which reads from
// `this.drivers` — no separate registry object here any more.
this.drivers = {} as typeof this.drivers;
const allDriverSources = [
...Object.entries(drivers),
...Object.entries(extensionStore.drivers),
];
for (const [driverKey, DriverClass] of allDriverSources) {
const instance =
typeof DriverClass === 'object'
? DriverClass
: (new (DriverClass as any)(
this.#config,
this.clients,
this.stores,
this.services,
) as any);
// @ts-expect-error as any casting to avoid overly complex or circular types
this.drivers[driverKey] = instance;
driversContainers[driverKey] = instance;
}
this.controllers = {} as typeof this.controllers;
for (const [controllerName, ControllerClass] of Object.entries(
controllers,
)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.controllers[controllerName] =
typeof ControllerClass === 'object'
? ControllerClass
: (new (ControllerClass as any)(
this.#config,
this.clients,
this.stores,
this.services,
this.drivers,
) as any);
this.#registerControllerRoutes(
controllerName,
// @ts-expect-error as any casting to avoid overly complex or circular types
this.controllers[controllerName],
);
controllersContainers[controllerName] =
// @ts-expect-error as any casting to avoid overly complex or circular types
this.controllers[controllerName];
}
for (const [controllerName, ControllerClass] of Object.entries(
extensionStore.controllers,
)) {
// @ts-expect-error as any casting to avoid overly complex or circular types
this.controllers[controllerName] =
typeof ControllerClass === 'object'
? ControllerClass
: (new (ControllerClass as any)(
this.#config,
this.clients,
this.stores,
this.services,
this.drivers,
) as any);
this.#registerControllerRoutes(
controllerName,
// @ts-expect-error as any casting to avoid overly complex or circular types
this.controllers[controllerName],
);
controllersContainers[controllerName] =
// @ts-expect-error as any casting to avoid overly complex or circular types
this.controllers[controllerName];
}
// Extension routes are shaped as `RouteDescriptor`s too, so they
// flow through the same materializer as controller routes — same
// option → middleware translation (subdomain, auth, body parsers, …).
// The extension-layer "prefix" is always empty; extensions compose
// their own path strings.
for (const route of extensionStore.routeHandlers) {
this.#materializeRoute(this.#app, '', route);
}
// Terminal middleware MUST install last — after every route + extension
// route is registered, so the catch-all 404 only fires for genuinely
// unmatched requests, and the error handler is reachable from any
// thrown error in the stack above it.
this.#installTerminalMiddleware();
return true;
}
/**
* Register every rate-limit backend whose dependency is available, so
* routes / drivers can mix and match per call. `config.rate_limit.backend`
* selects the _default_ applied when a caller doesn't specify a backend;
* it's no longer an exclusive choice. A typo or missing dependency for the
* chosen default falls back to memory with a warning so boot doesn't
* break.
*/
#configureRateLimiter() {
// Default to `redis` — the redis client is always present (falls
// back to ioredis-mock in dev when no nodes are configured), and
// sorted-set rate limiting scales across nodes for free. Set
// `rate_limit.backend` in config to switch to `memory` or `kv`.
const defaultBackend = this.#config.rate_limit?.backend ?? 'redis';
// Metering is wired so the concurrency gate can resolve
// `bySubscription` overrides per actor. Optional — without it,
// the base `limit` applies uniformly.
const metering = this.services?.metering as unknown;
try {
configureRateLimit({
default: defaultBackend,
redis: this.clients.redis,
kv: this.stores.kv,
metering,
});
} catch (e) {
console.warn(
`[rate-limit] default backend '${defaultBackend}' unavailable, falling back to memory:`,
(e as Error).message,
);
configureRateLimit({
redis: this.clients.redis,
kv: this.stores.kv,
metering,
});
}
}
/**
* Install always-on middleware on the express app, in the order they must
* run at request time. Ordering note:
*
* - `express.json` must run before `authProbe` so `req.body.auth_token` is
* readable.
* - `authProbe` never rejects; it only populates `req.actor` if a valid token
* is present.
* - Per-route gate middleware (requireAuth, adminOnly, ...) lands in
* `#materializeRoute` as those options ship.
*/
#installGlobalMiddleware() {
// -- Egress metering -----------------------------------------
// First, so the byte counter wraps `res.write` before compression
// does and therefore counts what actually goes out rather than what
// the handler produced. Reads the actor when the response ends, by
// which point the auth probe below has run.
this.#app.use(
createEgressMeteringMiddleware({ services: this.services }),
);
this.#app.use(cookieParser());
this.#app.use(compression());
this.#app.use(helmet.noSniff());
this.#app.use(helmet.hsts());
this.#app.use(helmet.ieNoOpen());
this.#app.use(helmet.permittedCrossDomainPolicies());
this.#app.use(helmet.xssFilter());
// Don't leak full URLs (which can carry signed tokens / file paths)
// to cross-origin destinations. Per-user hosted sites tighten this
// further to `no-referrer` in the puterSite middleware.
this.#app.use(
helmet.referrerPolicy({
policy: 'strict-origin-when-cross-origin',
}),
);
this.#app.disable('x-powered-by');
// Cross-Origin-Resource-Policy: always allow cross-origin reads.
// The stricter COOP+COEP pair (for SharedArrayBuffer) is deferred
// until the hosting layer lands — it requires UA + context gating.
this.#app.use((_req, res, next) => {
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
next();
});
// -- Query param sanitization --------------------------------
// Strip non-primitive query values. Express 5's default simple
// parser mostly avoids these, but when `extended` qs is enabled
// (or a client tricks the parser) arrays/objects can sneak in.
this.#app.use((req, _res, next) => {
if (req.query) {
const allowed = ['string', 'number', 'boolean'];
for (const k of Object.keys(req.query)) {
const v = req.query[k];
if (v != null && !allowed.includes(typeof v)) {
delete req.query[k];
}
}
}
next();
});
// -- UA parsing ----------------------------------------------
this.#app.use((req, _res, next) => {
const header = req.headers['user-agent'];
if (header) {
req.ua = uaParser(header);
}
next();
});
// -- Host header validation ----------------------------------
this.#installHostValidation();
// -- Host redirects (www → root, user subdomain → static hosting)
// Installed after host validation so we know the host is allowed,
// and before CORS/body-parsing so we short-circuit on redirects
// without burning work.
this.#app.use(createWwwRedirect(this.#config));
this.#app.use(createUserSubdomainRedirect(this.#config));
// -- Native app static serving (editor.*, docs.*, …) ---------
// No-op when `native_apps_root` is unset.
this.#app.use(createNativeAppStatic(this.#config));
// -- CORS headers --------------------------------------------
this.#installCors();
// -- IP validation -------------------------------------------
if (this.#config.enable_ip_validation) {
this.#installIpValidation();
}
// -- OPTIONS preflight ---------------------------------------
// WebDAV is exempt: OPTIONS is how a DAV client discovers the server,
// and the reply has to carry `DAV:` and `Allow:` for the mount to
// proceed. Answering it here with a bare 200 tells the client this
// isn't a WebDAV server at all, so let it fall through to the
// controller, which builds the real response.
this.#app.options('/*splat', (req, res, next) => {
if (activeSubdomain(req) === 'dav') {
next();
return;
}
res.sendStatus(200);
});
// -- Local Worker proxy (*.workers.puter.localhost) ----------
// Dev-only Miniflare dispatch, gated on `config.workers.localServer`.
// Mounted BEFORE body parsing so the Worker receives the raw request
// stream; no-op in production (real Cloudflare via WorkerDriver).
this.#app.use(
createLocalWorkerProxyMiddleware(this.#config, {
clients: this.clients,
stores: this.stores,
services: this.services,
}),
);
// -- Body parsing (JSON + text-as-json shim) -----------------
const captureRawBody: NonNullable<
Parameters<typeof express.json>[0]
>['verify'] = (req, _res, buf) => {
(req as { rawBody?: Buffer }).rawBody = Buffer.from(buf);
};
this.#app.use(express.json({ limit: '50mb', verify: captureRawBody }));
this.#app.use(
express.json({
limit: '50mb',
type: (req) =>
req.headers['content-type'] === 'text/plain;actually=json',
verify: captureRawBody,
}),
);
// Form-encoded bodies (e.g. `/down` from the GUI's iframe-triggered
// download form). Needs to run before the auth probe so
// `req.body.auth_token` is populated for urlencoded POSTs the same
// way it is for JSON POSTs. Small cap — this parser is only here to
// cover the auth_token / anti_csrf field shape, not file uploads.
this.#app.use(express.urlencoded({ extended: true, limit: '100kb' }));
// -- Auth probe ----------------------------------------------
const authService = this.services.auth as AuthService | undefined;
if (authService) {
this.#app.use(
createAuthProbe({
authService,
cookieName: this.#config.cookie_name,
}),
);
}
// -- Request fingerprints ------------------------------------
// Stamp `req.networkFingerprint` (server-derived) and
// `req.deviceFingerprint` (client-supplied, from body/header). Runs
// AFTER body parsing so the body fingerprint is readable, and before
// the ALS context so the snapshot carries them.
this.#app.use(createFingerprintMiddleware());
// -- Per-request ALS context ---------------------------------
// Runs AFTER auth probe so `req.actor` is already populated when
// we snapshot it into the context.
this.#app.use(createRequestContextMiddleware());
// -- User-hosted sites (*.puter.site, *.puter.app) -----------
// Short-circuits hosting-domain hosts before any API/GUI
// controller route has a chance to match. Needs DI layers for
// subdomain lookup, private-app gate, and file streaming.
this.#app.use(
createPuterSiteMiddleware(this.#config, {
clients: this.clients,
stores: this.stores,
services: this.services,
}),
);
extensionStore.globalMiddlewares.forEach((mw) => {
this.#app.use(mw);
});
}
// -- Host header validation --------------------------------------
#installHostValidation() {
const config = this.#config;
// Hostname missing — malformed request from a broken client.
this.#app.use((req, res, next) => {
if (req.hostname === undefined) {
res.status(400).send(
'Please verify your browser is up-to-date.',
);
return;
}
next();
});
// Build the allowed-domain set from config.
this.#app.use((req, res, next) => {
if (config.allow_all_host_values) {
next();
return;
}
if (!config.allow_no_host_header && !req.headers.host) {
res.status(400).send('Missing Host header.');
return;
}
// /healthcheck is always reachable regardless of host.
if (req.path === '/healthcheck') {
next();
return;
}
const hostName = (req.headers.host ?? '')
.split(':')[0]
.trim()
.toLowerCase();
const allowed = this.#getAllowedDomains();
if (
allowed.some((d) => PuterServer.#hostMatchesDomain(hostName, d))
) {
next();
return;
}
if (config.custom_domains_enabled) {
req.is_custom_domain = true;
next();
return;
}
res.status(400).send('Invalid Host header.');
});
}
#allowedDomainsCache: string[] | null = null;
#getAllowedDomains(): string[] {
if (this.#allowedDomainsCache) return this.#allowedDomainsCache;
const cfg = this.#config;
const raw = [
cfg.domain,
cfg.static_hosting_domain,
cfg.static_hosting_domain_alt,
cfg.private_app_hosting_domain,
cfg.private_app_hosting_domain_alt,
];
const staticDomain = PuterServer.#normalizeDomain(
cfg.static_hosting_domain,
);
if (staticDomain) raw.push(`at.${staticDomain}`);
if (cfg.allow_nipio_domains) raw.push('nip.io');
this.#allowedDomainsCache = raw
.map(PuterServer.#normalizeDomain)
.filter((d): d is string => d !== null);
return this.#allowedDomainsCache;
}
static #normalizeDomain(d: string | undefined | null): string | null {
if (!d || typeof d !== 'string') return null;
const trimmed = d.trim().toLowerCase();
return trimmed.length > 0 ? trimmed : null;
}
static #hostMatchesDomain(hostname: string, domain: string): boolean {
return hostname === domain || hostname.endsWith(`.${domain}`);
}
// -- CORS headers -------------------------------------------------
#installCors() {
const config = this.#config;
const allowedMethods =
'GET, POST, OPTIONS, PUT, PATCH, DELETE, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, UNLOCK';
const allowedHeaders = [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Authorization',
'Cache-Control',
'Pragma',
'sentry-trace',
'baggage',
'Depth',
'Destination',
'Overwrite',
'If',
'Lock-Token',
'Timeout',
'X-Expected-Entity-Length',
'DAV',
'stripe-signature',
].join(', ');
// What a browser DAV client is allowed to read back off a response.
// Everything below is a header the WebDAV controller sets and a client
// acts on: without this list `fetch` hands the page a response whose
// ETag, lock token and content range are all invisible, so it can't
// cache, lock, or resume anything.
const davExposedHeaders = [
'DAV',
'MS-Author-Via',
'Allow',
'ETag',
'Last-Modified',
'Content-Length',
'Content-Range',
'Accept-Ranges',
'Location',
'Lock-Token',
'WWW-Authenticate',
].join(', ');
this.#app.use((req, res, next) => {
const origin = req.headers.origin;
const subdomain = activeSubdomain(req);
// Allow any origin. puter.js is meant to be consumed from
// arbitrary third-party sites, so reflect the caller's origin
// (or fall back to `*` for non-browser clients).
res.setHeader('Access-Control-Allow-Origin', origin ?? '*');
if (origin) res.vary('Origin');
// Sticky cookies require api to allow credentials, but only for the API subdomain, and be careful not to set any other credentials on it
if (subdomain === 'api' && origin) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
} else if (subdomain === 'dav') {
res.setHeader('Access-Control-Allow-Credentials', 'false');
res.setHeader(
'Access-Control-Expose-Headers',
davExposedHeaders,
);
}
res.setHeader('Access-Control-Allow-Methods', allowedMethods);
res.setHeader('Access-Control-Allow-Headers', allowedHeaders);
res.setHeader('Access-Control-Allow-Private-Network', 'true');
// Disable iframes on the main domain
if (req.hostname === config.domain) {
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
}
next();
});
}
// -- IP validation -----------------------------------------------
#installIpValidation() {
this.#app.use(async (req, res, next) => {
// `req.ip` reflects `trust proxy`: it's the leftmost untrusted
// address from XFF when behind a configured proxy chain, and the
// direct socket peer otherwise. Reading XFF directly would let a
// client forge the value when traffic isn't behind the expected
// proxy.
const ip = req.ip;
const event = { allow: true, ip: ip! };
// emitAndWait so listeners that do async work (IP-reputation
// lookups, Redis checks) can complete before we read
// `event.allow` and decide the gate.
await this.clients.event.emitAndWait('ip.validate', event, {});
if (!event.allow) {
res.status(403).send('Forbidden');
return;
}
next();
});
}
/**
* Install end-of-pipeline middleware. Order matters:
*
* 1. The 404 catch-all runs only when no earlier route matched, so it must be
* installed _after_ every controller + extension route.
* 2. The error handler is the express terminal — it catches everything thrown
* by routes, gates, and the 404 above. Express 5 auto-forwards thrown
* errors (sync and async), so handlers can `throw new HttpError(...)`
* without `next(err)` ceremony.
*/
#installTerminalMiddleware() {
this.#app.use(
createNotFoundHandler({ guiDomain: this.#config.domain }),
);
this.#app.use(
createErrorHandler({
onError: (err, req) => {
// Page on 5xx only — skip 4xx HttpErrors, which are
// expected client-caused failures. Non-HttpError values
// are treated as unexpected 500s. De-dupe alarms by
// route + error signature so a hot loop of the same
// crash lands as a single alarm with N occurrences
// instead of N pages.
//
// FORCED_ALERT_CODES override the 5xx-only rule: a
// status < 500 still alarms if its legacyCode is in
// the map. Use this for things we want to know about
// even though we expose them as 4xx to users (e.g.
// sustained upstream provider rate limits). They are
// not our own crashes, so each maps to the severity it
// deserves rather than paging.
//
// SKIP_ALERT_PREFIXES override the 5xx rule the other
// direction: an error tagged as caused by an upstream
// provider or a misbehaving client gets exposed to
// the user but does not alarm at all.
//
// `noAlarm` beats both: the call site already decided
// this failure isn't worth recording (e.g. an upstream
// rate limit on a free model, where the volume tracks
// traffic and there's nothing to act on).
const FORCED_ALERT_CODES = new Map<string, PagerSeverity>([
['upstream_rate_limited', 'info'],
// Our credentials for a provider stopped working —
// everything through it fails until someone looks.
['upstream_auth_failed', 'warning'],
]);
const SKIP_ALERT_PREFIXES = /^(upstream_|client_)/;
const isHttp = isHttpError(err);
if (isHttp && err.noAlarm) return;
const status = isHttp ? err.statusCode : 500;
const legacyCode = isHttp ? (err.legacyCode ?? '') : '';
const forcedSeverity = FORCED_ALERT_CODES.get(legacyCode);
if (!forcedSeverity) {
if (status < 500) return;
if (SKIP_ALERT_PREFIXES.test(legacyCode)) return;
}
const signature = !isHttp
? err instanceof Error
? err.message
: String(err)
: status >= 500
? `${err.legacyCode || err.code || 'http'}:${err.message}`
: err.legacyCode || err.code || err.message;
const routePath =
(req as unknown as { route?: { path?: string } }).route
?.path ?? req.path;
const alarmId = `http_${status}:${req.method}:${routePath}:${signature}`;
this.clients.alarm.create(
alarmId,
`HTTP ${status} on ${req.method} ${req.originalUrl}: ${signature}`,
{
error: err instanceof Error ? err : undefined,
status,
method: req.method,
path: req.originalUrl,
body: req.body,
route: routePath,
actor: req.actor,
},
// An unhandled server error is the one thing that
// still pages on-call.
forcedSeverity ?? 'critical',
// The id pins route + error signature, so repeats are
// the same fault and belong on one incident.
{ dedup: true },
);
},
}),
);
}
/**
* Walk a controller's declared routes (via `PuterRouter`) and register each
* one against the underlying express app. Per-route option → middleware
* translation lives here — when we add auth/subdomain/body-parsing options,
* they get wired in at this single point without touching any controller
* call site.
*/
#registerControllerRoutes(
controllerName: string,
controller: WithControllerRegistration,
) {
if (!controller.registerRoutes) {
throw new Error(
`Controller ${controllerName} does not have registerRoutes method`,
);
}
// Controllers annotated with `@Controller('/prefix')` carry the prefix
// on their prototype; bare (imperative) controllers default to ''.
const prefix = (controller as unknown as Record<string, unknown>)[
PREFIX_METADATA_KEY
] as string | undefined;
const router = new PuterRouter(prefix ?? '');
controller.registerRoutes(router);
for (const route of router.routes) {
this.#materializeRoute(this.#app, router.prefix, route);
}
}
#materializeRoute(
app: Application,
routerPrefix: string,
route: RouteDescriptor,
) {
const mwChain: RequestHandler[] = [];
const opts = route.options;
// Validated here rather than trusted, and by the same function the
// driver decorator uses: a malformed requirement is a boot failure
// naming the route, never a gate that quietly admits everyone.
const subscriptionRequirement =
opts.requireSubscription === undefined
? undefined
: validateSubscriptionRequirement(
opts.requireSubscription,
`route ${route.method.toUpperCase()} ${routerPrefix}${String(route.path)}: requireSubscription`,
);
const requiresSubscription =
subscriptionRequirement !== undefined &&
subscriptionRequirement !== false;
// 1. Subdomain routing. Routes that specify `subdomain` only match
// that subdomain(s). Routes WITHOUT a `subdomain` option (and that
// aren't `use` middleware) are restricted to the root origin — this
// prevents API-subdomain requests from accidentally hitting a root-
// only route. Explicit `subdomain: '*'` disables the gate entirely.
//
// For `use` routes, `next('route')` in a middleware doesn't skip the
// handler (that's only reliable inside `app.METHOD`/`router.METHOD`
// chains). We handle subdomain gating by wrapping the handler for
// `use` routes further down — don't push `subdomainGate` here.
const isUse = route.method === 'use';
if (opts.subdomain !== undefined) {
if (opts.subdomain !== '*' && !isUse) {
mwChain.push(subdomainGate(opts.subdomain));
}
// subdomain: '*' → no gate, match any subdomain
} else if (!isUse) {
// No subdomain specified + not a `use()` middleware → root only.
// Root = no subdomain present (req.subdomains is empty).
mwChain.push((req, _res, next) => {
if (req.subdomains && req.subdomains.length > 0) {
next('route');
return;
}
next();
});
}
// 1b. Origin gate. Runs before auth, rate limiting, and captcha so an
// off-origin caller is rejected on the header alone — it never reaches
// the credential comparison, and it can't burn another request's rate
// limit budget on the way. Unauthenticated by nature: the routes that
// opt in are the ones that *hand out* a credential.
if (opts.guiOriginOnly) {
mwChain.push(guiOriginGate(this.#config));
}
// 2. Auth gates. Implication graph:
// adminOnly => requireAuth
// allowedAppIds => requireAuth
// requireUserActor => requireAuth
// Dedupe: only push requireAuthGate once when *any* of these are set.
const needsAuth = Boolean(
opts.requireAuth ||
opts.requireUserActor ||
opts.adminOnly ||
opts.allowedAppIds ||
opts.requireVerified ||
opts.noUserSession ||
opts.requirePhoneVerified ||
opts.requireCardVerified ||
requiresSubscription,
);
if (needsAuth) {
mwChain.push(requireAuthGate());
}
// Default-on account-verification gate. Every authenticated route
// rejects accounts still pending any signup-time verification —
// email confirmation, SMS phone verification, or card verification —
// unless `allowUnconfirmed` opts out. This is what keeps low-reputation
// signups (which the abuse harness flags instead of hard-blocking) out
// of AI, FS, driver, etc. endpoints server-side, not just behind the
// GUI modal, while still allowing essential flows (logout,
// confirm-email / -phone, card verification, whoami, save-account, …).
if (needsAuth && !opts.allowUnconfirmed) {
mwChain.push(requireVerifiedAccount());
}
// block access tokens by default
if (needsAuth && !opts.allowAccessToken) {
mwChain.push(requireNonAccessTokenGate());
}
// `requireVerified` intentionally does NOT imply `requireUserActor`:
// FS routes (and similar) want the user's email to be confirmed even
// when an app acts on the user's behalf. `requireVerifiedGate` reads
// `req.actor?.user?.email_confirmed`, which app-under-user actors
// carry, so it works for either actor shape.
//
// `adminOnly` also does NOT imply `requireUserActor`: admin endpoints
// stay callable from scripts/automation using an admin's full-access
// token, not only from browser sessions — both are root tokens.
// Beyond the username check, `adminOnlyGate` requires a root token
// (rejecting an admin acting through a third-party app) unless the
// route is also appId-gated, in which case `allowedAppIdsGate` governs
// which apps may pass.
if (opts.requireUserActor) {
mwChain.push(
requireUserActorGate({