@geekmidas/edge 0.0.0-stage → 10.0.0-alpha.182

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.
Files changed (84) hide show
  1. package/README.md +14 -2
  2. package/dist/certificates/local.cjs +393 -0
  3. package/dist/certificates/local.cjs.map +1 -0
  4. package/dist/certificates/local.d.cts +92 -0
  5. package/dist/certificates/local.d.cts.map +1 -0
  6. package/dist/certificates/local.d.mts +92 -0
  7. package/dist/certificates/local.d.mts.map +1 -0
  8. package/dist/certificates/local.mjs +361 -0
  9. package/dist/certificates/local.mjs.map +1 -0
  10. package/dist/compose-BHWyQvsD.cjs +22 -0
  11. package/dist/compose-BHWyQvsD.cjs.map +1 -0
  12. package/dist/compose-CcNlj65h.mjs +17 -0
  13. package/dist/compose-CcNlj65h.mjs.map +1 -0
  14. package/dist/dns/godaddy/index.cjs +448 -0
  15. package/dist/dns/godaddy/index.cjs.map +1 -0
  16. package/dist/dns/godaddy/index.d.cts +164 -0
  17. package/dist/dns/godaddy/index.d.cts.map +1 -0
  18. package/dist/dns/godaddy/index.d.mts +164 -0
  19. package/dist/dns/godaddy/index.d.mts.map +1 -0
  20. package/dist/dns/godaddy/index.mjs +435 -0
  21. package/dist/dns/godaddy/index.mjs.map +1 -0
  22. package/dist/dns/hostinger/index.cjs +252 -0
  23. package/dist/dns/hostinger/index.cjs.map +1 -0
  24. package/dist/dns/hostinger/index.d.cts +143 -0
  25. package/dist/dns/hostinger/index.d.cts.map +1 -0
  26. package/dist/dns/hostinger/index.d.mts +143 -0
  27. package/dist/dns/hostinger/index.d.mts.map +1 -0
  28. package/dist/dns/hostinger/index.mjs +249 -0
  29. package/dist/dns/hostinger/index.mjs.map +1 -0
  30. package/dist/dns/index.cjs +76 -0
  31. package/dist/dns/index.cjs.map +1 -0
  32. package/dist/dns/index.d.cts +144 -0
  33. package/dist/dns/index.d.cts.map +1 -0
  34. package/dist/dns/index.d.mts +144 -0
  35. package/dist/dns/index.d.mts.map +1 -0
  36. package/dist/dns/index.mjs +71 -0
  37. package/dist/dns/index.mjs.map +1 -0
  38. package/dist/dns/route53.cjs +210 -0
  39. package/dist/dns/route53.cjs.map +1 -0
  40. package/dist/dns/route53.d.cts +45 -0
  41. package/dist/dns/route53.d.cts.map +1 -0
  42. package/dist/dns/route53.d.mts +45 -0
  43. package/dist/dns/route53.d.mts.map +1 -0
  44. package/dist/dns/route53.mjs +209 -0
  45. package/dist/dns/route53.mjs.map +1 -0
  46. package/dist/errors-CO33_TDV.mjs +16 -0
  47. package/dist/errors-CO33_TDV.mjs.map +1 -0
  48. package/dist/errors-DBZfelEN.d.cts +13 -0
  49. package/dist/errors-DBZfelEN.d.cts.map +1 -0
  50. package/dist/errors-DBZfelEN.d.mts +13 -0
  51. package/dist/errors-DBZfelEN.d.mts.map +1 -0
  52. package/dist/errors-DlRLQOyZ.cjs +27 -0
  53. package/dist/errors-DlRLQOyZ.cjs.map +1 -0
  54. package/dist/index.cjs +6 -0
  55. package/dist/index.d.cts +15 -0
  56. package/dist/index.d.cts.map +1 -0
  57. package/dist/index.d.mts +15 -0
  58. package/dist/index.d.mts.map +1 -0
  59. package/dist/index.mjs +3 -0
  60. package/dist/proxy/caddy.cjs +167 -0
  61. package/dist/proxy/caddy.cjs.map +1 -0
  62. package/dist/proxy/caddy.d.cts +35 -0
  63. package/dist/proxy/caddy.d.cts.map +1 -0
  64. package/dist/proxy/caddy.d.mts +35 -0
  65. package/dist/proxy/caddy.d.mts.map +1 -0
  66. package/dist/proxy/caddy.mjs +164 -0
  67. package/dist/proxy/caddy.mjs.map +1 -0
  68. package/dist/proxy/traefik.cjs +460 -0
  69. package/dist/proxy/traefik.cjs.map +1 -0
  70. package/dist/proxy/traefik.d.cts +129 -0
  71. package/dist/proxy/traefik.d.cts.map +1 -0
  72. package/dist/proxy/traefik.d.mts +129 -0
  73. package/dist/proxy/traefik.d.mts.map +1 -0
  74. package/dist/proxy/traefik.mjs +437 -0
  75. package/dist/proxy/traefik.mjs.map +1 -0
  76. package/dist/routes/index.cjs +49 -0
  77. package/dist/routes/index.cjs.map +1 -0
  78. package/dist/routes/index.d.cts +205 -0
  79. package/dist/routes/index.d.cts.map +1 -0
  80. package/dist/routes/index.d.mts +205 -0
  81. package/dist/routes/index.d.mts.map +1 -0
  82. package/dist/routes/index.mjs +44 -0
  83. package/dist/routes/index.mjs.map +1 -0
  84. package/package.json +131 -3
@@ -0,0 +1,437 @@
1
+ import { t as composeLiteral } from "../compose-CcNlj65h.mjs";
2
+ import { EDGE_LIMITS, assertRouteRenderable, routeHosts } from "../routes/index.mjs";
3
+ import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from "@geekmidas/manifest";
4
+ import { createHash } from "node:crypto";
5
+ import { parse, stringify } from "yaml";
6
+ //#region src/proxy/traefik.ts
7
+ /**
8
+ * The server's shared edge, rendered for Traefik: what the edge itself runs
9
+ * with, and what one stack registers with it.
10
+ *
11
+ * One Traefik per server owns 80 and 443, the ACME state and the redirect to
12
+ * HTTPS. It is configured through its file provider alone: each stack writes
13
+ * one file — its routers, services and middlewares, every name prefixed with
14
+ * its compose project — into a directory the edge watches, and removes it
15
+ * when it stops. There is no Docker socket: the edge never learns what runs
16
+ * on the server except from those files.
17
+ *
18
+ * The edge and the stacks meet on one external Docker network. Only a
19
+ * stack's public services join it, each under an alias prefixed with its
20
+ * project (`<project>-api`), because the network is shared: a bare service
21
+ * name there would be answered by every stack's `api`.
22
+ *
23
+ * Pure but for the edge's name, read from the environment once (see
24
+ * {@link EDGE_PROJECT_ENV}): the documents are data, and the edge's side
25
+ * effects are `edge.ts`'s.
26
+ */
27
+ /**
28
+ * The image, pinned: the edge is every stack's way in, so a new version is a
29
+ * change to this line, not whatever `latest` is on the day a server starts.
30
+ */
31
+ const TRAEFIK_IMAGE = "traefik:v3.7.13";
32
+ /** The edge's name when nothing renames it: one per server. */
33
+ const DEFAULT_EDGE_PROJECT = "gkm-edge";
34
+ /**
35
+ * The variable that renames the edge — its compose project, and with it its
36
+ * network and its volumes (`<project>_acme`, `_certs`, `_dynamic`). A testing
37
+ * and advanced knob: an end-to-end suite runs an edge of its own beside a
38
+ * developer's, and never touches theirs. Every command that registers with
39
+ * one edge must be run with the same value.
40
+ */
41
+ const EDGE_PROJECT_ENV = "GKM_EDGE_PROJECT";
42
+ /** The edge's compose project: `GKM_EDGE_PROJECT`, else `gkm-edge`. */
43
+ function edgeProject(env = process.env) {
44
+ return env["GKM_EDGE_PROJECT"] || "gkm-edge";
45
+ }
46
+ /**
47
+ * The edge's compose project, one per server — read once, when gkm starts,
48
+ * so every step of a run names the same edge.
49
+ */
50
+ const EDGE_PROJECT = edgeProject();
51
+ /**
52
+ * The external network the edge and every stack's public services share:
53
+ * named after the edge, so a renamed edge has a network of its own.
54
+ */
55
+ const EDGE_NETWORK = EDGE_PROJECT;
56
+ /** The edge's compose service. */
57
+ const EDGE_SERVICE = "traefik";
58
+ /** Inside the edge's container: what it watches, and where certificates are. */
59
+ const EDGE_DYNAMIC_DIR = "/etc/gkm-edge/dynamic";
60
+ const EDGE_CERTS_DIR = "/etc/gkm-edge/certs";
61
+ /** The certificate resolver every deployed route without its own certificate uses. */
62
+ const ACME_RESOLVER = "letsencrypt";
63
+ /**
64
+ * The resolver a wildcard site's `*.<domain>` certificate comes from: Let's
65
+ * Encrypt issues a wildcard only over the DNS challenge, which the edge
66
+ * answers by writing an `_acme-challenge` TXT record through Route 53.
67
+ */
68
+ const ACME_DNS_RESOLVER = "letsencrypt-dns";
69
+ /**
70
+ * The key the edge writes those records with, inside its container: written
71
+ * by the deploy of a stage with a wildcard site, and allowed nothing but
72
+ * each such stage's `_acme-challenge` record (see `acmeDns.ts`).
73
+ */
74
+ const EDGE_AWS_CREDENTIALS = `${EDGE_CERTS_DIR}/aws-credentials`;
75
+ /** The internal entrypoint the edge's health check asks; never published. */
76
+ const PING_PORT = 8082;
77
+ /** A stack's service, as the edge — and the stack itself — reach it. */
78
+ function edgeAlias(project, service) {
79
+ return `${project}-${service}`;
80
+ }
81
+ /** A stack's certificate, as the edge's container reads it. */
82
+ function edgeCertificatePaths(project) {
83
+ return {
84
+ certFile: `${EDGE_CERTS_DIR}/${project}.crt`,
85
+ keyFile: `${EDGE_CERTS_DIR}/${project}.key`
86
+ };
87
+ }
88
+ /**
89
+ * The edge's static configuration: the entrypoints, the redirect, ACME, and
90
+ * the directory it watches. No API and no dashboard — nothing about the edge
91
+ * is reachable but the routes stacks register.
92
+ */
93
+ function traefikStatic(ports) {
94
+ return {
95
+ global: {
96
+ checkNewVersion: false,
97
+ sendAnonymousUsage: false
98
+ },
99
+ entryPoints: {
100
+ web: {
101
+ address: ":80",
102
+ http: { redirections: { entryPoint: {
103
+ to: ports.https === 443 ? "websecure" : `:${ports.https}`,
104
+ scheme: "https",
105
+ permanent: true
106
+ } } }
107
+ },
108
+ websecure: { address: ":443" },
109
+ ping: { address: `:${PING_PORT}` }
110
+ },
111
+ ping: { entryPoint: "ping" },
112
+ providers: { file: {
113
+ directory: EDGE_DYNAMIC_DIR,
114
+ watch: true
115
+ } },
116
+ certificatesResolvers: {
117
+ [ACME_RESOLVER]: { acme: {
118
+ storage: "/acme/acme.json",
119
+ httpChallenge: { entryPoint: "web" }
120
+ } },
121
+ [ACME_DNS_RESOLVER]: { acme: {
122
+ storage: "/acme/acme-dns.json",
123
+ dnsChallenge: {
124
+ provider: "route53",
125
+ resolvers: ["1.1.1.1:53", "8.8.8.8:53"]
126
+ }
127
+ } }
128
+ },
129
+ log: { level: "INFO" }
130
+ };
131
+ }
132
+ /** The edge's compose document. */
133
+ function edgeCompose(options) {
134
+ const { ports } = options;
135
+ return {
136
+ name: EDGE_PROJECT,
137
+ services: { [EDGE_SERVICE]: {
138
+ image: TRAEFIK_IMAGE,
139
+ restart: "unless-stopped",
140
+ ports: [`${ports.https}:443`, `${ports.http}:80`],
141
+ configs: [{
142
+ source: "traefik",
143
+ target: "/etc/traefik/traefik.yml"
144
+ }],
145
+ volumes: [
146
+ `dynamic:${EDGE_DYNAMIC_DIR}`,
147
+ `certs:${EDGE_CERTS_DIR}`,
148
+ "acme:/acme"
149
+ ],
150
+ labels: { "dev.geekmidas.edge.config": createHash("sha256").update(options.staticConfig).digest("hex").slice(0, 16) },
151
+ environment: {
152
+ AWS_SHARED_CREDENTIALS_FILE: EDGE_AWS_CREDENTIALS,
153
+ AWS_REGION: "us-east-1"
154
+ },
155
+ networks: ["edge"],
156
+ ...EDGE_LIMITS,
157
+ healthcheck: {
158
+ test: [
159
+ "CMD",
160
+ "traefik",
161
+ "healthcheck",
162
+ "--ping"
163
+ ],
164
+ interval: "10s",
165
+ timeout: "5s",
166
+ retries: 5
167
+ },
168
+ logging: options.logging
169
+ } },
170
+ configs: { traefik: { content: composeLiteral(options.staticConfig) } },
171
+ volumes: {
172
+ acme: {},
173
+ dynamic: {},
174
+ certs: {}
175
+ },
176
+ networks: { edge: {
177
+ name: EDGE_NETWORK,
178
+ external: true
179
+ } }
180
+ };
181
+ }
182
+ /** A stack's dynamic configuration, as an object. */
183
+ function traefikDynamic(routes, options) {
184
+ const { project, tls, edgeToken } = options;
185
+ const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
186
+ const url = ({ service, port }) => `http://${edgeAlias(project, service)}:${port}`;
187
+ const routers = {};
188
+ const services = {};
189
+ const middlewares = {};
190
+ const strip = `${project}-strip-gkm-headers`;
191
+ if (routes.length > 0) middlewares[strip] = { headers: { customRequestHeaders: { [CLIENT_IP_HEADER]: "" } } };
192
+ for (const route of routes) {
193
+ const chain = [strip];
194
+ const limited = /* @__PURE__ */ new Set();
195
+ if (route.allow) {
196
+ middlewares[name(route, "allow")] = { ipAllowList: { sourceRange: [...route.allow] } };
197
+ chain.push(name(route, "allow"));
198
+ }
199
+ if (route.auth) {
200
+ middlewares[name(route, "auth")] = { basicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] } };
201
+ chain.push(name(route, "auth"));
202
+ }
203
+ if (route.limits?.handshakesPerMinute) {
204
+ const perMinute = route.limits.handshakesPerMinute;
205
+ middlewares[name(route, "rate")] = { rateLimit: {
206
+ average: perMinute,
207
+ period: "1m",
208
+ burst: perMinute
209
+ } };
210
+ chain.push(name(route, "rate"));
211
+ limited.add(name(route, "rate"));
212
+ }
213
+ if (route.limits?.connectionsPerIp) {
214
+ middlewares[name(route, "in-flight")] = { inFlightReq: { amount: route.limits.connectionsPerIp } };
215
+ chain.push(name(route, "in-flight"));
216
+ limited.add(name(route, "in-flight"));
217
+ }
218
+ if (route.prefix) {
219
+ middlewares[name(route, "prefix")] = { addPrefix: { prefix: route.prefix } };
220
+ chain.push(name(route, "prefix"));
221
+ }
222
+ assertRouteRenderable(route);
223
+ const allowed = [...(route.paths ?? []).map((path) => `Path(\`${path}\`)`), ...(route.prefixes ?? []).map((prefix) => `PathPrefix(\`${prefix}\`)`)];
224
+ const paths = allowed.length ? ` && (${allowed.join(" || ")})` : "";
225
+ const header = route.requireHeader ? ` && Header(\`${route.requireHeader.name}\`, \`${route.requireHeader.value}\`)` : "";
226
+ const certificate = () => route.wildcard?.tls.kind === "dns" ? {
227
+ certResolver: ACME_DNS_RESOLVER,
228
+ domains: [{ main: `*.${route.wildcard.domain}` }]
229
+ } : tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {};
230
+ for (const handler of route.handlers ?? []) {
231
+ const handlerName = name(route, handler.name);
232
+ routers[handlerName] = {
233
+ rule: `${hostRule(route)} && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
234
+ priority: 1e4,
235
+ entryPoints: ["websecure"],
236
+ service: handlerName,
237
+ middlewares: [strip],
238
+ tls: certificate()
239
+ };
240
+ services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
241
+ }
242
+ if (route.redirects?.hosts.length) {
243
+ const redirect = name(route, "redirect");
244
+ middlewares[redirect] = { redirectRegex: {
245
+ regex: "^https?://[^/]+(.*)$",
246
+ replacement: `${route.redirects.to}$\{1}`,
247
+ permanent: true
248
+ } };
249
+ route.redirects.hosts.forEach((host, index) => {
250
+ routers[name(route, `redirect-${index + 1}`)] = {
251
+ rule: `Host(\`${host}\`)`,
252
+ entryPoints: ["websecure"],
253
+ service: "noop@internal",
254
+ middlewares: [redirect],
255
+ tls: certificate()
256
+ };
257
+ });
258
+ }
259
+ const rule = `${hostRule(route)}${paths}${header}`;
260
+ routers[name(route)] = {
261
+ rule,
262
+ ...route.wildcard ? { priority: 1 } : {},
263
+ entryPoints: ["websecure"],
264
+ service: name(route),
265
+ middlewares: chain,
266
+ tls: certificate()
267
+ };
268
+ if (edgeToken && !route.prefix) {
269
+ const trusted = chain.slice(1).filter((m) => !limited.has(m));
270
+ routers[name(route, "stack")] = {
271
+ rule: `${rule} && Header(\`${EDGE_TOKEN_HEADER}\`, \`${edgeToken}\`)`,
272
+ ...route.wildcard ? { priority: 2 } : {},
273
+ entryPoints: ["websecure"],
274
+ service: name(route),
275
+ ...trusted.length > 0 ? { middlewares: trusted } : {},
276
+ tls: certificate()
277
+ };
278
+ }
279
+ services[name(route)] = { loadBalancer: {
280
+ servers: route.upstreams.map((upstream) => ({ url: url(upstream) })),
281
+ ...route.prefix ? { passHostHeader: false } : {},
282
+ ...route.streaming ? { responseForwarding: { flushInterval: "-1ms" } } : {},
283
+ ...route.health ? { healthCheck: {
284
+ path: route.health,
285
+ interval: "5s",
286
+ timeout: "3s"
287
+ } } : {}
288
+ } };
289
+ }
290
+ return {
291
+ http: {
292
+ routers,
293
+ services,
294
+ ...Object.keys(middlewares).length > 0 ? { middlewares } : {}
295
+ },
296
+ ...tls.kind === "files" ? { tls: { certificates: [{
297
+ certFile: tls.certFile,
298
+ keyFile: tls.keyFile
299
+ }] } } : {}
300
+ };
301
+ }
302
+ /**
303
+ * The hosts a route answers, as a Traefik rule: its own and its aliases', or
304
+ * — for a wildcard site — exactly one label under its domain, but the ones
305
+ * it never takes. One label, as a wildcard certificate covers: a stage at
306
+ * `staging.example.com` is never reached through `example.com`'s wildcard.
307
+ *
308
+ * Several hosts are parenthesised, `(Host(a) || Host(b))`, so whatever is
309
+ * joined to the rule with `&&` — the path allowlist, a required header, the
310
+ * stack's token — holds on every one of them. One router's hosts are one
311
+ * certificate's names under ACME.
312
+ */
313
+ function hostRule(route) {
314
+ if (!route.wildcard) {
315
+ const hosts = [route.host, ...route.aliases ?? []].map((host) => `Host(\`${host}\`)`);
316
+ return hosts.length === 1 ? hosts[0] : `(${hosts.join(" || ")})`;
317
+ }
318
+ const { domain, except } = route.wildcard;
319
+ return [`HostRegexp(\`${`^[a-z0-9-]+\\.${domain.replace(/\./g, "\\.")}$`}\`)`, ...except.map((label) => `!Host(\`${label}.${domain}\`)`)].join(" && ");
320
+ }
321
+ /**
322
+ * What a stack's routes claim on the edge, from the route model: one claim
323
+ * per host, each route's aliases and redirects included.
324
+ */
325
+ function edgeClaims(routes) {
326
+ return routes.flatMap((route) => route.wildcard ? [{
327
+ wildcard: route.wildcard.domain.toLowerCase(),
328
+ except: [...route.wildcard.except]
329
+ }] : routeHosts(route).map((host) => ({ host: host.toLowerCase() })));
330
+ }
331
+ /**
332
+ * The comment line a stack's file carries its claims on: a comment, because
333
+ * Traefik's file provider refuses a whole file over a key it does not know,
334
+ * and gkm reads it back rather than taking the routers' rules apart.
335
+ */
336
+ const CLAIMS_PREFIX = "# gkm-claims: ";
337
+ /**
338
+ * The hosts a stack's file on the edge claims: from its claims line, or — a
339
+ * file written before gkm wrote one — from its routers' rules, in the shapes
340
+ * `traefikDynamic` renders them.
341
+ */
342
+ function readEdgeClaims(file) {
343
+ for (const line of file.split("\n")) {
344
+ if (!line.startsWith(CLAIMS_PREFIX)) continue;
345
+ try {
346
+ const claims = JSON.parse(line.slice(14));
347
+ if (Array.isArray(claims)) return claims.filter(isClaim);
348
+ } catch {}
349
+ }
350
+ let document;
351
+ try {
352
+ document = parse(file);
353
+ } catch {
354
+ return [];
355
+ }
356
+ const routers = document?.http?.routers;
357
+ if (!routers || typeof routers !== "object") return [];
358
+ const claims = [];
359
+ for (const router of Object.values(routers)) {
360
+ const rule = router?.rule;
361
+ if (typeof rule === "string") claims.push(...ruleClaims(rule));
362
+ }
363
+ return claims;
364
+ }
365
+ function isClaim(value) {
366
+ if (!value || typeof value !== "object") return false;
367
+ const claim = value;
368
+ return typeof claim.host === "string" || typeof claim.wildcard === "string" && Array.isArray(claim.except);
369
+ }
370
+ /**
371
+ * The hosts a rule matches: each `Host(\`a\`)` not negated, and a
372
+ * `HostRegexp` of a wildcard site — one label under a domain — with the
373
+ * `!Host` labels it leaves out.
374
+ */
375
+ function ruleClaims(rule) {
376
+ const negated = [...rule.matchAll(/!\s*Host\(`([^`]+)`\)/g)].map((match) => match[1].toLowerCase());
377
+ const wildcard = /HostRegexp\(`\^\[a-z0-9-\]\+\\\.(.+)\$`\)/.exec(rule);
378
+ if (wildcard) {
379
+ const domain = wildcard[1].replace(/\\\./g, ".").toLowerCase();
380
+ const suffix = `.${domain}`;
381
+ return [{
382
+ wildcard: domain,
383
+ except: negated.filter((host) => host.endsWith(suffix)).map((host) => host.slice(0, -suffix.length))
384
+ }];
385
+ }
386
+ return [...rule.matchAll(/(?<![!\w])Host\(`([^`]+)`\)/g)].map((match) => ({ host: match[1].toLowerCase() }));
387
+ }
388
+ /**
389
+ * Where two claims meet, as a host to name — or undefined where they never
390
+ * do. A wildcard takes one label under its domain, so it meets a name one
391
+ * label under it that it does not leave out, and another wildcard on the
392
+ * same domain.
393
+ */
394
+ function claimsOverlap(a, b) {
395
+ if ("host" in a && "host" in b) return a.host === b.host ? a.host : void 0;
396
+ if ("wildcard" in a && "wildcard" in b) return a.wildcard === b.wildcard ? `*.${a.wildcard}` : void 0;
397
+ const [name, wildcard] = "host" in a ? [a, b] : [b, a];
398
+ const suffix = `.${wildcard.wildcard}`;
399
+ if (!name.host.endsWith(suffix)) return void 0;
400
+ const label = name.host.slice(0, -suffix.length);
401
+ if (!/^[a-z0-9-]+$/.test(label) || wildcard.except.includes(label)) return;
402
+ return name.host;
403
+ }
404
+ /** A stack's dynamic configuration file, as written to the edge's directory. */
405
+ function traefikDynamicFile(routes, options) {
406
+ return `# Generated by gkm compose for ${options.project} — do not edit.
407
+ # The shared edge (${EDGE_PROJECT}) reads every file in this directory; this
408
+ # one is removed by gkm compose --down. The hosts it routes, which no other
409
+ # stack on the edge may route:
410
+ ${CLAIMS_PREFIX}${JSON.stringify(edgeClaims(routes))}
411
+ ${yaml(traefikDynamic(routes, options))}`;
412
+ }
413
+ /** The edge's static configuration file. */
414
+ function traefikStaticFile(ports) {
415
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
416
+ ${yaml(traefikStatic(ports))}`;
417
+ }
418
+ /** The edge's compose file. */
419
+ function edgeComposeFile(options) {
420
+ return `# Generated by gkm compose — the server's shared edge. Do not edit.
421
+ #
422
+ # Started by the first stack that runs with proxy: 'traefik', and left
423
+ # running by gkm compose --down. Stop it, once nothing uses it, with:
424
+ #
425
+ # docker compose -p ${EDGE_PROJECT} down
426
+ ${yaml(edgeCompose(options))}`;
427
+ }
428
+ function yaml(value) {
429
+ return stringify(value, {
430
+ lineWidth: 0,
431
+ aliasDuplicateObjects: false
432
+ });
433
+ }
434
+ //#endregion
435
+ export { ACME_DNS_RESOLVER, ACME_RESOLVER, DEFAULT_EDGE_PROJECT, EDGE_AWS_CREDENTIALS, EDGE_CERTS_DIR, EDGE_DYNAMIC_DIR, EDGE_NETWORK, EDGE_PROJECT, EDGE_PROJECT_ENV, EDGE_SERVICE, TRAEFIK_IMAGE, claimsOverlap, edgeAlias, edgeCertificatePaths, edgeClaims, edgeCompose, edgeComposeFile, edgeProject, readEdgeClaims, traefikDynamic, traefikDynamicFile, traefikStatic, traefikStaticFile };
436
+
437
+ //# sourceMappingURL=traefik.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"traefik.mjs","names":[],"sources":["../../src/proxy/traefik.ts"],"sourcesContent":["/**\n * The server's shared edge, rendered for Traefik: what the edge itself runs\n * with, and what one stack registers with it.\n *\n * One Traefik per server owns 80 and 443, the ACME state and the redirect to\n * HTTPS. It is configured through its file provider alone: each stack writes\n * one file — its routers, services and middlewares, every name prefixed with\n * its compose project — into a directory the edge watches, and removes it\n * when it stops. There is no Docker socket: the edge never learns what runs\n * on the server except from those files.\n *\n * The edge and the stacks meet on one external Docker network. Only a\n * stack's public services join it, each under an alias prefixed with its\n * project (`<project>-api`), because the network is shared: a bare service\n * name there would be answered by every stack's `api`.\n *\n * Pure but for the edge's name, read from the environment once (see\n * {@link EDGE_PROJECT_ENV}): the documents are data, and the edge's side\n * effects are `edge.ts`'s.\n */\n\nimport { createHash } from 'node:crypto';\nimport { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from '@geekmidas/manifest';\nimport { parse, stringify } from 'yaml';\nimport { composeLiteral } from '../compose';\nimport {\n\tassertRouteRenderable,\n\tEDGE_LIMITS,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\trouteHosts,\n\ttype Upstream,\n} from '../routes';\n\n/**\n * The image, pinned: the edge is every stack's way in, so a new version is a\n * change to this line, not whatever `latest` is on the day a server starts.\n */\nexport const TRAEFIK_IMAGE = 'traefik:v3.7.13';\n\n/** The edge's name when nothing renames it: one per server. */\nexport const DEFAULT_EDGE_PROJECT = 'gkm-edge';\n\n/**\n * The variable that renames the edge — its compose project, and with it its\n * network and its volumes (`<project>_acme`, `_certs`, `_dynamic`). A testing\n * and advanced knob: an end-to-end suite runs an edge of its own beside a\n * developer's, and never touches theirs. Every command that registers with\n * one edge must be run with the same value.\n */\nexport const EDGE_PROJECT_ENV = 'GKM_EDGE_PROJECT';\n\n/** The edge's compose project: `GKM_EDGE_PROJECT`, else `gkm-edge`. */\nexport function edgeProject(env: NodeJS.ProcessEnv = process.env): string {\n\treturn env[EDGE_PROJECT_ENV] || DEFAULT_EDGE_PROJECT;\n}\n\n/**\n * The edge's compose project, one per server — read once, when gkm starts,\n * so every step of a run names the same edge.\n */\nexport const EDGE_PROJECT = edgeProject();\n\n/**\n * The external network the edge and every stack's public services share:\n * named after the edge, so a renamed edge has a network of its own.\n */\nexport const EDGE_NETWORK = EDGE_PROJECT;\n\n/** The edge's compose service. */\nexport const EDGE_SERVICE = 'traefik';\n\n/** Inside the edge's container: what it watches, and where certificates are. */\nexport const EDGE_DYNAMIC_DIR = '/etc/gkm-edge/dynamic';\nexport const EDGE_CERTS_DIR = '/etc/gkm-edge/certs';\n\n/** The certificate resolver every deployed route without its own certificate uses. */\nexport const ACME_RESOLVER = 'letsencrypt';\n\n/**\n * The resolver a wildcard site's `*.<domain>` certificate comes from: Let's\n * Encrypt issues a wildcard only over the DNS challenge, which the edge\n * answers by writing an `_acme-challenge` TXT record through Route 53.\n */\nexport const ACME_DNS_RESOLVER = 'letsencrypt-dns';\n\n/**\n * The key the edge writes those records with, inside its container: written\n * by the deploy of a stage with a wildcard site, and allowed nothing but\n * each such stage's `_acme-challenge` record (see `acmeDns.ts`).\n */\nexport const EDGE_AWS_CREDENTIALS = `${EDGE_CERTS_DIR}/aws-credentials`;\n\n/** The internal entrypoint the edge's health check asks; never published. */\nconst PING_PORT = 8082;\n\n/** A stack's service, as the edge — and the stack itself — reach it. */\nexport function edgeAlias(project: string, service: string): string {\n\treturn `${project}-${service}`;\n}\n\n/** A stack's certificate, as the edge's container reads it. */\nexport function edgeCertificatePaths(project: string): {\n\tcertFile: string;\n\tkeyFile: string;\n} {\n\treturn {\n\t\tcertFile: `${EDGE_CERTS_DIR}/${project}.crt`,\n\t\tkeyFile: `${EDGE_CERTS_DIR}/${project}.key`,\n\t};\n}\n\n/** The edge's ports on the host. */\nexport interface EdgePorts {\n\thttps: number;\n\thttp: number;\n}\n\n/**\n * The edge's static configuration: the entrypoints, the redirect, ACME, and\n * the directory it watches. No API and no dashboard — nothing about the edge\n * is reachable but the routes stacks register.\n */\nexport function traefikStatic(ports: EdgePorts): Record<string, unknown> {\n\treturn {\n\t\tglobal: { checkNewVersion: false, sendAnonymousUsage: false },\n\t\tentryPoints: {\n\t\t\tweb: {\n\t\t\t\taddress: ':80',\n\t\t\t\thttp: {\n\t\t\t\t\t// Every plain-HTTP request is sent to HTTPS — but an ACME\n\t\t\t\t\t// HTTP-01 challenge, which Traefik answers before the redirect.\n\t\t\t\t\tredirections: {\n\t\t\t\t\t\tentryPoint: {\n\t\t\t\t\t\t\t// The published port when it is not 443, so the redirect\n\t\t\t\t\t\t\t// lands where the edge actually listens.\n\t\t\t\t\t\t\tto: ports.https === 443 ? 'websecure' : `:${ports.https}`,\n\t\t\t\t\t\t\tscheme: 'https',\n\t\t\t\t\t\t\tpermanent: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twebsecure: { address: ':443' },\n\t\t\tping: { address: `:${PING_PORT}` },\n\t\t},\n\t\tping: { entryPoint: 'ping' },\n\t\tproviders: {\n\t\t\tfile: { directory: EDGE_DYNAMIC_DIR, watch: true },\n\t\t},\n\t\tcertificatesResolvers: {\n\t\t\t[ACME_RESOLVER]: {\n\t\t\t\tacme: {\n\t\t\t\t\tstorage: '/acme/acme.json',\n\t\t\t\t\thttpChallenge: { entryPoint: 'web' },\n\t\t\t\t},\n\t\t\t},\n\t\t\t[ACME_DNS_RESOLVER]: {\n\t\t\t\tacme: {\n\t\t\t\t\tstorage: '/acme/acme-dns.json',\n\t\t\t\t\tdnsChallenge: {\n\t\t\t\t\t\tprovider: 'route53',\n\t\t\t\t\t\t// Asked directly, so the record is seen as soon as Route 53\n\t\t\t\t\t\t// serves it rather than when a cache on the server expires.\n\t\t\t\t\t\tresolvers: ['1.1.1.1:53', '8.8.8.8:53'],\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tlog: { level: 'INFO' },\n\t};\n}\n\n/** The edge's compose document. */\nexport function edgeCompose(options: {\n\tports: EdgePorts;\n\t/**\n\t * The static configuration, as written: handed to the container inline\n\t * (`configs.content`), so nothing is read from a path on whichever machine\n\t * runs the deploy — and its hash recreates the edge when it changes.\n\t */\n\tstaticConfig: string;\n\tlogging: { driver: string; options: Record<string, string> };\n}): Record<string, unknown> {\n\tconst { ports } = options;\n\treturn {\n\t\tname: EDGE_PROJECT,\n\t\tservices: {\n\t\t\t[EDGE_SERVICE]: {\n\t\t\t\timage: TRAEFIK_IMAGE,\n\t\t\t\trestart: 'unless-stopped',\n\t\t\t\tports: [`${ports.https}:443`, `${ports.http}:80`],\n\t\t\t\tconfigs: [{ source: 'traefik', target: '/etc/traefik/traefik.yml' }],\n\t\t\t\tvolumes: [\n\t\t\t\t\t// Volumes on the server, written through the engine (`docker\n\t\t\t\t\t// exec`): each stack's routes and certificate, replaced by a\n\t\t\t\t\t// rename the file provider sees whole.\n\t\t\t\t\t`dynamic:${EDGE_DYNAMIC_DIR}`,\n\t\t\t\t\t`certs:${EDGE_CERTS_DIR}`,\n\t\t\t\t\t'acme:/acme',\n\t\t\t\t],\n\t\t\t\t// Static configuration is read at start: a change to it is a\n\t\t\t\t// change to the service, so `up` recreates the edge.\n\t\t\t\tlabels: {\n\t\t\t\t\t'dev.geekmidas.edge.config': createHash('sha256')\n\t\t\t\t\t\t.update(options.staticConfig)\n\t\t\t\t\t\t.digest('hex')\n\t\t\t\t\t\t.slice(0, 16),\n\t\t\t\t},\n\t\t\t\t// What the DNS challenge writes with: read from the file a stage\n\t\t\t\t// with a wildcard site puts there, and never needed otherwise.\n\t\t\t\tenvironment: {\n\t\t\t\t\tAWS_SHARED_CREDENTIALS_FILE: EDGE_AWS_CREDENTIALS,\n\t\t\t\t\tAWS_REGION: 'us-east-1',\n\t\t\t\t},\n\t\t\t\tnetworks: ['edge'],\n\t\t\t\t// Every stack on the server shares it, so it is sized for the one\n\t\t\t\t// that holds the most sockets — see `EDGE_LIMITS`.\n\t\t\t\t...EDGE_LIMITS,\n\t\t\t\thealthcheck: {\n\t\t\t\t\ttest: ['CMD', 'traefik', 'healthcheck', '--ping'],\n\t\t\t\t\tinterval: '10s',\n\t\t\t\t\ttimeout: '5s',\n\t\t\t\t\tretries: 5,\n\t\t\t\t},\n\t\t\t\tlogging: options.logging,\n\t\t\t},\n\t\t},\n\t\tconfigs: { traefik: { content: composeLiteral(options.staticConfig) } },\n\t\tvolumes: { acme: {}, dynamic: {}, certs: {} },\n\t\tnetworks: { edge: { name: EDGE_NETWORK, external: true } },\n\t};\n}\n\n/** What a stack registers with the edge — its routes, and its certificate. */\nexport interface TraefikStackOptions {\n\tproject: string;\n\t/** ACME, or the stage's own certificate. */\n\ttls: EdgeTls;\n\t/**\n\t * The stack's token, on which a service of the stack keeps gkm's client\n\t * address through the edge — see `clientIpRule`.\n\t */\n\tedgeToken?: string;\n}\n\n/** A stack's dynamic configuration, as an object. */\nexport function traefikDynamic(\n\troutes: readonly EdgeRoute[],\n\toptions: TraefikStackOptions,\n): Record<string, unknown> {\n\tconst { project, tls, edgeToken } = options;\n\tconst name = (route: EdgeRoute, suffix?: string) =>\n\t\t`${project}-${route.name}${suffix ? `-${suffix}` : ''}`;\n\tconst url = ({ service, port }: Upstream) =>\n\t\t`http://${edgeAlias(project, service)}:${port}`;\n\n\tconst routers: Record<string, unknown> = {};\n\tconst services: Record<string, unknown> = {};\n\tconst middlewares: Record<string, unknown> = {};\n\n\t// gkm's own header, which only a service of this stack may send — the\n\t// auth server rate-limits by the client address it carries — removed from\n\t// every request that arrives from outside. An empty value is Traefik's\n\t// way of removing a request header. A request carrying the stack's token\n\t// is one of its own services calling a sibling through the edge: it is\n\t// matched by a router of its own, below, whose chain keeps the header.\n\tconst strip = `${project}-strip-gkm-headers`;\n\tif (routes.length > 0) {\n\t\tmiddlewares[strip] = {\n\t\t\theaders: { customRequestHeaders: { [CLIENT_IP_HEADER]: '' } },\n\t\t};\n\t}\n\n\tfor (const route of routes) {\n\t\tconst chain: string[] = [strip];\n\t\t// The client-address limits, which the stack's own services — all\n\t\t// behind one address — are not counted against.\n\t\tconst limited = new Set<string>();\n\t\tif (route.allow) {\n\t\t\t// The peer Traefik sees — never X-Forwarded-For, which a client\n\t\t\t// could set. Everything else gets 403.\n\t\t\tmiddlewares[name(route, 'allow')] = {\n\t\t\t\tipAllowList: { sourceRange: [...route.allow] },\n\t\t\t};\n\t\t\tchain.push(name(route, 'allow'));\n\t\t}\n\t\tif (route.auth) {\n\t\t\t// The stage's login, asked for before anything reaches the\n\t\t\t// upstream. The service's health check goes to the upstream\n\t\t\t// directly, so it is never asked.\n\t\t\tmiddlewares[name(route, 'auth')] = {\n\t\t\t\tbasicAuth: { users: [`${route.auth.user}:${route.auth.hash}`] },\n\t\t\t};\n\t\t\tchain.push(name(route, 'auth'));\n\t\t}\n\t\t// Per client address, as the edge — the first hop — sees it: an\n\t\t// upgrade past either is answered 429 before it reaches a replica.\n\t\t// An upgraded request stays in flight while its socket is open, so\n\t\t// `inFlightReq` counts open sockets.\n\t\tif (route.limits?.handshakesPerMinute) {\n\t\t\tconst perMinute = route.limits.handshakesPerMinute;\n\t\t\tmiddlewares[name(route, 'rate')] = {\n\t\t\t\trateLimit: { average: perMinute, period: '1m', burst: perMinute },\n\t\t\t};\n\t\t\tchain.push(name(route, 'rate'));\n\t\t\tlimited.add(name(route, 'rate'));\n\t\t}\n\t\tif (route.limits?.connectionsPerIp) {\n\t\t\tmiddlewares[name(route, 'in-flight')] = {\n\t\t\t\tinFlightReq: { amount: route.limits.connectionsPerIp },\n\t\t\t};\n\t\t\tchain.push(name(route, 'in-flight'));\n\t\t\tlimited.add(name(route, 'in-flight'));\n\t\t}\n\t\tif (route.prefix) {\n\t\t\tmiddlewares[name(route, 'prefix')] = {\n\t\t\t\taddPrefix: { prefix: route.prefix },\n\t\t\t};\n\t\t\tchain.push(name(route, 'prefix'));\n\t\t}\n\n\t\tassertRouteRenderable(route);\n\t\t// Only the paths it names, where it names some: a request for any\n\t\t// other matches no router, and the edge answers it 404 itself. So\n\t\t// does one without the header a CDN sends, where it requires one.\n\t\tconst allowed = [\n\t\t\t...(route.paths ?? []).map((path) => `Path(\\`${path}\\`)`),\n\t\t\t...(route.prefixes ?? []).map((prefix) => `PathPrefix(\\`${prefix}\\`)`),\n\t\t];\n\t\tconst paths = allowed.length ? ` && (${allowed.join(' || ')})` : '';\n\t\tconst header = route.requireHeader\n\t\t\t? ` && Header(\\`${route.requireHeader.name}\\`, \\`${route.requireHeader.value}\\`)`\n\t\t\t: '';\n\n\t\tconst certificate = (): Record<string, unknown> =>\n\t\t\troute.wildcard?.tls.kind === 'dns'\n\t\t\t\t? {\n\t\t\t\t\t\tcertResolver: ACME_DNS_RESOLVER,\n\t\t\t\t\t\tdomains: [{ main: `*.${route.wildcard.domain}` }],\n\t\t\t\t\t}\n\t\t\t\t: tls.kind === 'acme'\n\t\t\t\t\t? { certResolver: ACME_RESOLVER }\n\t\t\t\t\t: {};\n\n\t\t// Each handler: a router of its own on the same host, ahead of the\n\t\t// route's, to a service of its own.\n\t\tfor (const handler of route.handlers ?? []) {\n\t\t\tconst handlerName = name(route, handler.name);\n\t\t\trouters[handlerName] = {\n\t\t\t\t// Every host of the route, as its own router's rule has them.\n\t\t\t\trule: `${hostRule(route)} && (${handler.prefixes\n\t\t\t\t\t.map((prefix) => `PathPrefix(\\`${prefix}\\`)`)\n\t\t\t\t\t.join(' || ')})`,\n\t\t\t\t// Above the route's own router, whatever the rules' lengths.\n\t\t\t\tpriority: 10_000,\n\t\t\t\tentryPoints: ['websecure'],\n\t\t\t\tservice: handlerName,\n\t\t\t\tmiddlewares: [strip],\n\t\t\t\ttls: certificate(),\n\t\t\t};\n\t\t\tservices[handlerName] = {\n\t\t\t\tloadBalancer: {\n\t\t\t\t\tservers: handler.upstreams.map((upstream) => ({\n\t\t\t\t\t\turl: url(upstream),\n\t\t\t\t\t})),\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\n\t\t// Each redirect host: a router of its own, answering a permanent\n\t\t// redirect to the canonical host with the path and query it was asked\n\t\t// for. Nothing is behind it — Traefik's `noop` service never answers,\n\t\t// because the middleware always does first.\n\t\tif (route.redirects?.hosts.length) {\n\t\t\tconst redirect = name(route, 'redirect');\n\t\t\tmiddlewares[redirect] = {\n\t\t\t\tredirectRegex: {\n\t\t\t\t\tregex: '^https?://[^/]+(.*)$',\n\t\t\t\t\treplacement: `${route.redirects.to}$\\{1}`,\n\t\t\t\t\tpermanent: true,\n\t\t\t\t},\n\t\t\t};\n\t\t\troute.redirects.hosts.forEach((host, index) => {\n\t\t\t\trouters[name(route, `redirect-${index + 1}`)] = {\n\t\t\t\t\trule: `Host(\\`${host}\\`)`,\n\t\t\t\t\tentryPoints: ['websecure'],\n\t\t\t\t\tservice: 'noop@internal',\n\t\t\t\t\tmiddlewares: [redirect],\n\t\t\t\t\ttls: certificate(),\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\n\t\tconst rule = `${hostRule(route)}${paths}${header}`;\n\t\trouters[name(route)] = {\n\t\t\trule,\n\t\t\t// Below every named host's router, whatever the rules' lengths: a\n\t\t\t// wildcard site gets only the labels nothing else answers.\n\t\t\t...(route.wildcard ? { priority: 1 } : {}),\n\t\t\tentryPoints: ['websecure'],\n\t\t\tservice: name(route),\n\t\t\tmiddlewares: chain,\n\t\t\ttls: certificate(),\n\t\t};\n\t\t// The stack's own services, proven by its token: the same route, to\n\t\t// the same service, keeping gkm's header. Its longer rule puts it ahead\n\t\t// of the route's own; a wildcard's, just above that one's.\n\t\tif (edgeToken && !route.prefix) {\n\t\t\tconst trusted = chain.slice(1).filter((m) => !limited.has(m));\n\t\t\trouters[name(route, 'stack')] = {\n\t\t\t\trule: `${rule} && Header(\\`${EDGE_TOKEN_HEADER}\\`, \\`${edgeToken}\\`)`,\n\t\t\t\t...(route.wildcard ? { priority: 2 } : {}),\n\t\t\t\tentryPoints: ['websecure'],\n\t\t\t\tservice: name(route),\n\t\t\t\t...(trusted.length > 0 ? { middlewares: trusted } : {}),\n\t\t\t\ttls: certificate(),\n\t\t\t};\n\t\t}\n\n\t\tservices[name(route)] = {\n\t\t\tloadBalancer: {\n\t\t\t\tservers: route.upstreams.map((upstream) => ({ url: url(upstream) })),\n\t\t\t\t// A bucket is routed and signed on the Host header, so MinIO is\n\t\t\t\t// sent its own; an app is sent the one the caller used, which is\n\t\t\t\t// what it builds redirects, cookies and links on.\n\t\t\t\t...(route.prefix ? { passHostHeader: false } : {}),\n\t\t\t\t...(route.streaming\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t// Never buffer: each chunk of a streamed response is\n\t\t\t\t\t\t\t// flushed to the client as it is written.\n\t\t\t\t\t\t\tresponseForwarding: { flushInterval: '-1ms' },\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(route.health\n\t\t\t\t\t? {\n\t\t\t\t\t\t\thealthCheck: {\n\t\t\t\t\t\t\t\tpath: route.health,\n\t\t\t\t\t\t\t\tinterval: '5s',\n\t\t\t\t\t\t\t\ttimeout: '3s',\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t};\n\t}\n\n\treturn {\n\t\thttp: {\n\t\t\trouters,\n\t\t\tservices,\n\t\t\t...(Object.keys(middlewares).length > 0 ? { middlewares } : {}),\n\t\t},\n\t\t...(tls.kind === 'files'\n\t\t\t? {\n\t\t\t\t\ttls: {\n\t\t\t\t\t\tcertificates: [{ certFile: tls.certFile, keyFile: tls.keyFile }],\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n\n/**\n * The hosts a route answers, as a Traefik rule: its own and its aliases', or\n * — for a wildcard site — exactly one label under its domain, but the ones\n * it never takes. One label, as a wildcard certificate covers: a stage at\n * `staging.example.com` is never reached through `example.com`'s wildcard.\n *\n * Several hosts are parenthesised, `(Host(a) || Host(b))`, so whatever is\n * joined to the rule with `&&` — the path allowlist, a required header, the\n * stack's token — holds on every one of them. One router's hosts are one\n * certificate's names under ACME.\n */\nfunction hostRule(route: EdgeRoute): string {\n\tif (!route.wildcard) {\n\t\tconst hosts = [route.host, ...(route.aliases ?? [])].map(\n\t\t\t(host) => `Host(\\`${host}\\`)`,\n\t\t);\n\t\treturn hosts.length === 1 ? hosts[0]! : `(${hosts.join(' || ')})`;\n\t}\n\tconst { domain, except } = route.wildcard;\n\tconst pattern = `^[a-z0-9-]+\\\\.${domain.replace(/\\./g, '\\\\.')}$`;\n\treturn [\n\t\t`HostRegexp(\\`${pattern}\\`)`,\n\t\t...except.map((label) => `!Host(\\`${label}.${domain}\\`)`),\n\t].join(' && ');\n}\n\n/**\n * A host a stack routes on the shared edge: one name, or — for a wildcard\n * site — every one label under a domain but the ones it never takes.\n */\nexport type EdgeClaim =\n\t| { host: string }\n\t| { wildcard: string; except: readonly string[] };\n\n/**\n * What a stack's routes claim on the edge, from the route model: one claim\n * per host, each route's aliases and redirects included.\n */\nexport function edgeClaims(routes: readonly EdgeRoute[]): EdgeClaim[] {\n\treturn routes.flatMap((route): EdgeClaim[] =>\n\t\troute.wildcard\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\twildcard: route.wildcard.domain.toLowerCase(),\n\t\t\t\t\t\texcept: [...route.wildcard.except],\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: routeHosts(route).map((host) => ({ host: host.toLowerCase() })),\n\t);\n}\n\n/**\n * The comment line a stack's file carries its claims on: a comment, because\n * Traefik's file provider refuses a whole file over a key it does not know,\n * and gkm reads it back rather than taking the routers' rules apart.\n */\nconst CLAIMS_PREFIX = '# gkm-claims: ';\n\n/**\n * The hosts a stack's file on the edge claims: from its claims line, or — a\n * file written before gkm wrote one — from its routers' rules, in the shapes\n * `traefikDynamic` renders them.\n */\nexport function readEdgeClaims(file: string): EdgeClaim[] {\n\tfor (const line of file.split('\\n')) {\n\t\tif (!line.startsWith(CLAIMS_PREFIX)) continue;\n\t\ttry {\n\t\t\tconst claims = JSON.parse(line.slice(CLAIMS_PREFIX.length));\n\t\t\tif (Array.isArray(claims)) return claims.filter(isClaim);\n\t\t} catch {\n\t\t\t// A line that is not gkm's: the rules below still say.\n\t\t}\n\t}\n\tlet document: unknown;\n\ttry {\n\t\tdocument = parse(file);\n\t} catch {\n\t\treturn [];\n\t}\n\tconst routers = (document as { http?: { routers?: unknown } } | null)?.http\n\t\t?.routers;\n\tif (!routers || typeof routers !== 'object') return [];\n\tconst claims: EdgeClaim[] = [];\n\tfor (const router of Object.values(routers)) {\n\t\tconst rule = (router as { rule?: unknown } | null)?.rule;\n\t\tif (typeof rule === 'string') claims.push(...ruleClaims(rule));\n\t}\n\treturn claims;\n}\n\nfunction isClaim(value: unknown): value is EdgeClaim {\n\tif (!value || typeof value !== 'object') return false;\n\tconst claim = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof claim.host === 'string' ||\n\t\t(typeof claim.wildcard === 'string' && Array.isArray(claim.except))\n\t);\n}\n\n/**\n * The hosts a rule matches: each `Host(\\`a\\`)` not negated, and a\n * `HostRegexp` of a wildcard site — one label under a domain — with the\n * `!Host` labels it leaves out.\n */\nfunction ruleClaims(rule: string): EdgeClaim[] {\n\tconst negated = [...rule.matchAll(/!\\s*Host\\(`([^`]+)`\\)/g)].map((match) =>\n\t\tmatch[1]!.toLowerCase(),\n\t);\n\tconst wildcard = /HostRegexp\\(`\\^\\[a-z0-9-\\]\\+\\\\\\.(.+)\\$`\\)/.exec(rule);\n\tif (wildcard) {\n\t\tconst domain = wildcard[1]!.replace(/\\\\\\./g, '.').toLowerCase();\n\t\tconst suffix = `.${domain}`;\n\t\treturn [\n\t\t\t{\n\t\t\t\twildcard: domain,\n\t\t\t\texcept: negated\n\t\t\t\t\t.filter((host) => host.endsWith(suffix))\n\t\t\t\t\t.map((host) => host.slice(0, -suffix.length)),\n\t\t\t},\n\t\t];\n\t}\n\treturn [...rule.matchAll(/(?<![!\\w])Host\\(`([^`]+)`\\)/g)].map((match) => ({\n\t\thost: match[1]!.toLowerCase(),\n\t}));\n}\n\n/**\n * Where two claims meet, as a host to name — or undefined where they never\n * do. A wildcard takes one label under its domain, so it meets a name one\n * label under it that it does not leave out, and another wildcard on the\n * same domain.\n */\nexport function claimsOverlap(a: EdgeClaim, b: EdgeClaim): string | undefined {\n\tif ('host' in a && 'host' in b) {\n\t\treturn a.host === b.host ? a.host : undefined;\n\t}\n\tif ('wildcard' in a && 'wildcard' in b) {\n\t\treturn a.wildcard === b.wildcard ? `*.${a.wildcard}` : undefined;\n\t}\n\tconst [name, wildcard] = ('host' in a ? [a, b] : [b, a]) as [\n\t\t{ host: string },\n\t\t{ wildcard: string; except: readonly string[] },\n\t];\n\tconst suffix = `.${wildcard.wildcard}`;\n\tif (!name.host.endsWith(suffix)) return undefined;\n\tconst label = name.host.slice(0, -suffix.length);\n\tif (!/^[a-z0-9-]+$/.test(label) || wildcard.except.includes(label)) {\n\t\treturn undefined;\n\t}\n\treturn name.host;\n}\n\n/** A stack's dynamic configuration file, as written to the edge's directory. */\nexport function traefikDynamicFile(\n\troutes: readonly EdgeRoute[],\n\toptions: TraefikStackOptions,\n): string {\n\treturn `# Generated by gkm compose for ${options.project} — do not edit.\n# The shared edge (${EDGE_PROJECT}) reads every file in this directory; this\n# one is removed by gkm compose --down. The hosts it routes, which no other\n# stack on the edge may route:\n${CLAIMS_PREFIX}${JSON.stringify(edgeClaims(routes))}\n${yaml(traefikDynamic(routes, options))}`;\n}\n\n/** The edge's static configuration file. */\nexport function traefikStaticFile(ports: EdgePorts): string {\n\treturn `# Generated by gkm compose — the server's shared edge. Do not edit.\n${yaml(traefikStatic(ports))}`;\n}\n\n/** The edge's compose file. */\nexport function edgeComposeFile(\n\toptions: Parameters<typeof edgeCompose>[0],\n): string {\n\treturn `# Generated by gkm compose — the server's shared edge. Do not edit.\n#\n# Started by the first stack that runs with proxy: 'traefik', and left\n# running by gkm compose --down. Stop it, once nothing uses it, with:\n#\n# docker compose -p ${EDGE_PROJECT} down\n${yaml(edgeCompose(options))}`;\n}\n\nfunction yaml(value: unknown): string {\n\treturn stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,gBAAgB;;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AAM,SAAS,IAAI,SAAS;CAC5B,IAAI,CAAC,KAAK,KAAK,SAAS,MAAM,GAAG,OAAO,KAAA;CACxC,MAAM,QAAQ,KAAK,KAAK,MAAM,GAAG,CAAC,OAAO,MAAM;CAC/C,IAAI,CAAC,eAAe,KAAK,KAAK,KAAK,SAAS,OAAO,SAAS,KAAK,GAChE;CAED,OAAO,KAAK;AACb;;AAGA,SAAgB,mBACf,QACA,SACS;CACT,OAAO,kCAAkC,QAAQ,QAAQ;qBACrC,aAAa;;;EAGhC,gBAAgB,KAAK,UAAU,WAAW,MAAM,CAAC,EAAE;EACnD,KAAK,eAAe,QAAQ,OAAO,CAAC;AACtC;;AAGA,SAAgB,kBAAkB,OAA0B;CAC3D,OAAO;EACN,KAAK,cAAc,KAAK,CAAC;AAC3B;;AAGA,SAAgB,gBACf,SACS;CACT,OAAO;;;;;wBAKgB,aAAa;EACnC,KAAK,YAAY,OAAO,CAAC;AAC3B;AAEA,SAAS,KAAK,OAAwB;CACrC,OAAO,UAAU,OAAO;EAAE,WAAW;EAAG,uBAAuB;CAAM,CAAC;AACvE"}
@@ -0,0 +1,49 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/routes/index.ts
3
+ /**
4
+ * Every host a route answers on — its own, its aliases and its redirects —
5
+ * in that order: what DNS, certificates and the edge's claims cover.
6
+ */
7
+ function routeHosts(route) {
8
+ return [
9
+ route.host,
10
+ ...route.aliases ?? [],
11
+ ...route.redirects?.hosts ?? []
12
+ ];
13
+ }
14
+ /** A route with handlers and a check that would have to hold for each of them. */
15
+ var EdgeRouteConflict = class extends Error {
16
+ route;
17
+ constructor(route) {
18
+ super(`The edge route '${route}' sends some paths to other upstreams and also restricts who or what it answers. The two are not combined: give the restricted paths a host of their own.`);
19
+ this.route = route;
20
+ this.name = "EdgeRouteConflict";
21
+ }
22
+ };
23
+ /** @throws {EdgeRouteConflict} */
24
+ function assertRouteRenderable(route) {
25
+ if (route.handlers?.length && (route.allow || route.paths || route.prefixes || route.requireHeader)) throw new EdgeRouteConflict(route.name);
26
+ }
27
+ /** File descriptors a process holding sockets may open. */
28
+ const NOFILE = {
29
+ soft: 1048576,
30
+ hard: 1048576
31
+ };
32
+ /**
33
+ * What the edge runs with: a descriptor per socket, twice — the client's and
34
+ * the upstream's — and every local port for those upstream connections. One
35
+ * edge address to one upstream has only the ephemeral range to open
36
+ * connections from, ~28k by Linux's default; widened, ~64k per replica.
37
+ */
38
+ const EDGE_LIMITS = {
39
+ sysctls: { "net.ipv4.ip_local_port_range": "1024 65535" },
40
+ ulimits: { nofile: NOFILE }
41
+ };
42
+ //#endregion
43
+ exports.EDGE_LIMITS = EDGE_LIMITS;
44
+ exports.EdgeRouteConflict = EdgeRouteConflict;
45
+ exports.NOFILE = NOFILE;
46
+ exports.assertRouteRenderable = assertRouteRenderable;
47
+ exports.routeHosts = routeHosts;
48
+
49
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/routes/index.ts"],"sourcesContent":["/**\n * What a stack's edge serves, as data: one route per public host, and the\n * service behind it. Computed once by the stack, then rendered by whichever\n * proxy the stage runs — a Caddyfile for the stack's own Caddy, or a dynamic\n * config file for the server's shared Traefik — so the two never drift.\n *\n * Pure.\n */\n\n/** A service of the stack that a route sends to. */\nexport interface Upstream {\n\t/** Its compose service name — `api`, `minio`. */\n\tservice: string;\n\t/** The port it listens on, inside the network. */\n\tport: number;\n}\n\n/** One public host and what answers it. */\nexport interface EdgeRoute {\n\t/**\n\t * Its name within the stack — unique there, and what a renderer names\n\t * its routers and middlewares after: `api`, `files-uploads`.\n\t */\n\tname: string;\n\t/** e.g. `api.example.com` — the canonical host, its `<ID>_URL`'s. */\n\thost: string;\n\t/**\n\t * More hosts answered exactly as `host` is — a construct's `aliases`:\n\t * every check, handler and upstream of the route holds on each of them.\n\t */\n\taliases?: readonly string[];\n\t/**\n\t * Hosts answered with a permanent redirect to `to`, the canonical origin\n\t * (`https://example.com`, with the edge's port where it is not 443), path\n\t * and query kept — a site's `redirects`. Nothing is proxied for them.\n\t */\n\tredirects?: { hosts: readonly string[]; to: string };\n\t/**\n\t * Where requests go. One today; a release that swaps containers without\n\t * downtime routes to the old and the new while it does.\n\t */\n\tupstreams: readonly Upstream[];\n\t/**\n\t * Never buffer the response: a streamed one — server-sent events, a\n\t * Next.js RSC payload — reaches the client as each chunk is written.\n\t */\n\tstreaming: boolean;\n\t/**\n\t * A path prefix added before the request is sent, with the upstream's own\n\t * address as `Host`: a bucket, served at a host of its own, is a prefix\n\t * on MinIO, which routes and signs on the Host header.\n\t */\n\tprefix?: string;\n\t/**\n\t * The client addresses (IPs or CIDRs) it answers; every other is refused\n\t * with 403, before the request reaches the upstream. Absent, it answers\n\t * everyone. Matched against the peer the proxy sees, never a header a\n\t * client could set.\n\t */\n\tallow?: readonly string[];\n\t/**\n\t * The only paths it answers, matched exactly; every other is refused at\n\t * the edge, before the request reaches the upstream. Absent, it answers\n\t * every path. A worker is reached only on the routes SNS pushes to.\n\t */\n\tpaths?: readonly string[];\n\t/**\n\t * Path prefixes it answers besides `paths` — `/i/` admits everything\n\t * under it. Together they are the whole allowlist; absent both, it\n\t * answers every path. A processor unit's own host is reached only on its\n\t * processors' prefixes.\n\t */\n\tprefixes?: readonly string[];\n\t/**\n\t * A header every request must carry, with exactly this value; any other\n\t * is refused at the edge. What a CDN adds to reach its origin, so the\n\t * origin's public host cannot be called around the CDN.\n\t */\n\trequireHeader?: { name: string; value: string };\n\t/**\n\t * Path prefixes on this host sent to another upstream, ahead of the\n\t * route's own: a file server's processor patterns, to its processor unit,\n\t * while every other path is the bucket. Served at the path asked for —\n\t * no `prefix` — and never combined with `allow`, `paths`, `prefixes` or\n\t * `requireHeader`, which would have to hold for every handler too.\n\t */\n\thandlers?: readonly EdgeHandler[];\n\t/**\n\t * The login every request must carry — HTTP basic auth, asked for by the\n\t * edge before anything reaches the upstream. Absent, it asks for none.\n\t * The password's bcrypt hash, never the password.\n\t */\n\tauth?: { user: string; hash: string };\n\t/**\n\t * What one client address may ask of it — a WebSocket surface's\n\t * handshakes a minute and open sockets — refused with 429 at the edge.\n\t * Rendered for Traefik (`rateLimit`, `inFlightReq`); Caddy ships no rate\n\t * limiter, so behind it the surface's own count is what holds.\n\t */\n\tlimits?: { handshakesPerMinute?: number; connectionsPerIp?: number };\n\t/** The path the upstream answers its health on — `/health`, `/`. */\n\thealth?: string;\n\t/**\n\t * For a wildcard site's route, whose `host` is `*.<domain>`: every one\n\t * label under the domain that no other route answers, and how its\n\t * certificate is had. Named hosts always win over it.\n\t */\n\twildcard?: EdgeWildcard;\n}\n\n/**\n * Every host a route answers on — its own, its aliases and its redirects —\n * in that order: what DNS, certificates and the edge's claims cover.\n */\nexport function routeHosts(route: EdgeRoute): string[] {\n\treturn [\n\t\troute.host,\n\t\t...(route.aliases ?? []),\n\t\t...(route.redirects?.hosts ?? []),\n\t];\n}\n\n/** How a `*.<domain>` route is matched and certified. */\nexport interface EdgeWildcard {\n\t/** The domain under the `*` — `example.com`. */\n\tdomain: string;\n\t/**\n\t * Labels under the domain that never reach it, although no route of this\n\t * stack answers them: the protected subdomains (`www`, `mail`), and a\n\t * stage whose domain sits under this one's (`staging`).\n\t */\n\texcept: readonly string[];\n\t/**\n\t * Where its certificate comes from:\n\t * - `stage`: the stage's own (`deploy.compose.tls`), a wildcard one;\n\t * - `dns`: one `*.<domain>` certificate from Let's Encrypt over the DNS\n\t * challenge, which the shared Traefik edge answers through Route 53;\n\t * - `on-demand`: one per host, as Caddy is first asked for it, once the\n\t * site's `hosts` route — `ask`, on the stack's network — answers 200.\n\t */\n\ttls: { kind: 'stage' } | { kind: 'dns' } | { kind: 'on-demand'; ask: string };\n}\n\n/** Some of a route's paths, answered by another upstream. */\nexport interface EdgeHandler {\n\t/** Unique within the route: what a renderer names its router after. */\n\tname: string;\n\t/** e.g. `/i/` — everything under it. */\n\tprefixes: readonly string[];\n\tupstreams: readonly Upstream[];\n}\n\n/** A route with handlers and a check that would have to hold for each of them. */\nexport class EdgeRouteConflict extends Error {\n\tconstructor(readonly route: string) {\n\t\tsuper(\n\t\t\t`The edge route '${route}' sends some paths to other upstreams and also ` +\n\t\t\t\t`restricts who or what it answers. The two are not combined: give the ` +\n\t\t\t\t`restricted paths a host of their own.`,\n\t\t);\n\t\tthis.name = 'EdgeRouteConflict';\n\t}\n}\n\n/** @throws {EdgeRouteConflict} */\nexport function assertRouteRenderable(route: EdgeRoute): void {\n\tif (\n\t\troute.handlers?.length &&\n\t\t(route.allow || route.paths || route.prefixes || route.requireHeader)\n\t) {\n\t\tthrow new EdgeRouteConflict(route.name);\n\t}\n}\n\n/** Where a stack's certificates come from. */\nexport type EdgeTls =\n\t/** A deployed stage: Let's Encrypt, over HTTP-01, on first request. */\n\t| { kind: 'acme' }\n\t/**\n\t * A certificate and key, as the proxy's container reads them: a deployed\n\t * stage's own (`deploy.compose.tls`), or — on the local stage — the one\n\t * gkm's local authority issued (`trust/authority.ts`).\n\t */\n\t| { kind: 'files'; certFile: string; keyFile: string };\n\n/** File descriptors a process holding sockets may open. */\nexport const NOFILE = { soft: 1_048_576, hard: 1_048_576 };\n\n/**\n * What the edge runs with: a descriptor per socket, twice — the client's and\n * the upstream's — and every local port for those upstream connections. One\n * edge address to one upstream has only the ephemeral range to open\n * connections from, ~28k by Linux's default; widened, ~64k per replica.\n */\nexport const EDGE_LIMITS: {\n\tsysctls: Record<string, string>;\n\tulimits: Record<string, { soft: number; hard: number }>;\n} = {\n\tsysctls: { 'net.ipv4.ip_local_port_range': '1024 65535' },\n\tulimits: { nofile: NOFILE },\n};\n\n/** The proxies a stack can be served by — `deploy.compose.proxy`. */\nexport type ComposeProxy = 'caddy' | 'traefik';\n"],"mappings":";;;;;;AAkHA,SAAgB,WAAW,OAA4B;CACtD,OAAO;EACN,MAAM;EACN,GAAI,MAAM,WAAW,CAAC;EACtB,GAAI,MAAM,WAAW,SAAS,CAAC;CAChC;AACD;;AAiCA,IAAa,oBAAb,cAAuC,MAAM;CACvB;CAArB,YAAY,OAAwB;EACnC,MACC,mBAAmB,MAAM,0JAG1B;EALoB,KAAA,QAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,sBAAsB,OAAwB;CAC7D,IACC,MAAM,UAAU,WACf,MAAM,SAAS,MAAM,SAAS,MAAM,YAAY,MAAM,gBAEvD,MAAM,IAAI,kBAAkB,MAAM,IAAI;AAExC;;AAcA,MAAa,SAAS;CAAE,MAAM;CAAW,MAAM;AAAU;;;;;;;AAQzD,MAAa,cAGT;CACH,SAAS,EAAE,gCAAgC,aAAa;CACxD,SAAS,EAAE,QAAQ,OAAO;AAC3B"}