@geekmidas/edge 10.0.0-alpha.184 → 10.0.0-alpha.185
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/proxy/caddy.cjs +6 -4
- package/dist/proxy/caddy.cjs.map +1 -1
- package/dist/proxy/caddy.d.cts.map +1 -1
- package/dist/proxy/caddy.d.mts.map +1 -1
- package/dist/proxy/caddy.mjs +7 -5
- package/dist/proxy/caddy.mjs.map +1 -1
- package/dist/proxy/traefik.cjs +5 -2
- package/dist/proxy/traefik.cjs.map +1 -1
- package/dist/proxy/traefik.d.cts.map +1 -1
- package/dist/proxy/traefik.d.mts.map +1 -1
- package/dist/proxy/traefik.mjs +6 -3
- package/dist/proxy/traefik.mjs.map +1 -1
- package/dist/routes/index.cjs +12 -0
- package/dist/routes/index.cjs.map +1 -1
- package/dist/routes/index.d.cts +42 -1
- package/dist/routes/index.d.cts.map +1 -1
- package/dist/routes/index.d.mts +42 -1
- package/dist/routes/index.d.mts.map +1 -1
- package/dist/routes/index.mjs +11 -1
- package/dist/routes/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/proxy/caddy.cjs
CHANGED
|
@@ -17,9 +17,9 @@ let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
|
17
17
|
*/
|
|
18
18
|
/** Where Caddy reads a stage's own certificate, inside its container. */
|
|
19
19
|
const CADDY_TLS_DIR = "/etc/caddy/tls";
|
|
20
|
-
/** An upstream on the stack's own network
|
|
21
|
-
function address(
|
|
22
|
-
return
|
|
20
|
+
/** An upstream on the stack's own network — its service name — or on the host. */
|
|
21
|
+
function address(upstream) {
|
|
22
|
+
return require_routes_index.upstreamAddress(upstream);
|
|
23
23
|
}
|
|
24
24
|
/** The Caddyfile for a stack's edge. */
|
|
25
25
|
function edgeCaddyfile(routes, options) {
|
|
@@ -77,7 +77,9 @@ function siteBlock(route, edgeToken, certificate) {
|
|
|
77
77
|
# Answered by another service: ${handler.name}.
|
|
78
78
|
@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(" ")}
|
|
79
79
|
handle @handler${index} {
|
|
80
|
-
reverse_proxy ${handler.upstreams.map(address).join(" ")}
|
|
80
|
+
reverse_proxy ${handler.upstreams.map(address).join(" ")}${handler.under ? ` {
|
|
81
|
+
rewrite ${handler.under}{uri}
|
|
82
|
+
}` : ""}
|
|
81
83
|
}
|
|
82
84
|
`).join("")}
|
|
83
85
|
handle {${proxy.replace(/\n/g, "\n ")}
|
package/dist/proxy/caddy.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caddy.cjs","names":["CLIENT_IP_HEADER","EDGE_TOKEN_HEADER"],"sources":["../../src/proxy/caddy.ts"],"sourcesContent":["/**\n * The stack's own edge, rendered for Caddy: one site block per route.\n *\n * Deployed, each host is the stage's real domain and Caddy gets it a\n * certificate from Let's Encrypt on first request — the same automatic HTTPS\n * it does anywhere, with nothing to configure but the name — or serves the\n * stage's own certificate (`deploy.compose.tls`). Locally the hosts are\n * `*.localhost` and the certificate is the one gkm's local authority issued,\n * as the `gkm dev` edge's is, so a local stack is `https://` like a deployed\n * one.\n *\n * Pure: the routes are data (`@geekmidas/edge/routes`), and rendering them is one string.\n */\n\nimport { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from '@geekmidas/manifest';\nimport {\n\tassertRouteRenderable,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype Upstream,\n} from '../routes';\n\n/** Where Caddy reads a stage's own certificate, inside its container. */\nexport const CADDY_TLS_DIR = '/etc/caddy/tls';\n\nexport interface CaddyfileOptions {\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\t/** Where ACME sends expiry notices, when someone wants them. */\n\temail?: string;\n\t/**\n\t * `false` on the local stage: plain HTTP is not sent to HTTPS, whose\n\t * published port there may not be 443.\n\t */\n\tredirects?: boolean;\n}\n\n/** An upstream on the stack's own network: its service name. */\nfunction address({ service, port }: Upstream): string {\n\treturn `${service}:${port}`;\n}\n\n/** The Caddyfile for a stack's edge. */\nexport function edgeCaddyfile(\n\troutes: readonly EdgeRoute[],\n\toptions: CaddyfileOptions,\n): string {\n\tconst { tls } = options;\n\t// A wildcard site certified host by host: Caddy asks its `hosts` route\n\t// before it gets a certificate for one, so a name no tenant has is never\n\t// sent to Let's Encrypt.\n\tconst ask = routes.find((route) => route.wildcard?.tls.kind === 'on-demand')\n\t\t?.wildcard?.tls;\n\tconst onDemand =\n\t\task?.kind === 'on-demand'\n\t\t\t? `\n\ton_demand_tls {\n\t\task ${ask.ask}\n\t}`\n\t\t\t: '';\n\tconst settings = `${options.email ? `\\n\\temail ${options.email}` : ''}${\n\t\toptions.redirects === false ? '\\n\\tauto_https disable_redirects' : ''\n\t}${onDemand}`;\n\tconst global = settings ? `{${settings}\\n}` : '';\n\n\tconst certificate =\n\t\ttls.kind === 'files'\n\t\t\t? `\n\ttls ${tls.certFile} ${tls.keyFile}\n`\n\t\t\t: '';\n\n\t// The wildcard site last: Caddy prefers a named host to `*.<domain>`\n\t// wherever the blocks are, and reading it last says the same.\n\tconst blocks = [\n\t\t...routes.filter((route) => !route.wildcard),\n\t\t...routes.filter((route) => route.wildcard),\n\t].map((route) =>\n\t\tsiteBlock(\n\t\t\troute,\n\t\t\toptions.edgeToken,\n\t\t\troute.wildcard?.tls.kind === 'on-demand'\n\t\t\t\t? `\n\ttls {\n\t\ton_demand\n\t}\n`\n\t\t\t\t: certificate,\n\t\t),\n\t);\n\n\t// No blank line under the header: `caddy fmt` wants the first block there.\n\treturn `${HEADER}${global ? `${global}\\n\\n` : ''}${blocks.join('\\n\\n')}\\n`;\n}\n\n/** One route's site block. */\nfunction siteBlock(\n\troute: EdgeRoute,\n\tedgeToken: string | undefined,\n\tcertificate: string,\n): string {\n\tassertRouteRenderable(route);\n\tconst { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;\n\tconst allowed = [\n\t\t...(paths ?? []),\n\t\t...(prefixes ?? []).map((prefix) => `${prefix}*`),\n\t];\n\n\tconst except = route.wildcard?.except ?? [];\n\tconst checks = `${\n\t\texcept.length\n\t\t\t? `\n\t# Labels no tenant may take, although nothing in this stack answers them.\n\t@protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(' ')}\n\trespond @protected 404\n`\n\t\t\t: ''\n\t}${\n\t\tallow\n\t\t\t? `\n\t# Only these addresses — the peer Caddy sees, never a header a client\n\t# could set. Everything else is refused before it reaches the upstream.\n\t@denied not remote_ip ${allow.join(' ')}\n\trespond @denied 403\n`\n\t\t\t: ''\n\t}${\n\t\trequireHeader\n\t\t\t? `\n\t# Only what the CDN sends: it adds this header to every request, and this\n\t# host would be reached around the CDN otherwise.\n\t@forged not header ${requireHeader.name} \"${requireHeader.value}\"\n\trespond @forged 403\n`\n\t\t\t: ''\n\t}${\n\t\tauth\n\t\t\t? `\n\t# The stage's login, asked for before anything reaches the upstream.\n\tbasic_auth {\n\t\t${auth.user} ${auth.hash}\n\t}\n`\n\t\t\t: ''\n\t}${\n\t\tallowed.length\n\t\t\t? `\n\t# Only these paths answer. Everything else on this host is refused before\n\t# it reaches the upstream.\n\t@elsewhere not path ${allowed.join(' ')}\n\trespond @elsewhere 404\n`\n\t\t\t: ''\n\t}`;\n\n\tconst proxy = proxyBlock(route);\n\tconst body = handlers?.length\n\t\t? `${handlers\n\t\t\t\t.map(\n\t\t\t\t\t(handler, index) => `\n\t# Answered by another service: ${handler.name}.\n\t@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(' ')}\n\thandle @handler${index} {\n\t\treverse_proxy ${handler.upstreams.map(address).join(' ')}\n\t}\n`,\n\t\t\t\t)\n\t\t\t\t.join('')}\n\thandle {${proxy.replace(/\\n/g, '\\n\\t')}\n\t}`\n\t\t: proxy;\n\n\t// Its aliases join the block: every check and handler holds on each.\n\tconst names = [host, ...(route.aliases ?? [])]\n\t\t.map((name) => `https://${name}`)\n\t\t.join(', ');\n\t// Each redirect host, a block of its own that sends the browser to the\n\t// canonical host, path and query kept, and proxies nothing.\n\tconst redirects = (route.redirects?.hosts ?? [])\n\t\t.map(\n\t\t\t(from) => `\n\nhttps://${from} {${certificate}\n\tredir ${route.redirects?.to}{uri} permanent\n}`,\n\t\t)\n\t\t.join('');\n\n\treturn `${names} {${certificate}${clientIpRule(edgeToken)}\n${checks}${body}\n}${redirects}`;\n}\n\n/** Where a route's requests go, when no handler took them. */\nfunction proxyBlock(route: EdgeRoute): string {\n\tconst { upstreams, prefix, streaming } = route;\n\tconst health = healthCheck(route);\n\treturn prefix\n\t\t? `\n\t# A bucket, served at a host of its own: the bucket is a prefix on MinIO,\n\t# which routes and signs on the Host header — so it is sent the upstream's.\n\treverse_proxy ${upstreams.map(address).join(' ')} {\n\t\trewrite ${prefix}{uri}\n\t\theader_up Host {upstream_hostport}${health}\n\t}`\n\t\t: `\n\t# Host and X-Forwarded-* are passed through as Caddy does by default, so\n\t# an app builds redirects, cookies and links on the address a caller used.\n\treverse_proxy ${upstreams.map(address).join(' ')}${\n\t\tstreaming || health\n\t\t\t? ` {${\n\t\t\t\t\tstreaming\n\t\t\t\t\t\t? `\n\t\t# Never buffer: a streamed response — server-sent events, a Next.js\n\t\t# RSC payload — reaches the client as each chunk is written.\n\t\tflush_interval -1`\n\t\t\t\t\t\t: ''\n\t\t\t\t}${health}\n\t}`\n\t\t\t: ''\n\t}`;\n}\n\n/**\n * Caddy's own check of each upstream, as the Traefik edge's\n * `loadBalancer.healthCheck`: one that stops answering is taken out of\n * rotation until it does again. Caddy starts once its apps have — not once\n * they are healthy — so this is what keeps a request from an upstream that\n * is not up, and a route to an app with none up answers an error (503)\n * rather than going missing.\n */\nfunction healthCheck({ health }: EdgeRoute): string {\n\treturn health\n\t\t? `\n\t\t# Each upstream asked on its own: one that stops answering is out of\n\t\t# rotation until it answers again.\n\t\thealth_uri ${health}\n\t\thealth_interval 5s\n\t\thealth_timeout 3s`\n\t\t: '';\n}\n\nconst HEADER = `# Generated by gkm compose from the construct manifest — do not edit.\n#\n# One host per API and site, each in front of its own container, one per\n# file server in front of the stack's MinIO — its processors' paths sent to\n# their own service — one per worker SNS pushes to and per processor unit a\n# CDN reaches, answering only those paths, and — when its logs are served\n# publicly — one for OpenObserve, to the addresses it allows. A site the\n# stage puts behind a password asks for its login first.\n`;\n\n/**\n * The lines every site block of an edge opens with, for gkm's own\n * `x-gkm-client-ip` — the client address the auth server rate-limits by.\n *\n * Only a service of this stack may send it. One that calls a sibling at its\n * public address comes through this edge, and proves where it comes from with\n * the stack's token (`x-gkm-edge-token`), derived from the stage's seed and\n * handed to every process of the stack — never to a browser. A request\n * without it has the header removed, so nobody outside can choose the address\n * they are rate-limited by. Without a token, it is removed from every request.\n */\nexport function clientIpRule(edgeToken: string | undefined): string {\n\tif (!edgeToken) {\n\t\treturn `\n\t# gkm's own header, which only a service of this stack may send: the auth\n\t# server rate-limits by the client address it carries.\n\trequest_header -${CLIENT_IP_HEADER}`;\n\t}\n\treturn `\n\t# gkm's own header, which only a service of this stack may send — proven by\n\t# the stack's token: the auth server rate-limits by the client address it\n\t# carries. Removed from every other request.\n\t@gkm_outside not header ${EDGE_TOKEN_HEADER} ${edgeToken}\n\trequest_header @gkm_outside -${CLIENT_IP_HEADER}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,MAAa,gBAAgB;;AAmB7B,SAAS,QAAQ,EAAE,SAAS,QAA0B;CACrD,OAAO,GAAG,QAAQ,GAAG;AACtB;;AAGA,SAAgB,cACf,QACA,SACS;CACT,MAAM,EAAE,QAAQ;CAIhB,MAAM,MAAM,OAAO,MAAM,UAAU,MAAM,UAAU,IAAI,SAAS,WAAW,CAAC,EACzE,UAAU;CACb,MAAM,WACL,KAAK,SAAS,cACX;;QAEG,IAAI,IAAI;MAEX;CACJ,MAAM,WAAW,GAAG,QAAQ,QAAQ,aAAa,QAAQ,UAAU,KAClE,QAAQ,cAAc,QAAQ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TOKEN_HEADER"],"sources":["../../src/proxy/caddy.ts"],"sourcesContent":["/**\n * The stack's own edge, rendered for Caddy: one site block per route.\n *\n * Deployed, each host is the stage's real domain and Caddy gets it a\n * certificate from Let's Encrypt on first request — the same automatic HTTPS\n * it does anywhere, with nothing to configure but the name — or serves the\n * stage's own certificate (`deploy.compose.tls`). Locally the hosts are\n * `*.localhost` and the certificate is the one gkm's local authority issued,\n * as the `gkm dev` edge's is, so a local stack is `https://` like a deployed\n * one.\n *\n * Pure: the routes are data (`@geekmidas/edge/routes`), and rendering them is one string.\n */\n\nimport { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from '@geekmidas/manifest';\nimport {\n\tassertRouteRenderable,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype Upstream,\n\tupstreamAddress,\n} from '../routes';\n\n/** Where Caddy reads a stage's own certificate, inside its container. */\nexport const CADDY_TLS_DIR = '/etc/caddy/tls';\n\nexport interface CaddyfileOptions {\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\t/** Where ACME sends expiry notices, when someone wants them. */\n\temail?: string;\n\t/**\n\t * `false` on the local stage: plain HTTP is not sent to HTTPS, whose\n\t * published port there may not be 443.\n\t */\n\tredirects?: boolean;\n}\n\n/** An upstream on the stack's own network — its service name — or on the host. */\nfunction address(upstream: Upstream): string {\n\treturn upstreamAddress(upstream);\n}\n\n/** The Caddyfile for a stack's edge. */\nexport function edgeCaddyfile(\n\troutes: readonly EdgeRoute[],\n\toptions: CaddyfileOptions,\n): string {\n\tconst { tls } = options;\n\t// A wildcard site certified host by host: Caddy asks its `hosts` route\n\t// before it gets a certificate for one, so a name no tenant has is never\n\t// sent to Let's Encrypt.\n\tconst ask = routes.find((route) => route.wildcard?.tls.kind === 'on-demand')\n\t\t?.wildcard?.tls;\n\tconst onDemand =\n\t\task?.kind === 'on-demand'\n\t\t\t? `\n\ton_demand_tls {\n\t\task ${ask.ask}\n\t}`\n\t\t\t: '';\n\tconst settings = `${options.email ? `\\n\\temail ${options.email}` : ''}${\n\t\toptions.redirects === false ? '\\n\\tauto_https disable_redirects' : ''\n\t}${onDemand}`;\n\tconst global = settings ? `{${settings}\\n}` : '';\n\n\tconst certificate =\n\t\ttls.kind === 'files'\n\t\t\t? `\n\ttls ${tls.certFile} ${tls.keyFile}\n`\n\t\t\t: '';\n\n\t// The wildcard site last: Caddy prefers a named host to `*.<domain>`\n\t// wherever the blocks are, and reading it last says the same.\n\tconst blocks = [\n\t\t...routes.filter((route) => !route.wildcard),\n\t\t...routes.filter((route) => route.wildcard),\n\t].map((route) =>\n\t\tsiteBlock(\n\t\t\troute,\n\t\t\toptions.edgeToken,\n\t\t\troute.wildcard?.tls.kind === 'on-demand'\n\t\t\t\t? `\n\ttls {\n\t\ton_demand\n\t}\n`\n\t\t\t\t: certificate,\n\t\t),\n\t);\n\n\t// No blank line under the header: `caddy fmt` wants the first block there.\n\treturn `${HEADER}${global ? `${global}\\n\\n` : ''}${blocks.join('\\n\\n')}\\n`;\n}\n\n/** One route's site block. */\nfunction siteBlock(\n\troute: EdgeRoute,\n\tedgeToken: string | undefined,\n\tcertificate: string,\n): string {\n\tassertRouteRenderable(route);\n\tconst { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;\n\tconst allowed = [\n\t\t...(paths ?? []),\n\t\t...(prefixes ?? []).map((prefix) => `${prefix}*`),\n\t];\n\n\tconst except = route.wildcard?.except ?? [];\n\tconst checks = `${\n\t\texcept.length\n\t\t\t? `\n\t# Labels no tenant may take, although nothing in this stack answers them.\n\t@protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(' ')}\n\trespond @protected 404\n`\n\t\t\t: ''\n\t}${\n\t\tallow\n\t\t\t? `\n\t# Only these addresses — the peer Caddy sees, never a header a client\n\t# could set. Everything else is refused before it reaches the upstream.\n\t@denied not remote_ip ${allow.join(' ')}\n\trespond @denied 403\n`\n\t\t\t: ''\n\t}${\n\t\trequireHeader\n\t\t\t? `\n\t# Only what the CDN sends: it adds this header to every request, and this\n\t# host would be reached around the CDN otherwise.\n\t@forged not header ${requireHeader.name} \"${requireHeader.value}\"\n\trespond @forged 403\n`\n\t\t\t: ''\n\t}${\n\t\tauth\n\t\t\t? `\n\t# The stage's login, asked for before anything reaches the upstream.\n\tbasic_auth {\n\t\t${auth.user} ${auth.hash}\n\t}\n`\n\t\t\t: ''\n\t}${\n\t\tallowed.length\n\t\t\t? `\n\t# Only these paths answer. Everything else on this host is refused before\n\t# it reaches the upstream.\n\t@elsewhere not path ${allowed.join(' ')}\n\trespond @elsewhere 404\n`\n\t\t\t: ''\n\t}`;\n\n\tconst proxy = proxyBlock(route);\n\tconst body = handlers?.length\n\t\t? `${handlers\n\t\t\t\t.map(\n\t\t\t\t\t(handler, index) => `\n\t# Answered by another service: ${handler.name}.\n\t@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(' ')}\n\thandle @handler${index} {\n\t\treverse_proxy ${handler.upstreams.map(address).join(' ')}${\n\t\t\thandler.under\n\t\t\t\t? ` {\n\t\t\trewrite ${handler.under}{uri}\n\t\t}`\n\t\t\t\t: ''\n\t\t}\n\t}\n`,\n\t\t\t\t)\n\t\t\t\t.join('')}\n\thandle {${proxy.replace(/\\n/g, '\\n\\t')}\n\t}`\n\t\t: proxy;\n\n\t// Its aliases join the block: every check and handler holds on each.\n\tconst names = [host, ...(route.aliases ?? [])]\n\t\t.map((name) => `https://${name}`)\n\t\t.join(', ');\n\t// Each redirect host, a block of its own that sends the browser to the\n\t// canonical host, path and query kept, and proxies nothing.\n\tconst redirects = (route.redirects?.hosts ?? [])\n\t\t.map(\n\t\t\t(from) => `\n\nhttps://${from} {${certificate}\n\tredir ${route.redirects?.to}{uri} permanent\n}`,\n\t\t)\n\t\t.join('');\n\n\treturn `${names} {${certificate}${clientIpRule(edgeToken)}\n${checks}${body}\n}${redirects}`;\n}\n\n/** Where a route's requests go, when no handler took them. */\nfunction proxyBlock(route: EdgeRoute): string {\n\tconst { upstreams, prefix, streaming } = route;\n\tconst health = healthCheck(route);\n\treturn prefix\n\t\t? `\n\t# A bucket, served at a host of its own: the bucket is a prefix on MinIO,\n\t# which routes and signs on the Host header — so it is sent the upstream's.\n\treverse_proxy ${upstreams.map(address).join(' ')} {\n\t\trewrite ${prefix}{uri}\n\t\theader_up Host {upstream_hostport}${health}\n\t}`\n\t\t: `\n\t# Host and X-Forwarded-* are passed through as Caddy does by default, so\n\t# an app builds redirects, cookies and links on the address a caller used.\n\treverse_proxy ${upstreams.map(address).join(' ')}${\n\t\tstreaming || health\n\t\t\t? ` {${\n\t\t\t\t\tstreaming\n\t\t\t\t\t\t? `\n\t\t# Never buffer: a streamed response — server-sent events, a Next.js\n\t\t# RSC payload — reaches the client as each chunk is written.\n\t\tflush_interval -1`\n\t\t\t\t\t\t: ''\n\t\t\t\t}${health}\n\t}`\n\t\t\t: ''\n\t}`;\n}\n\n/**\n * Caddy's own check of each upstream, as the Traefik edge's\n * `loadBalancer.healthCheck`: one that stops answering is taken out of\n * rotation until it does again. Caddy starts once its apps have — not once\n * they are healthy — so this is what keeps a request from an upstream that\n * is not up, and a route to an app with none up answers an error (503)\n * rather than going missing.\n */\nfunction healthCheck({ health }: EdgeRoute): string {\n\treturn health\n\t\t? `\n\t\t# Each upstream asked on its own: one that stops answering is out of\n\t\t# rotation until it answers again.\n\t\thealth_uri ${health}\n\t\thealth_interval 5s\n\t\thealth_timeout 3s`\n\t\t: '';\n}\n\nconst HEADER = `# Generated by gkm compose from the construct manifest — do not edit.\n#\n# One host per API and site, each in front of its own container, one per\n# file server in front of the stack's MinIO — its processors' paths sent to\n# their own service — one per worker SNS pushes to and per processor unit a\n# CDN reaches, answering only those paths, and — when its logs are served\n# publicly — one for OpenObserve, to the addresses it allows. A site the\n# stage puts behind a password asks for its login first.\n`;\n\n/**\n * The lines every site block of an edge opens with, for gkm's own\n * `x-gkm-client-ip` — the client address the auth server rate-limits by.\n *\n * Only a service of this stack may send it. One that calls a sibling at its\n * public address comes through this edge, and proves where it comes from with\n * the stack's token (`x-gkm-edge-token`), derived from the stage's seed and\n * handed to every process of the stack — never to a browser. A request\n * without it has the header removed, so nobody outside can choose the address\n * they are rate-limited by. Without a token, it is removed from every request.\n */\nexport function clientIpRule(edgeToken: string | undefined): string {\n\tif (!edgeToken) {\n\t\treturn `\n\t# gkm's own header, which only a service of this stack may send: the auth\n\t# server rate-limits by the client address it carries.\n\trequest_header -${CLIENT_IP_HEADER}`;\n\t}\n\treturn `\n\t# gkm's own header, which only a service of this stack may send — proven by\n\t# the stack's token: the auth server rate-limits by the client address it\n\t# carries. Removed from every other request.\n\t@gkm_outside not header ${EDGE_TOKEN_HEADER} ${edgeToken}\n\trequest_header @gkm_outside -${CLIENT_IP_HEADER}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,MAAa,gBAAgB;;AAmB7B,SAAS,QAAQ,UAA4B;CAC5C,OAAOA,qBAAAA,gBAAgB,QAAQ;AAChC;;AAGA,SAAgB,cACf,QACA,SACS;CACT,MAAM,EAAE,QAAQ;CAIhB,MAAM,MAAM,OAAO,MAAM,UAAU,MAAM,UAAU,IAAI,SAAS,WAAW,CAAC,EACzE,UAAU;CACb,MAAM,WACL,KAAK,SAAS,cACX;;QAEG,IAAI,IAAI;MAEX;CACJ,MAAM,WAAW,GAAG,QAAQ,QAAQ,aAAa,QAAQ,UAAU,KAClE,QAAQ,cAAc,QAAQ,oCAAqC,KACjE;CACH,MAAM,SAAS,WAAW,IAAI,SAAS,OAAO;CAE9C,MAAM,cACL,IAAI,SAAS,UACV;OACE,IAAI,SAAS,GAAG,IAAI,QAAQ;IAE9B;CAIJ,MAAM,SAAS,CACd,GAAG,OAAO,QAAQ,UAAU,CAAC,MAAM,QAAQ,GAC3C,GAAG,OAAO,QAAQ,UAAU,MAAM,QAAQ,CAC3C,CAAC,CAAC,KAAK,UACN,UACC,OACA,QAAQ,WACR,MAAM,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,CAAE,CAAC,CAC5C,KAAK,SAAS,WAAW,MAAM,CAAC,CAChC,KAAK,IAAI;CAGX,MAAM,aAAa,MAAM,WAAW,SAAS,CAAC,EAAA,CAC5C,KACC,SAAS;;UAEH,KAAK,IAAI,YAAY;SACtB,MAAM,WAAW,GAAG;EAE3B,CAAC,CACA,KAAK,EAAE;CAET,OAAO,GAAG,MAAM,IAAI,cAAc,aAAa,SAAS,EAAE;EACzD,SAAS,KAAK;GACb;AACH;;AAGA,SAAS,WAAW,OAA0B;CAC7C,MAAM,EAAE,WAAW,QAAQ,cAAc;CACzC,MAAM,SAAS,YAAY,KAAK;CAChC,OAAO,SACJ;;;iBAGa,UAAU,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,EAAE;YACtC,OAAO;sCACmB,OAAO;MAEzC;;;iBAGa,UAAU,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,IAC9C,aAAa,SACV,KACA,YACG;;;uBAIA,KACD,OAAO;MAET;AAEL;;;;;;;;;AAUA,SAAS,YAAY,EAAE,UAA6B;CACnD,OAAO,SACJ;;;eAGW,OAAO;;uBAGlB;AACJ;AAEA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;AAqBf,SAAgB,aAAa,WAAuC;CACnE,IAAI,CAAC,WACJ,OAAO;;;mBAGUC,oBAAAA;CAElB,OAAO;;;;2BAImBC,oBAAAA,kBAAkB,GAAG,UAAU;gCAC1BD,oBAAAA;AAChC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caddy.d.cts","names":[],"sources":["../../src/proxy/caddy.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"caddy.d.cts","names":[],"sources":["../../src/proxy/caddy.ts"],"mappings":";;;qBAwBa;iBAEI;EAChB,KAAK;;;;;EAKL;;EAEA;;;;;EAKA;;;wBASe,cACf,iBAAiB,aACjB,SAAS;;;;;;;;;;;;wBAgOM,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caddy.d.mts","names":[],"sources":["../../src/proxy/caddy.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"caddy.d.mts","names":[],"sources":["../../src/proxy/caddy.ts"],"mappings":";;;qBAwBa;iBAEI;EAChB,KAAK;;;;;EAKL;;EAEA;;;;;EAKA;;;wBASe,cACf,iBAAiB,aACjB,SAAS;;;;;;;;;;;;wBAgOM,aAAa"}
|
package/dist/proxy/caddy.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { assertRouteRenderable } from "../routes/index.mjs";
|
|
1
|
+
import { assertRouteRenderable, upstreamAddress } from "../routes/index.mjs";
|
|
2
2
|
import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from "@geekmidas/manifest";
|
|
3
3
|
//#region src/proxy/caddy.ts
|
|
4
4
|
/**
|
|
@@ -16,9 +16,9 @@ import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from "@geekmidas/manifest";
|
|
|
16
16
|
*/
|
|
17
17
|
/** Where Caddy reads a stage's own certificate, inside its container. */
|
|
18
18
|
const CADDY_TLS_DIR = "/etc/caddy/tls";
|
|
19
|
-
/** An upstream on the stack's own network
|
|
20
|
-
function address(
|
|
21
|
-
return
|
|
19
|
+
/** An upstream on the stack's own network — its service name — or on the host. */
|
|
20
|
+
function address(upstream) {
|
|
21
|
+
return upstreamAddress(upstream);
|
|
22
22
|
}
|
|
23
23
|
/** The Caddyfile for a stack's edge. */
|
|
24
24
|
function edgeCaddyfile(routes, options) {
|
|
@@ -76,7 +76,9 @@ function siteBlock(route, edgeToken, certificate) {
|
|
|
76
76
|
# Answered by another service: ${handler.name}.
|
|
77
77
|
@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(" ")}
|
|
78
78
|
handle @handler${index} {
|
|
79
|
-
reverse_proxy ${handler.upstreams.map(address).join(" ")}
|
|
79
|
+
reverse_proxy ${handler.upstreams.map(address).join(" ")}${handler.under ? ` {
|
|
80
|
+
rewrite ${handler.under}{uri}
|
|
81
|
+
}` : ""}
|
|
80
82
|
}
|
|
81
83
|
`).join("")}
|
|
82
84
|
handle {${proxy.replace(/\n/g, "\n ")}
|
package/dist/proxy/caddy.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"caddy.mjs","names":[],"sources":["../../src/proxy/caddy.ts"],"sourcesContent":["/**\n * The stack's own edge, rendered for Caddy: one site block per route.\n *\n * Deployed, each host is the stage's real domain and Caddy gets it a\n * certificate from Let's Encrypt on first request — the same automatic HTTPS\n * it does anywhere, with nothing to configure but the name — or serves the\n * stage's own certificate (`deploy.compose.tls`). Locally the hosts are\n * `*.localhost` and the certificate is the one gkm's local authority issued,\n * as the `gkm dev` edge's is, so a local stack is `https://` like a deployed\n * one.\n *\n * Pure: the routes are data (`@geekmidas/edge/routes`), and rendering them is one string.\n */\n\nimport { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from '@geekmidas/manifest';\nimport {\n\tassertRouteRenderable,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype Upstream,\n} from '../routes';\n\n/** Where Caddy reads a stage's own certificate, inside its container. */\nexport const CADDY_TLS_DIR = '/etc/caddy/tls';\n\nexport interface CaddyfileOptions {\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\t/** Where ACME sends expiry notices, when someone wants them. */\n\temail?: string;\n\t/**\n\t * `false` on the local stage: plain HTTP is not sent to HTTPS, whose\n\t * published port there may not be 443.\n\t */\n\tredirects?: boolean;\n}\n\n/** An upstream on the stack's own network: its service name. */\nfunction address({ service, port }: Upstream): string {\n\treturn `${service}:${port}`;\n}\n\n/** The Caddyfile for a stack's edge. */\nexport function edgeCaddyfile(\n\troutes: readonly EdgeRoute[],\n\toptions: CaddyfileOptions,\n): string {\n\tconst { tls } = options;\n\t// A wildcard site certified host by host: Caddy asks its `hosts` route\n\t// before it gets a certificate for one, so a name no tenant has is never\n\t// sent to Let's Encrypt.\n\tconst ask = routes.find((route) => route.wildcard?.tls.kind === 'on-demand')\n\t\t?.wildcard?.tls;\n\tconst onDemand =\n\t\task?.kind === 'on-demand'\n\t\t\t? `\n\ton_demand_tls {\n\t\task ${ask.ask}\n\t}`\n\t\t\t: '';\n\tconst settings = `${options.email ? `\\n\\temail ${options.email}` : ''}${\n\t\toptions.redirects === false ? '\\n\\tauto_https disable_redirects' : ''\n\t}${onDemand}`;\n\tconst global = settings ? `{${settings}\\n}` : '';\n\n\tconst certificate =\n\t\ttls.kind === 'files'\n\t\t\t? `\n\ttls ${tls.certFile} ${tls.keyFile}\n`\n\t\t\t: '';\n\n\t// The wildcard site last: Caddy prefers a named host to `*.<domain>`\n\t// wherever the blocks are, and reading it last says the same.\n\tconst blocks = [\n\t\t...routes.filter((route) => !route.wildcard),\n\t\t...routes.filter((route) => route.wildcard),\n\t].map((route) =>\n\t\tsiteBlock(\n\t\t\troute,\n\t\t\toptions.edgeToken,\n\t\t\troute.wildcard?.tls.kind === 'on-demand'\n\t\t\t\t? `\n\ttls {\n\t\ton_demand\n\t}\n`\n\t\t\t\t: certificate,\n\t\t),\n\t);\n\n\t// No blank line under the header: `caddy fmt` wants the first block there.\n\treturn `${HEADER}${global ? `${global}\\n\\n` : ''}${blocks.join('\\n\\n')}\\n`;\n}\n\n/** One route's site block. */\nfunction siteBlock(\n\troute: EdgeRoute,\n\tedgeToken: string | undefined,\n\tcertificate: string,\n): string {\n\tassertRouteRenderable(route);\n\tconst { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;\n\tconst allowed = [\n\t\t...(paths ?? []),\n\t\t...(prefixes ?? []).map((prefix) => `${prefix}*`),\n\t];\n\n\tconst except = route.wildcard?.except ?? [];\n\tconst checks = `${\n\t\texcept.length\n\t\t\t? `\n\t# Labels no tenant may take, although nothing in this stack answers them.\n\t@protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(' ')}\n\trespond @protected 404\n`\n\t\t\t: ''\n\t}${\n\t\tallow\n\t\t\t? `\n\t# Only these addresses — the peer Caddy sees, never a header a client\n\t# could set. Everything else is refused before it reaches the upstream.\n\t@denied not remote_ip ${allow.join(' ')}\n\trespond @denied 403\n`\n\t\t\t: ''\n\t}${\n\t\trequireHeader\n\t\t\t? `\n\t# Only what the CDN sends: it adds this header to every request, and this\n\t# host would be reached around the CDN otherwise.\n\t@forged not header ${requireHeader.name} \"${requireHeader.value}\"\n\trespond @forged 403\n`\n\t\t\t: ''\n\t}${\n\t\tauth\n\t\t\t? `\n\t# The stage's login, asked for before anything reaches the upstream.\n\tbasic_auth {\n\t\t${auth.user} ${auth.hash}\n\t}\n`\n\t\t\t: ''\n\t}${\n\t\tallowed.length\n\t\t\t? `\n\t# Only these paths answer. Everything else on this host is refused before\n\t# it reaches the upstream.\n\t@elsewhere not path ${allowed.join(' ')}\n\trespond @elsewhere 404\n`\n\t\t\t: ''\n\t}`;\n\n\tconst proxy = proxyBlock(route);\n\tconst body = handlers?.length\n\t\t? `${handlers\n\t\t\t\t.map(\n\t\t\t\t\t(handler, index) => `\n\t# Answered by another service: ${handler.name}.\n\t@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(' ')}\n\thandle @handler${index} {\n\t\treverse_proxy ${handler.upstreams.map(address).join(' ')}\n\t}\n`,\n\t\t\t\t)\n\t\t\t\t.join('')}\n\thandle {${proxy.replace(/\\n/g, '\\n\\t')}\n\t}`\n\t\t: proxy;\n\n\t// Its aliases join the block: every check and handler holds on each.\n\tconst names = [host, ...(route.aliases ?? [])]\n\t\t.map((name) => `https://${name}`)\n\t\t.join(', ');\n\t// Each redirect host, a block of its own that sends the browser to the\n\t// canonical host, path and query kept, and proxies nothing.\n\tconst redirects = (route.redirects?.hosts ?? [])\n\t\t.map(\n\t\t\t(from) => `\n\nhttps://${from} {${certificate}\n\tredir ${route.redirects?.to}{uri} permanent\n}`,\n\t\t)\n\t\t.join('');\n\n\treturn `${names} {${certificate}${clientIpRule(edgeToken)}\n${checks}${body}\n}${redirects}`;\n}\n\n/** Where a route's requests go, when no handler took them. */\nfunction proxyBlock(route: EdgeRoute): string {\n\tconst { upstreams, prefix, streaming } = route;\n\tconst health = healthCheck(route);\n\treturn prefix\n\t\t? `\n\t# A bucket, served at a host of its own: the bucket is a prefix on MinIO,\n\t# which routes and signs on the Host header — so it is sent the upstream's.\n\treverse_proxy ${upstreams.map(address).join(' ')} {\n\t\trewrite ${prefix}{uri}\n\t\theader_up Host {upstream_hostport}${health}\n\t}`\n\t\t: `\n\t# Host and X-Forwarded-* are passed through as Caddy does by default, so\n\t# an app builds redirects, cookies and links on the address a caller used.\n\treverse_proxy ${upstreams.map(address).join(' ')}${\n\t\tstreaming || health\n\t\t\t? ` {${\n\t\t\t\t\tstreaming\n\t\t\t\t\t\t? `\n\t\t# Never buffer: a streamed response — server-sent events, a Next.js\n\t\t# RSC payload — reaches the client as each chunk is written.\n\t\tflush_interval -1`\n\t\t\t\t\t\t: ''\n\t\t\t\t}${health}\n\t}`\n\t\t\t: ''\n\t}`;\n}\n\n/**\n * Caddy's own check of each upstream, as the Traefik edge's\n * `loadBalancer.healthCheck`: one that stops answering is taken out of\n * rotation until it does again. Caddy starts once its apps have — not once\n * they are healthy — so this is what keeps a request from an upstream that\n * is not up, and a route to an app with none up answers an error (503)\n * rather than going missing.\n */\nfunction healthCheck({ health }: EdgeRoute): string {\n\treturn health\n\t\t? `\n\t\t# Each upstream asked on its own: one that stops answering is out of\n\t\t# rotation until it answers again.\n\t\thealth_uri ${health}\n\t\thealth_interval 5s\n\t\thealth_timeout 3s`\n\t\t: '';\n}\n\nconst HEADER = `# Generated by gkm compose from the construct manifest — do not edit.\n#\n# One host per API and site, each in front of its own container, one per\n# file server in front of the stack's MinIO — its processors' paths sent to\n# their own service — one per worker SNS pushes to and per processor unit a\n# CDN reaches, answering only those paths, and — when its logs are served\n# publicly — one for OpenObserve, to the addresses it allows. A site the\n# stage puts behind a password asks for its login first.\n`;\n\n/**\n * The lines every site block of an edge opens with, for gkm's own\n * `x-gkm-client-ip` — the client address the auth server rate-limits by.\n *\n * Only a service of this stack may send it. One that calls a sibling at its\n * public address comes through this edge, and proves where it comes from with\n * the stack's token (`x-gkm-edge-token`), derived from the stage's seed and\n * handed to every process of the stack — never to a browser. A request\n * without it has the header removed, so nobody outside can choose the address\n * they are rate-limited by. Without a token, it is removed from every request.\n */\nexport function clientIpRule(edgeToken: string | undefined): string {\n\tif (!edgeToken) {\n\t\treturn `\n\t# gkm's own header, which only a service of this stack may send: the auth\n\t# server rate-limits by the client address it carries.\n\trequest_header -${CLIENT_IP_HEADER}`;\n\t}\n\treturn `\n\t# gkm's own header, which only a service of this stack may send — proven by\n\t# the stack's token: the auth server rate-limits by the client address it\n\t# carries. Removed from every other request.\n\t@gkm_outside not header ${EDGE_TOKEN_HEADER} ${edgeToken}\n\trequest_header @gkm_outside -${CLIENT_IP_HEADER}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuBA,MAAa,gBAAgB;;AAmB7B,SAAS,QAAQ,EAAE,SAAS,QAA0B;CACrD,OAAO,GAAG,QAAQ,GAAG;AACtB;;AAGA,SAAgB,cACf,QACA,SACS;CACT,MAAM,EAAE,QAAQ;CAIhB,MAAM,MAAM,OAAO,MAAM,UAAU,MAAM,UAAU,IAAI,SAAS,WAAW,CAAC,EACzE,UAAU;CACb,MAAM,WACL,KAAK,SAAS,cACX;;QAEG,IAAI,IAAI;MAEX;CACJ,MAAM,WAAW,GAAG,QAAQ,QAAQ,aAAa,QAAQ,UAAU,KAClE,QAAQ,cAAc,QAAQ,oCAAqC,KACjE;CACH,MAAM,SAAS,WAAW,IAAI,SAAS,OAAO;CAE9C,MAAM,cACL,IAAI,SAAS,UACV;OACE,IAAI,SAAS,GAAG,IAAI,QAAQ;IAE9B;CAIJ,MAAM,SAAS,CACd,GAAG,OAAO,QAAQ,UAAU,CAAC,MAAM,QAAQ,GAC3C,GAAG,OAAO,QAAQ,UAAU,MAAM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I,MAAM,WAAW,CAAC,CAAE,CAAC,CAC5C,KAAK,SAAS,WAAW,MAAM,CAAC,CAChC,KAAK,IAAI;CAGX,MAAM,aAAa,MAAM,WAAW,SAAS,CAAC,EAAA,CAC5C,KACC,SAAS;;UAEH,KAAK,IAAI,YAAY;SACtB,MAAM,WAAW,GAAG;EAE3B,CAAC,CACA,KAAK,EAAE;CAET,OAAO,GAAG,MAAM,IAAI,cAAc,aAAa,SAAS,EAAE;EACzD,SAAS,KAAK;GACb;AACH;;AAGA,SAAS,WAAW,OAA0B;CAC7C,MAAM,EAAE,WAAW,QAAQ,cAAc;CACzC,MAAM,SAAS,YAAY,KAAK;CAChC,OAAO,SACJ;;;iBAGa,UAAU,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,EAAE;YACtC,OAAO;sCACmB,OAAO;MAEzC;;;iBAGa,UAAU,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,IAC9C,aAAa,SACV,KACA,YACG;;;uBAIA,KACD,OAAO;MAET;AAEL;;;;;;;;;AAUA,SAAS,YAAY,EAAE,UAA6B;CACnD,OAAO,SACJ;;;eAGW,OAAO;;uBAGlB;AACJ;AAEA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;AAqBf,SAAgB,aAAa,WAAuC;CACnE,IAAI,CAAC,WACJ,OAAO;;;mBAGU;CAElB,OAAO;;;;2BAImB,kBAAkB,GAAG,UAAU;gCAC1B;AAChC"}
|
|
1
|
+
{"version":3,"file":"caddy.mjs","names":[],"sources":["../../src/proxy/caddy.ts"],"sourcesContent":["/**\n * The stack's own edge, rendered for Caddy: one site block per route.\n *\n * Deployed, each host is the stage's real domain and Caddy gets it a\n * certificate from Let's Encrypt on first request — the same automatic HTTPS\n * it does anywhere, with nothing to configure but the name — or serves the\n * stage's own certificate (`deploy.compose.tls`). Locally the hosts are\n * `*.localhost` and the certificate is the one gkm's local authority issued,\n * as the `gkm dev` edge's is, so a local stack is `https://` like a deployed\n * one.\n *\n * Pure: the routes are data (`@geekmidas/edge/routes`), and rendering them is one string.\n */\n\nimport { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from '@geekmidas/manifest';\nimport {\n\tassertRouteRenderable,\n\ttype EdgeRoute,\n\ttype EdgeTls,\n\ttype Upstream,\n\tupstreamAddress,\n} from '../routes';\n\n/** Where Caddy reads a stage's own certificate, inside its container. */\nexport const CADDY_TLS_DIR = '/etc/caddy/tls';\n\nexport interface CaddyfileOptions {\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\t/** Where ACME sends expiry notices, when someone wants them. */\n\temail?: string;\n\t/**\n\t * `false` on the local stage: plain HTTP is not sent to HTTPS, whose\n\t * published port there may not be 443.\n\t */\n\tredirects?: boolean;\n}\n\n/** An upstream on the stack's own network — its service name — or on the host. */\nfunction address(upstream: Upstream): string {\n\treturn upstreamAddress(upstream);\n}\n\n/** The Caddyfile for a stack's edge. */\nexport function edgeCaddyfile(\n\troutes: readonly EdgeRoute[],\n\toptions: CaddyfileOptions,\n): string {\n\tconst { tls } = options;\n\t// A wildcard site certified host by host: Caddy asks its `hosts` route\n\t// before it gets a certificate for one, so a name no tenant has is never\n\t// sent to Let's Encrypt.\n\tconst ask = routes.find((route) => route.wildcard?.tls.kind === 'on-demand')\n\t\t?.wildcard?.tls;\n\tconst onDemand =\n\t\task?.kind === 'on-demand'\n\t\t\t? `\n\ton_demand_tls {\n\t\task ${ask.ask}\n\t}`\n\t\t\t: '';\n\tconst settings = `${options.email ? `\\n\\temail ${options.email}` : ''}${\n\t\toptions.redirects === false ? '\\n\\tauto_https disable_redirects' : ''\n\t}${onDemand}`;\n\tconst global = settings ? `{${settings}\\n}` : '';\n\n\tconst certificate =\n\t\ttls.kind === 'files'\n\t\t\t? `\n\ttls ${tls.certFile} ${tls.keyFile}\n`\n\t\t\t: '';\n\n\t// The wildcard site last: Caddy prefers a named host to `*.<domain>`\n\t// wherever the blocks are, and reading it last says the same.\n\tconst blocks = [\n\t\t...routes.filter((route) => !route.wildcard),\n\t\t...routes.filter((route) => route.wildcard),\n\t].map((route) =>\n\t\tsiteBlock(\n\t\t\troute,\n\t\t\toptions.edgeToken,\n\t\t\troute.wildcard?.tls.kind === 'on-demand'\n\t\t\t\t? `\n\ttls {\n\t\ton_demand\n\t}\n`\n\t\t\t\t: certificate,\n\t\t),\n\t);\n\n\t// No blank line under the header: `caddy fmt` wants the first block there.\n\treturn `${HEADER}${global ? `${global}\\n\\n` : ''}${blocks.join('\\n\\n')}\\n`;\n}\n\n/** One route's site block. */\nfunction siteBlock(\n\troute: EdgeRoute,\n\tedgeToken: string | undefined,\n\tcertificate: string,\n): string {\n\tassertRouteRenderable(route);\n\tconst { host, allow, auth, paths, prefixes, requireHeader, handlers } = route;\n\tconst allowed = [\n\t\t...(paths ?? []),\n\t\t...(prefixes ?? []).map((prefix) => `${prefix}*`),\n\t];\n\n\tconst except = route.wildcard?.except ?? [];\n\tconst checks = `${\n\t\texcept.length\n\t\t\t? `\n\t# Labels no tenant may take, although nothing in this stack answers them.\n\t@protected host ${except.map((label) => `${label}.${route.wildcard?.domain}`).join(' ')}\n\trespond @protected 404\n`\n\t\t\t: ''\n\t}${\n\t\tallow\n\t\t\t? `\n\t# Only these addresses — the peer Caddy sees, never a header a client\n\t# could set. Everything else is refused before it reaches the upstream.\n\t@denied not remote_ip ${allow.join(' ')}\n\trespond @denied 403\n`\n\t\t\t: ''\n\t}${\n\t\trequireHeader\n\t\t\t? `\n\t# Only what the CDN sends: it adds this header to every request, and this\n\t# host would be reached around the CDN otherwise.\n\t@forged not header ${requireHeader.name} \"${requireHeader.value}\"\n\trespond @forged 403\n`\n\t\t\t: ''\n\t}${\n\t\tauth\n\t\t\t? `\n\t# The stage's login, asked for before anything reaches the upstream.\n\tbasic_auth {\n\t\t${auth.user} ${auth.hash}\n\t}\n`\n\t\t\t: ''\n\t}${\n\t\tallowed.length\n\t\t\t? `\n\t# Only these paths answer. Everything else on this host is refused before\n\t# it reaches the upstream.\n\t@elsewhere not path ${allowed.join(' ')}\n\trespond @elsewhere 404\n`\n\t\t\t: ''\n\t}`;\n\n\tconst proxy = proxyBlock(route);\n\tconst body = handlers?.length\n\t\t? `${handlers\n\t\t\t\t.map(\n\t\t\t\t\t(handler, index) => `\n\t# Answered by another service: ${handler.name}.\n\t@handler${index} path ${handler.prefixes.map((prefix) => `${prefix}*`).join(' ')}\n\thandle @handler${index} {\n\t\treverse_proxy ${handler.upstreams.map(address).join(' ')}${\n\t\t\thandler.under\n\t\t\t\t? ` {\n\t\t\trewrite ${handler.under}{uri}\n\t\t}`\n\t\t\t\t: ''\n\t\t}\n\t}\n`,\n\t\t\t\t)\n\t\t\t\t.join('')}\n\thandle {${proxy.replace(/\\n/g, '\\n\\t')}\n\t}`\n\t\t: proxy;\n\n\t// Its aliases join the block: every check and handler holds on each.\n\tconst names = [host, ...(route.aliases ?? [])]\n\t\t.map((name) => `https://${name}`)\n\t\t.join(', ');\n\t// Each redirect host, a block of its own that sends the browser to the\n\t// canonical host, path and query kept, and proxies nothing.\n\tconst redirects = (route.redirects?.hosts ?? [])\n\t\t.map(\n\t\t\t(from) => `\n\nhttps://${from} {${certificate}\n\tredir ${route.redirects?.to}{uri} permanent\n}`,\n\t\t)\n\t\t.join('');\n\n\treturn `${names} {${certificate}${clientIpRule(edgeToken)}\n${checks}${body}\n}${redirects}`;\n}\n\n/** Where a route's requests go, when no handler took them. */\nfunction proxyBlock(route: EdgeRoute): string {\n\tconst { upstreams, prefix, streaming } = route;\n\tconst health = healthCheck(route);\n\treturn prefix\n\t\t? `\n\t# A bucket, served at a host of its own: the bucket is a prefix on MinIO,\n\t# which routes and signs on the Host header — so it is sent the upstream's.\n\treverse_proxy ${upstreams.map(address).join(' ')} {\n\t\trewrite ${prefix}{uri}\n\t\theader_up Host {upstream_hostport}${health}\n\t}`\n\t\t: `\n\t# Host and X-Forwarded-* are passed through as Caddy does by default, so\n\t# an app builds redirects, cookies and links on the address a caller used.\n\treverse_proxy ${upstreams.map(address).join(' ')}${\n\t\tstreaming || health\n\t\t\t? ` {${\n\t\t\t\t\tstreaming\n\t\t\t\t\t\t? `\n\t\t# Never buffer: a streamed response — server-sent events, a Next.js\n\t\t# RSC payload — reaches the client as each chunk is written.\n\t\tflush_interval -1`\n\t\t\t\t\t\t: ''\n\t\t\t\t}${health}\n\t}`\n\t\t\t: ''\n\t}`;\n}\n\n/**\n * Caddy's own check of each upstream, as the Traefik edge's\n * `loadBalancer.healthCheck`: one that stops answering is taken out of\n * rotation until it does again. Caddy starts once its apps have — not once\n * they are healthy — so this is what keeps a request from an upstream that\n * is not up, and a route to an app with none up answers an error (503)\n * rather than going missing.\n */\nfunction healthCheck({ health }: EdgeRoute): string {\n\treturn health\n\t\t? `\n\t\t# Each upstream asked on its own: one that stops answering is out of\n\t\t# rotation until it answers again.\n\t\thealth_uri ${health}\n\t\thealth_interval 5s\n\t\thealth_timeout 3s`\n\t\t: '';\n}\n\nconst HEADER = `# Generated by gkm compose from the construct manifest — do not edit.\n#\n# One host per API and site, each in front of its own container, one per\n# file server in front of the stack's MinIO — its processors' paths sent to\n# their own service — one per worker SNS pushes to and per processor unit a\n# CDN reaches, answering only those paths, and — when its logs are served\n# publicly — one for OpenObserve, to the addresses it allows. A site the\n# stage puts behind a password asks for its login first.\n`;\n\n/**\n * The lines every site block of an edge opens with, for gkm's own\n * `x-gkm-client-ip` — the client address the auth server rate-limits by.\n *\n * Only a service of this stack may send it. One that calls a sibling at its\n * public address comes through this edge, and proves where it comes from with\n * the stack's token (`x-gkm-edge-token`), derived from the stage's seed and\n * handed to every process of the stack — never to a browser. A request\n * without it has the header removed, so nobody outside can choose the address\n * they are rate-limited by. Without a token, it is removed from every request.\n */\nexport function clientIpRule(edgeToken: string | undefined): string {\n\tif (!edgeToken) {\n\t\treturn `\n\t# gkm's own header, which only a service of this stack may send: the auth\n\t# server rate-limits by the client address it carries.\n\trequest_header -${CLIENT_IP_HEADER}`;\n\t}\n\treturn `\n\t# gkm's own header, which only a service of this stack may send — proven by\n\t# the stack's token: the auth server rate-limits by the client address it\n\t# carries. Removed from every other request.\n\t@gkm_outside not header ${EDGE_TOKEN_HEADER} ${edgeToken}\n\trequest_header @gkm_outside -${CLIENT_IP_HEADER}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,MAAa,gBAAgB;;AAmB7B,SAAS,QAAQ,UAA4B;CAC5C,OAAO,gBAAgB,QAAQ;AAChC;;AAGA,SAAgB,cACf,QACA,SACS;CACT,MAAM,EAAE,QAAQ;CAIhB,MAAM,MAAM,OAAO,MAAM,UAAU,MAAM,UAAU,IAAI,SAAS,WAAW,CAAC,EACzE,UAAU;CACb,MAAM,WACL,KAAK,SAAS,cACX;;QAEG,IAAI,IAAI;MAEX;CACJ,MAAM,WAAW,GAAG,QAAQ,QAAQ,aAAa,QAAQ,UAAU,KAClE,QAAQ,cAAc,QAAQ,oCAAqC,KACjE;CACH,MAAM,SAAS,WAAW,IAAI,SAAS,OAAO;CAE9C,MAAM,cACL,IAAI,SAAS,UACV;OACE,IAAI,SAAS,GAAG,IAAI,QAAQ;IAE9B;CAIJ,MAAM,SAAS,CACd,GAAG,OAAO,QAAQ,UAAU,CAAC,MAAM,QAAQ,GAC3C,GAAG,OAAO,QAAQ,UAAU,MAAM,QAAQ,CAC3C,CAAC,CAAC,KAAK,UACN,UACC,OACA,QAAQ,WACR,MAAM,UAAU,IAAI,SAAS,cAC1B;;;;IAKA,WACJ,CACD;CAGA,OAAO,GAAG,SAAS,SAAS,GAAG,OAAO,QAAQ,KAAK,OAAO,KAAK,MAAM,EAAE;AACxE;;AAGA,SAAS,UACR,OACA,WACA,aACS;CACT,sBAAsB,KAAK;CAC3B,MAAM,EAAE,MAAM,OAAO,MAAM,OAAO,UAAU,eAAe,aAAa;CACxE,MAAM,UAAU,CACf,GAAI,SAAS,CAAC,GACd,IAAI,YAAY,CAAC,EAAA,CAAG,KAAK,WAAW,G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WAAW,QAAQ,cAAc;CACzC,MAAM,SAAS,YAAY,KAAK;CAChC,OAAO,SACJ;;;iBAGa,UAAU,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,EAAE;YACtC,OAAO;sCACmB,OAAO;MAEzC;;;iBAGa,UAAU,IAAI,OAAO,CAAC,CAAC,KAAK,GAAG,IAC9C,aAAa,SACV,KACA,YACG;;;uBAIA,KACD,OAAO;MAET;AAEL;;;;;;;;;AAUA,SAAS,YAAY,EAAE,UAA6B;CACnD,OAAO,SACJ;;;eAGW,OAAO;;uBAGlB;AACJ;AAEA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;AAqBf,SAAgB,aAAa,WAAuC;CACnE,IAAI,CAAC,WACJ,OAAO;;;mBAGU;CAElB,OAAO;;;;2BAImB,kBAAkB,GAAG,UAAU;gCAC1B;AAChC"}
|
package/dist/proxy/traefik.cjs
CHANGED
|
@@ -154,6 +154,7 @@ function edgeCompose(options) {
|
|
|
154
154
|
AWS_REGION: "us-east-1"
|
|
155
155
|
},
|
|
156
156
|
networks: ["edge"],
|
|
157
|
+
extra_hosts: [`${require_routes_index.HOST_GATEWAY}:host-gateway`],
|
|
157
158
|
...require_routes_index.EDGE_LIMITS,
|
|
158
159
|
healthcheck: {
|
|
159
160
|
test: [
|
|
@@ -184,7 +185,7 @@ function edgeCompose(options) {
|
|
|
184
185
|
function traefikDynamic(routes, options) {
|
|
185
186
|
const { project, tls, edgeToken } = options;
|
|
186
187
|
const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
|
|
187
|
-
const url = (
|
|
188
|
+
const url = (upstream) => `http://${require_routes_index.upstreamAddress(upstream, (service) => edgeAlias(project, service))}`;
|
|
188
189
|
const routers = {};
|
|
189
190
|
const services = {};
|
|
190
191
|
const middlewares = {};
|
|
@@ -230,12 +231,14 @@ function traefikDynamic(routes, options) {
|
|
|
230
231
|
} : tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {};
|
|
231
232
|
for (const handler of route.handlers ?? []) {
|
|
232
233
|
const handlerName = name(route, handler.name);
|
|
234
|
+
const under = name(route, `${handler.name}-under`);
|
|
235
|
+
if (handler.under) middlewares[under] = { addPrefix: { prefix: handler.under } };
|
|
233
236
|
routers[handlerName] = {
|
|
234
237
|
rule: `${hostRule(route)} && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
|
|
235
238
|
priority: 1e4,
|
|
236
239
|
entryPoints: ["websecure"],
|
|
237
240
|
service: handlerName,
|
|
238
|
-
middlewares: [strip],
|
|
241
|
+
middlewares: handler.under ? [strip, under] : [strip],
|
|
239
242
|
tls: certificate()
|
|
240
243
|
};
|
|
241
244
|
services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"traefik.cjs","names":["createHash","EDGE_LIMITS","composeLiteral","CLIENT_IP_HEADER","EDGE_TOKEN_HEADER","routeHosts","parse","yaml","stringify"],"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;;AAG7B,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,mBAAmB;;AAGhC,SAAgB,YAAY,MAAyB,QAAQ,KAAa;CACzE,OAAO,IAAA,uBAAA;AACR;;;;;AAMA,MAAa,eAAe,YAAY;;;;;AAMxC,MAAa,eAAe;;AAG5B,MAAa,eAAe;;AAG5B,MAAa,mBAAmB;AAChC,MAAa,iBAAiB;;AAG9B,MAAa,gBAAgB;;;;;;AAO7B,MAAa,oBAAoB;;;;;;AAOjC,MAAa,uBAAuB,GAAG,eAAe;;AAGtD,MAAM,YAAY;;AAGlB,SAAgB,UAAU,SAAiB,SAAyB;CACnE,OAAO,GAAG,QAAQ,GAAG;AACtB;;AAGA,SAAgB,qBAAqB,SAGnC;CACD,OAAO;EACN,UAAU,GAAG,eAAe,GAAG,QAAQ;EACvC,SA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ACtC;;AAGA,SAAgB,kBAAkB,OAA0B;CAC3D,OAAO;EACNA,OAAK,cAAc,KAAK,CAAC;AAC3B;;AAGA,SAAgB,gBACf,SACS;CACT,OAAO;;;;;wBAKgB,aAAa;EACnCA,OAAK,YAAY,OAAO,CAAC;AAC3B;AAEA,SAASA,OAAK,OAAwB;CACrC,QAAA,GAAOC,KAAAA,UAAAA,CAAU,OAAO;EAAE,WAAW;EAAG,uBAAuB;CAAM,CAAC;AACvE"}
|
|
1
|
+
{"version":3,"file":"traefik.cjs","names":["createHash","HOST_GATEWAY","EDGE_LIMITS","composeLiteral","upstreamAddress","CLIENT_IP_HEADER","EDGE_TOKEN_HEADER","routeHosts","parse","yaml","stringify"],"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\tHOST_GATEWAY,\n\trouteHosts,\n\ttype Upstream,\n\tupstreamAddress,\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// A process on the host — an app `gkm dev` runs — is reached\n\t\t\t\t// through the host's gateway. Docker Desktop resolves the name\n\t\t\t\t// already; on Linux it needs saying.\n\t\t\t\textra_hosts: [`${HOST_GATEWAY}:host-gateway`],\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\t// A service of the stack by its alias on the shared network; a process on\n\t// the host — an app `gkm dev` runs — through the host's gateway.\n\tconst url = (upstream: Upstream) =>\n\t\t`http://${upstreamAddress(upstream, (service) => edgeAlias(project, service))}`;\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\t// Sent under the path the upstream mounts it on, where it names one.\n\t\t\tconst under = name(route, `${handler.name}-under`);\n\t\t\tif (handler.under) {\n\t\t\t\tmiddlewares[under] = { addPrefix: { prefix: handler.under } };\n\t\t\t}\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: handler.under ? [strip, under] : [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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,gBAAgB;;AAG7B,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,mBAAmB;;AAGhC,SAAgB,YAAY,MAAyB,QAAQ,KAAa;CACzE,OAAO,IAAA,uBAAA;AACR;;;;;AAMA,MAAa,eAAe,YAAY;;;;;AAMxC,MAAa,eAAe;;AAG5B,MAAa,eAAe;;AAG5B,MAAa,mBAAmB;AAChC,MAAa,iBAAiB;;AAG9B,MAAa,gBAAgB;;;;;;AAO7B,MAAa,oBAAoB;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,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;CAItD,MAAM,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;EACnDC,OAAK,eAAe,QAAQ,OAAO,CAAC;AACtC;;AAGA,SAAgB,kBAAkB,OAA0B;CAC3D,OAAO;EACNA,OAAK,cAAc,KAAK,CAAC;AAC3B;;AAGA,SAAgB,gBACf,SACS;CACT,OAAO;;;;;wBAKgB,aAAa;EACnCA,OAAK,YAAY,OAAO,CAAC;AAC3B;AAEA,SAASA,OAAK,OAAwB;CACrC,QAAA,GAAOC,KAAAA,UAAAA,CAAU,OAAO;EAAE,WAAW;EAAG,uBAAuB;CAAM,CAAC;AACvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"traefik.d.cts","names":[],"sources":["../../src/proxy/traefik.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"traefik.d.cts","names":[],"sources":["../../src/proxy/traefik.ts"],"mappings":";;;;;;qBAwCa;;qBAGA;;;;;;;;qBASA;;wBAGG,YAAY,MAAK,OAAO;;;;;qBAQ3B;;;;;qBAMA;;qBAGA;;qBAGA;qBACA;;qBAGA;;;;;;qBAOA;;;;;;qBAOA;;wBAMG,UAAU,iBAAiB;;wBAK3B,qBAAqB;EACpC;EACA;;;iBASgB;EAChB;EACA;;;;;;;wBAQe,cAAc,OAAO,YAAY;;wBAmDjC,YAAY;EAC3B,OAAO;;;;;;EAMP;EACA;IAAW;IAAgB,SAAS;;IACjC;;iBAwDa;EAChB;;EAEA,KAAK;;;;;EAKL;;;wBAIe,eACf,iBAAiB,aACjB,SAAS,sBACP;;;;;YA0PS;EACP;;EACA;EAAkB;;;;;;wBAMP,WAAW,iBAAiB,cAAc;;;;;;wBAyB1C,eAAe,eAAe;;;;;;;wBAqE9B,cAAc,GAAG,WAAW,GAAG;;wBAqB/B,mBACf,iBAAiB,aACjB,SAAS;;wBAWM,kBAAkB,OAAO;;wBAMzB,gBACf,SAAS,kBAAkB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"traefik.d.mts","names":[],"sources":["../../src/proxy/traefik.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"traefik.d.mts","names":[],"sources":["../../src/proxy/traefik.ts"],"mappings":";;;;;;qBAwCa;;qBAGA;;;;;;;;qBASA;;wBAGG,YAAY,MAAK,OAAO;;;;;qBAQ3B;;;;;qBAMA;;qBAGA;;qBAGA;qBACA;;qBAGA;;;;;;qBAOA;;;;;;qBAOA;;wBAMG,UAAU,iBAAiB;;wBAK3B,qBAAqB;EACpC;EACA;;;iBASgB;EAChB;EACA;;;;;;;wBAQe,cAAc,OAAO,YAAY;;wBAmDjC,YAAY;EAC3B,OAAO;;;;;;EAMP;EACA;IAAW;IAAgB,SAAS;;IACjC;;iBAwDa;EAChB;;EAEA,KAAK;;;;;EAKL;;;wBAIe,eACf,iBAAiB,aACjB,SAAS,sBACP;;;;;YA0PS;EACP;;EACA;EAAkB;;;;;;wBAMP,WAAW,iBAAiB,cAAc;;;;;;wBAyB1C,eAAe,eAAe;;;;;;;wBAqE9B,cAAc,GAAG,WAAW,GAAG;;wBAqB/B,mBACf,iBAAiB,aACjB,SAAS;;wBAWM,kBAAkB,OAAO;;wBAMzB,gBACf,SAAS,kBAAkB"}
|
package/dist/proxy/traefik.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as composeLiteral } from "../compose-CcNlj65h.mjs";
|
|
2
|
-
import { EDGE_LIMITS, assertRouteRenderable, routeHosts } from "../routes/index.mjs";
|
|
2
|
+
import { EDGE_LIMITS, HOST_GATEWAY, assertRouteRenderable, routeHosts, upstreamAddress } from "../routes/index.mjs";
|
|
3
3
|
import { CLIENT_IP_HEADER, EDGE_TOKEN_HEADER } from "@geekmidas/manifest";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { parse, stringify } from "yaml";
|
|
@@ -153,6 +153,7 @@ function edgeCompose(options) {
|
|
|
153
153
|
AWS_REGION: "us-east-1"
|
|
154
154
|
},
|
|
155
155
|
networks: ["edge"],
|
|
156
|
+
extra_hosts: [`${HOST_GATEWAY}:host-gateway`],
|
|
156
157
|
...EDGE_LIMITS,
|
|
157
158
|
healthcheck: {
|
|
158
159
|
test: [
|
|
@@ -183,7 +184,7 @@ function edgeCompose(options) {
|
|
|
183
184
|
function traefikDynamic(routes, options) {
|
|
184
185
|
const { project, tls, edgeToken } = options;
|
|
185
186
|
const name = (route, suffix) => `${project}-${route.name}${suffix ? `-${suffix}` : ""}`;
|
|
186
|
-
const url = (
|
|
187
|
+
const url = (upstream) => `http://${upstreamAddress(upstream, (service) => edgeAlias(project, service))}`;
|
|
187
188
|
const routers = {};
|
|
188
189
|
const services = {};
|
|
189
190
|
const middlewares = {};
|
|
@@ -229,12 +230,14 @@ function traefikDynamic(routes, options) {
|
|
|
229
230
|
} : tls.kind === "acme" ? { certResolver: ACME_RESOLVER } : {};
|
|
230
231
|
for (const handler of route.handlers ?? []) {
|
|
231
232
|
const handlerName = name(route, handler.name);
|
|
233
|
+
const under = name(route, `${handler.name}-under`);
|
|
234
|
+
if (handler.under) middlewares[under] = { addPrefix: { prefix: handler.under } };
|
|
232
235
|
routers[handlerName] = {
|
|
233
236
|
rule: `${hostRule(route)} && (${handler.prefixes.map((prefix) => `PathPrefix(\`${prefix}\`)`).join(" || ")})`,
|
|
234
237
|
priority: 1e4,
|
|
235
238
|
entryPoints: ["websecure"],
|
|
236
239
|
service: handlerName,
|
|
237
|
-
middlewares: [strip],
|
|
240
|
+
middlewares: handler.under ? [strip, under] : [strip],
|
|
238
241
|
tls: certificate()
|
|
239
242
|
};
|
|
240
243
|
services[handlerName] = { loadBalancer: { servers: handler.upstreams.map((upstream) => ({ url: url(upstream) })) } };
|
|
@@ -1 +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;;AAG7B,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,mBAAmB;;AAGhC,SAAgB,YAAY,MAAyB,QAAQ,KAAa;CACzE,OAAO,IAAA,uBAAA;AACR;;;;;AAMA,MAAa,eAAe,YAAY;;;;;AAMxC,MAAa,eAAe;;AAG5B,MAAa,eAAe;;AAG5B,MAAa,mBAAmB;AAChC,MAAa,iBAAiB;;AAG9B,MAAa,gBAAgB;;;;;;AAO7B,MAAa,oBAAoB;;;;;;AAOjC,MAAa,uBAAuB,GAAG,eAAe;;AAGtD,MAAM,YAAY;;AAGlB,SAAgB,UAAU,SAAiB,SAAyB;CACnE,OAAO,GAAG,QAAQ,GAAG;AACtB;;AAGA,SAAgB,qBAAqB,SAGnC;CACD,OAAO;EACN,UAAU,GAAG,eAAe,GAAG,QAAQ;EACvC,SAAS,GAAG,eAAe,GAAG,QAAQ;CACvC;AACD;;;;;;AAaA,SAAgB,cAAc,OAA2C;CACxE,OAAO;EACN,QAAQ;GAAE,iBAAiB;GAAO,oBAAoB;EAAM;EAC5D,aAAa;GACZ,KAAK;IACJ,SAAS;IACT,MAAM,EAGL,cAAc,EACb,YAAY;KAGX,IAAI,MAAM,UAAU,MAAM,cAAc,IAAI,MAAM;KAClD,QAAQ;KACR,WAAW;IACZ,EACD,EACD;GACD;GACA,WAAW,EAAE,SAAS,OAAO;GAC7B,MAAM,EAAE,SAAS,IAAI,YAAY;EAClC;EACA,MAAM,EAAE,Y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CAAE,YAAY,EAC7B,EAAE;AACH;;;;;;;AAQA,SAAgB,cAAc,GAAc,GAAkC;CAC7E,IAAI,UAAU,KAAK,UAAU,GAC5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,KAAA;CAErC,IAAI,cAAc,KAAK,cAAc,GACpC,OAAO,EAAE,aAAa,EAAE,WAAW,KAAK,EAAE,aAAa,KAAA;CAExD,MAAM,CAAC,MAAM,YAAa,UAAU,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC;CAItD,MAAM,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"}
|
|
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\tHOST_GATEWAY,\n\trouteHosts,\n\ttype Upstream,\n\tupstreamAddress,\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// A process on the host — an app `gkm dev` runs — is reached\n\t\t\t\t// through the host's gateway. Docker Desktop resolves the name\n\t\t\t\t// already; on Linux it needs saying.\n\t\t\t\textra_hosts: [`${HOST_GATEWAY}:host-gateway`],\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\t// A service of the stack by its alias on the shared network; a process on\n\t// the host — an app `gkm dev` runs — through the host's gateway.\n\tconst url = (upstream: Upstream) =>\n\t\t`http://${upstreamAddress(upstream, (service) => edgeAlias(project, service))}`;\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\t// Sent under the path the upstream mounts it on, where it names one.\n\t\t\tconst under = name(route, `${handler.name}-under`);\n\t\t\tif (handler.under) {\n\t\t\t\tmiddlewares[under] = { addPrefix: { prefix: handler.under } };\n\t\t\t}\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: handler.under ? [strip, under] : [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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,gBAAgB;;AAG7B,MAAa,uBAAuB;;;;;;;;AASpC,MAAa,mBAAmB;;AAGhC,SAAgB,YAAY,MAAyB,QAAQ,KAAa;CACzE,OAAO,IAAA,uBAAA;AACR;;;;;AAMA,MAAa,eAAe,YAAY;;;;;AAMxC,MAAa,eAAe;;AAG5B,MAAa,eAAe;;AAG5B,MAAa,mBAAmB;AAChC,MAAa,iBAAiB;;AAG9B,MAAa,gBAAgB;;;;;;AAO7B,MAAa,oBAAoB;;;;;;AAOjC,MAAa,uBAAuB,GAAG,eAAe;;AAGtD,MAAM,YAAY;;AAGlB,SAAgB,UAAU,SAAiB,SAAyB;CACnE,OAAO,GAAG,QAAQ,GAAG;AACtB;;AAGA,SAAgB,qBAAqB,SAGnC;CACD,OAAO;EACN,UAAU,GAAG,eAAe,GAAG,QAAQ;EACvC,SAAS,GAAG,eAAe,GAAG,QAAQ;CACvC;AACD;;;;;;AAaA,SAAgB,cAAc,OAA2C;CACxE,OAAO;EACN,QAAQ;GAAE,iBAAiB;GAAO,oBAAoB;EAAM;EAC5D,aAAa;GACZ,KAAK;IACJ,SAAS;IACT,MAAM,EAGL,cAAc,EACb,YAAY;KAGX,IAAI,MAAM,UAAU,MAAM,cAAc,IAAI,MAAM;KAClD,QAAQ;KACR,WAAW;IACZ,EACD,EACD;GACD;GACA,WAAW,EAAE,SAAS,OAAO;GAC7B,MAAM,EAAE,SAAS,IAAI,YAAY;EAClC;EACA,MAAM,EAAE,YAAY,OAAO;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/dist/routes/index.cjs
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
//#region src/routes/index.ts
|
|
3
3
|
/**
|
|
4
|
+
* The host's own address, from inside a container. Docker Desktop resolves
|
|
5
|
+
* it already; on Linux the proxy's compose definition maps it to the host
|
|
6
|
+
* gateway (`extra_hosts`).
|
|
7
|
+
*/
|
|
8
|
+
const HOST_GATEWAY = "host.docker.internal";
|
|
9
|
+
/** An upstream's `host:port`, as a proxy on the stack's network dials it. */
|
|
10
|
+
function upstreamAddress(upstream, service = (name) => name) {
|
|
11
|
+
return "onHost" in upstream ? `${HOST_GATEWAY}:${upstream.port}` : `${service(upstream.service)}:${upstream.port}`;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
4
14
|
* Every host a route answers on — its own, its aliases and its redirects —
|
|
5
15
|
* in that order: what DNS, certificates and the edge's claims cover.
|
|
6
16
|
*/
|
|
@@ -42,8 +52,10 @@ const EDGE_LIMITS = {
|
|
|
42
52
|
//#endregion
|
|
43
53
|
exports.EDGE_LIMITS = EDGE_LIMITS;
|
|
44
54
|
exports.EdgeRouteConflict = EdgeRouteConflict;
|
|
55
|
+
exports.HOST_GATEWAY = HOST_GATEWAY;
|
|
45
56
|
exports.NOFILE = NOFILE;
|
|
46
57
|
exports.assertRouteRenderable = assertRouteRenderable;
|
|
47
58
|
exports.routeHosts = routeHosts;
|
|
59
|
+
exports.upstreamAddress = upstreamAddress;
|
|
48
60
|
|
|
49
61
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +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"}
|
|
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/** Where a route sends its requests. */\nexport type Upstream = ServiceUpstream | HostUpstream;\n\n/** A service of the stack that a route sends to. */\nexport interface ServiceUpstream {\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/**\n * A process on the Docker host itself, outside every stack — an app `gkm dev`\n * runs, or a port a container publishes there — reached from the proxy's\n * container through the host's gateway ({@link HOST_GATEWAY}).\n */\nexport interface HostUpstream {\n\tonHost: true;\n\t/** The port it listens on, on the host. */\n\tport: number;\n}\n\n/**\n * The host's own address, from inside a container. Docker Desktop resolves\n * it already; on Linux the proxy's compose definition maps it to the host\n * gateway (`extra_hosts`).\n */\nexport const HOST_GATEWAY = 'host.docker.internal';\n\n/** An upstream's `host:port`, as a proxy on the stack's network dials it. */\nexport function upstreamAddress(\n\tupstream: Upstream,\n\t/** How a service of the stack is named where the proxy runs. */\n\tservice: (name: string) => string = (name) => name,\n): string {\n\treturn 'onHost' in upstream\n\t\t? `${HOST_GATEWAY}:${upstream.port}`\n\t\t: `${service(upstream.service)}:${upstream.port}`;\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\t/**\n\t * The site's `hosts` route, asked before each request a label makes —\n\t * `GET <path>?domain=<host>` on `upstream` — where a certificate already\n\t * covers every label (gkm's local one): a 2xx serves the label, and any\n\t * other answer is what the client gets. Rendered by Caddy (`forward_auth`);\n\t * Traefik's `forwardAuth` cannot hand the host as `domain`, so behind it\n\t * every label but `except` reaches the site, as a deployed Traefik stage's\n\t * do.\n\t */\n\thosts?: { upstream: Upstream; path: 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\t/**\n\t * A path prefix added before the request is sent — where the upstream\n\t * mounts what it answers: a dev server holding a file server's\n\t * processors, under `/__gkm/processors/<id>`.\n\t */\n\tunder?: string;\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":";;;;;;;AAoCA,MAAa,eAAe;;AAG5B,SAAgB,gBACf,UAEA,WAAqC,SAAS,MACrC;CACT,OAAO,YAAY,WAChB,GAAG,aAAa,GAAG,SAAS,SAC5B,GAAG,QAAQ,SAAS,OAAO,EAAE,GAAG,SAAS;AAC7C;;;;;AAmGA,SAAgB,WAAW,OAA4B;CACtD,OAAO;EACN,MAAM;EACN,GAAI,MAAM,WAAW,CAAC;EACtB,GAAI,MAAM,WAAW,SAAS,CAAC;CAChC;AACD;;AAiDA,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"}
|
package/dist/routes/index.d.cts
CHANGED
|
@@ -7,13 +7,35 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Pure.
|
|
9
9
|
*/
|
|
10
|
+
/** Where a route sends its requests. */
|
|
11
|
+
export type Upstream = ServiceUpstream | HostUpstream;
|
|
10
12
|
/** A service of the stack that a route sends to. */
|
|
11
|
-
export interface
|
|
13
|
+
export interface ServiceUpstream {
|
|
12
14
|
/** Its compose service name — `api`, `minio`. */
|
|
13
15
|
service: string;
|
|
14
16
|
/** The port it listens on, inside the network. */
|
|
15
17
|
port: number;
|
|
16
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* A process on the Docker host itself, outside every stack — an app `gkm dev`
|
|
21
|
+
* runs, or a port a container publishes there — reached from the proxy's
|
|
22
|
+
* container through the host's gateway ({@link HOST_GATEWAY}).
|
|
23
|
+
*/
|
|
24
|
+
export interface HostUpstream {
|
|
25
|
+
onHost: true;
|
|
26
|
+
/** The port it listens on, on the host. */
|
|
27
|
+
port: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The host's own address, from inside a container. Docker Desktop resolves
|
|
31
|
+
* it already; on Linux the proxy's compose definition maps it to the host
|
|
32
|
+
* gateway (`extra_hosts`).
|
|
33
|
+
*/
|
|
34
|
+
export declare const HOST_GATEWAY = "host.docker.internal";
|
|
35
|
+
/** An upstream's `host:port`, as a proxy on the stack's network dials it. */
|
|
36
|
+
export declare function upstreamAddress(upstream: Upstream,
|
|
37
|
+
/** How a service of the stack is named where the proxy runs. */
|
|
38
|
+
service?: (name: string) => string): string;
|
|
17
39
|
/** One public host and what answers it. */
|
|
18
40
|
export interface EdgeRoute {
|
|
19
41
|
/**
|
|
@@ -149,6 +171,19 @@ export interface EdgeWildcard {
|
|
|
149
171
|
kind: 'on-demand';
|
|
150
172
|
ask: string;
|
|
151
173
|
};
|
|
174
|
+
/**
|
|
175
|
+
* The site's `hosts` route, asked before each request a label makes —
|
|
176
|
+
* `GET <path>?domain=<host>` on `upstream` — where a certificate already
|
|
177
|
+
* covers every label (gkm's local one): a 2xx serves the label, and any
|
|
178
|
+
* other answer is what the client gets. Rendered by Caddy (`forward_auth`);
|
|
179
|
+
* Traefik's `forwardAuth` cannot hand the host as `domain`, so behind it
|
|
180
|
+
* every label but `except` reaches the site, as a deployed Traefik stage's
|
|
181
|
+
* do.
|
|
182
|
+
*/
|
|
183
|
+
hosts?: {
|
|
184
|
+
upstream: Upstream;
|
|
185
|
+
path: string;
|
|
186
|
+
};
|
|
152
187
|
}
|
|
153
188
|
/** Some of a route's paths, answered by another upstream. */
|
|
154
189
|
export interface EdgeHandler {
|
|
@@ -157,6 +192,12 @@ export interface EdgeHandler {
|
|
|
157
192
|
/** e.g. `/i/` — everything under it. */
|
|
158
193
|
prefixes: readonly string[];
|
|
159
194
|
upstreams: readonly Upstream[];
|
|
195
|
+
/**
|
|
196
|
+
* A path prefix added before the request is sent — where the upstream
|
|
197
|
+
* mounts what it answers: a dev server holding a file server's
|
|
198
|
+
* processors, under `/__gkm/processors/<id>`.
|
|
199
|
+
*/
|
|
200
|
+
under?: string;
|
|
160
201
|
}
|
|
161
202
|
/** A route with handlers and a check that would have to hold for each of them. */
|
|
162
203
|
export declare class EdgeRouteConflict extends Error {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/routes/index.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/routes/index.ts"],"mappings":";;;;;;;;;;YAUY,WAAW,kBAAkB;;iBAGxB;;EAEhB;;EAEA;;;;;;;iBAQgB;EAChB;;EAEA;;;;;;;qBAQY;;wBAGG,gBACf,UAAU,UAEV;;AAAA,WAAU;;iBAQM;;;;;EAKhB;;EAEA;;;;;EAKA;;;;;;EAMA;IAAc;IAA0B;;;;;;EAKxC,oBAAoB;;;;;EAKpB;;;;;;EAMA;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;;;EAMA;IAAkB;IAAc;;;;;;;;;EAQhC,oBAAoB;;;;;;EAMpB;IAAS;IAAc;;;;;;;;EAOvB;IAAW;IAA8B;;;EAEzC;;;;;;EAMA,WAAW;;;;;;wBAOI,WAAW,OAAO;;iBASjB;;EAEhB;;;;;;EAMA;;;;;;;;;EASA;IAAO;;IAAoB;;IAAkB;IAAmB;;;;;;;;;;;EAUhE;IAAU,UAAU;IAAU;;;;iBAId;;EAEhB;;EAEA;EACA,oBAAoB;;;;;;EAMpB;;;qBAIY,0BAA0B;WACjB;EAArB,YAAqB;;;wBAWN,sBAAsB,OAAO;;YAUjC;;;EAEP;;;;;;;;EAMA;EAAe;EAAkB;;;qBAGzB;EAAW;EAAiB;;;;;;;;qBAQ5B;EACZ,SAAS;EACT,SAAS;IAAiB;IAAc;;;;YAO7B"}
|
package/dist/routes/index.d.mts
CHANGED
|
@@ -7,13 +7,35 @@
|
|
|
7
7
|
*
|
|
8
8
|
* Pure.
|
|
9
9
|
*/
|
|
10
|
+
/** Where a route sends its requests. */
|
|
11
|
+
export type Upstream = ServiceUpstream | HostUpstream;
|
|
10
12
|
/** A service of the stack that a route sends to. */
|
|
11
|
-
export interface
|
|
13
|
+
export interface ServiceUpstream {
|
|
12
14
|
/** Its compose service name — `api`, `minio`. */
|
|
13
15
|
service: string;
|
|
14
16
|
/** The port it listens on, inside the network. */
|
|
15
17
|
port: number;
|
|
16
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* A process on the Docker host itself, outside every stack — an app `gkm dev`
|
|
21
|
+
* runs, or a port a container publishes there — reached from the proxy's
|
|
22
|
+
* container through the host's gateway ({@link HOST_GATEWAY}).
|
|
23
|
+
*/
|
|
24
|
+
export interface HostUpstream {
|
|
25
|
+
onHost: true;
|
|
26
|
+
/** The port it listens on, on the host. */
|
|
27
|
+
port: number;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The host's own address, from inside a container. Docker Desktop resolves
|
|
31
|
+
* it already; on Linux the proxy's compose definition maps it to the host
|
|
32
|
+
* gateway (`extra_hosts`).
|
|
33
|
+
*/
|
|
34
|
+
export declare const HOST_GATEWAY = "host.docker.internal";
|
|
35
|
+
/** An upstream's `host:port`, as a proxy on the stack's network dials it. */
|
|
36
|
+
export declare function upstreamAddress(upstream: Upstream,
|
|
37
|
+
/** How a service of the stack is named where the proxy runs. */
|
|
38
|
+
service?: (name: string) => string): string;
|
|
17
39
|
/** One public host and what answers it. */
|
|
18
40
|
export interface EdgeRoute {
|
|
19
41
|
/**
|
|
@@ -149,6 +171,19 @@ export interface EdgeWildcard {
|
|
|
149
171
|
kind: 'on-demand';
|
|
150
172
|
ask: string;
|
|
151
173
|
};
|
|
174
|
+
/**
|
|
175
|
+
* The site's `hosts` route, asked before each request a label makes —
|
|
176
|
+
* `GET <path>?domain=<host>` on `upstream` — where a certificate already
|
|
177
|
+
* covers every label (gkm's local one): a 2xx serves the label, and any
|
|
178
|
+
* other answer is what the client gets. Rendered by Caddy (`forward_auth`);
|
|
179
|
+
* Traefik's `forwardAuth` cannot hand the host as `domain`, so behind it
|
|
180
|
+
* every label but `except` reaches the site, as a deployed Traefik stage's
|
|
181
|
+
* do.
|
|
182
|
+
*/
|
|
183
|
+
hosts?: {
|
|
184
|
+
upstream: Upstream;
|
|
185
|
+
path: string;
|
|
186
|
+
};
|
|
152
187
|
}
|
|
153
188
|
/** Some of a route's paths, answered by another upstream. */
|
|
154
189
|
export interface EdgeHandler {
|
|
@@ -157,6 +192,12 @@ export interface EdgeHandler {
|
|
|
157
192
|
/** e.g. `/i/` — everything under it. */
|
|
158
193
|
prefixes: readonly string[];
|
|
159
194
|
upstreams: readonly Upstream[];
|
|
195
|
+
/**
|
|
196
|
+
* A path prefix added before the request is sent — where the upstream
|
|
197
|
+
* mounts what it answers: a dev server holding a file server's
|
|
198
|
+
* processors, under `/__gkm/processors/<id>`.
|
|
199
|
+
*/
|
|
200
|
+
under?: string;
|
|
160
201
|
}
|
|
161
202
|
/** A route with handlers and a check that would have to hold for each of them. */
|
|
162
203
|
export declare class EdgeRouteConflict extends Error {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/routes/index.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/routes/index.ts"],"mappings":";;;;;;;;;;YAUY,WAAW,kBAAkB;;iBAGxB;;EAEhB;;EAEA;;;;;;;iBAQgB;EAChB;;EAEA;;;;;;;qBAQY;;wBAGG,gBACf,UAAU,UAEV;;AAAA,WAAU;;iBAQM;;;;;EAKhB;;EAEA;;;;;EAKA;;;;;;EAMA;IAAc;IAA0B;;;;;;EAKxC,oBAAoB;;;;;EAKpB;;;;;;EAMA;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;;;EAMA;IAAkB;IAAc;;;;;;;;;EAQhC,oBAAoB;;;;;;EAMpB;IAAS;IAAc;;;;;;;;EAOvB;IAAW;IAA8B;;;EAEzC;;;;;;EAMA,WAAW;;;;;;wBAOI,WAAW,OAAO;;iBASjB;;EAEhB;;;;;;EAMA;;;;;;;;;EASA;IAAO;;IAAoB;;IAAkB;IAAmB;;;;;;;;;;;EAUhE;IAAU,UAAU;IAAU;;;;iBAId;;EAEhB;;EAEA;EACA,oBAAoB;;;;;;EAMpB;;;qBAIY,0BAA0B;WACjB;EAArB,YAAqB;;;wBAWN,sBAAsB,OAAO;;YAUjC;;;EAEP;;;;;;;;EAMA;EAAe;EAAkB;;;qBAGzB;EAAW;EAAiB;;;;;;;;qBAQ5B;EACZ,SAAS;EACT,SAAS;IAAiB;IAAc;;;;YAO7B"}
|
package/dist/routes/index.mjs
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
//#region src/routes/index.ts
|
|
2
2
|
/**
|
|
3
|
+
* The host's own address, from inside a container. Docker Desktop resolves
|
|
4
|
+
* it already; on Linux the proxy's compose definition maps it to the host
|
|
5
|
+
* gateway (`extra_hosts`).
|
|
6
|
+
*/
|
|
7
|
+
const HOST_GATEWAY = "host.docker.internal";
|
|
8
|
+
/** An upstream's `host:port`, as a proxy on the stack's network dials it. */
|
|
9
|
+
function upstreamAddress(upstream, service = (name) => name) {
|
|
10
|
+
return "onHost" in upstream ? `${HOST_GATEWAY}:${upstream.port}` : `${service(upstream.service)}:${upstream.port}`;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
3
13
|
* Every host a route answers on — its own, its aliases and its redirects —
|
|
4
14
|
* in that order: what DNS, certificates and the edge's claims cover.
|
|
5
15
|
*/
|
|
@@ -39,6 +49,6 @@ const EDGE_LIMITS = {
|
|
|
39
49
|
ulimits: { nofile: NOFILE }
|
|
40
50
|
};
|
|
41
51
|
//#endregion
|
|
42
|
-
export { EDGE_LIMITS, EdgeRouteConflict, NOFILE, assertRouteRenderable, routeHosts };
|
|
52
|
+
export { EDGE_LIMITS, EdgeRouteConflict, HOST_GATEWAY, NOFILE, assertRouteRenderable, routeHosts, upstreamAddress };
|
|
43
53
|
|
|
44
54
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","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"}
|
|
1
|
+
{"version":3,"file":"index.mjs","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/** Where a route sends its requests. */\nexport type Upstream = ServiceUpstream | HostUpstream;\n\n/** A service of the stack that a route sends to. */\nexport interface ServiceUpstream {\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/**\n * A process on the Docker host itself, outside every stack — an app `gkm dev`\n * runs, or a port a container publishes there — reached from the proxy's\n * container through the host's gateway ({@link HOST_GATEWAY}).\n */\nexport interface HostUpstream {\n\tonHost: true;\n\t/** The port it listens on, on the host. */\n\tport: number;\n}\n\n/**\n * The host's own address, from inside a container. Docker Desktop resolves\n * it already; on Linux the proxy's compose definition maps it to the host\n * gateway (`extra_hosts`).\n */\nexport const HOST_GATEWAY = 'host.docker.internal';\n\n/** An upstream's `host:port`, as a proxy on the stack's network dials it. */\nexport function upstreamAddress(\n\tupstream: Upstream,\n\t/** How a service of the stack is named where the proxy runs. */\n\tservice: (name: string) => string = (name) => name,\n): string {\n\treturn 'onHost' in upstream\n\t\t? `${HOST_GATEWAY}:${upstream.port}`\n\t\t: `${service(upstream.service)}:${upstream.port}`;\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\t/**\n\t * The site's `hosts` route, asked before each request a label makes —\n\t * `GET <path>?domain=<host>` on `upstream` — where a certificate already\n\t * covers every label (gkm's local one): a 2xx serves the label, and any\n\t * other answer is what the client gets. Rendered by Caddy (`forward_auth`);\n\t * Traefik's `forwardAuth` cannot hand the host as `domain`, so behind it\n\t * every label but `except` reaches the site, as a deployed Traefik stage's\n\t * do.\n\t */\n\thosts?: { upstream: Upstream; path: 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\t/**\n\t * A path prefix added before the request is sent — where the upstream\n\t * mounts what it answers: a dev server holding a file server's\n\t * processors, under `/__gkm/processors/<id>`.\n\t */\n\tunder?: string;\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":";;;;;;AAoCA,MAAa,eAAe;;AAG5B,SAAgB,gBACf,UAEA,WAAqC,SAAS,MACrC;CACT,OAAO,YAAY,WAChB,GAAG,aAAa,GAAG,SAAS,SAC5B,GAAG,QAAQ,SAAS,OAAO,EAAE,GAAG,SAAS;AAC7C;;;;;AAmGA,SAAgB,WAAW,OAA4B;CACtD,OAAO;EACN,MAAM;EACN,GAAI,MAAM,WAAW,CAAC;EACtB,GAAI,MAAM,WAAW,SAAS,CAAC;CAChC;AACD;;AAiDA,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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geekmidas/edge",
|
|
3
|
-
"version": "10.0.0-alpha.
|
|
3
|
+
"version": "10.0.0-alpha.185",
|
|
4
4
|
"description": "The edge in front of a gkm stack: routes, reverse proxies, certificates and DNS providers.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -109,7 +109,7 @@
|
|
|
109
109
|
"dependencies": {
|
|
110
110
|
"node-forge": "~1.4.2",
|
|
111
111
|
"yaml": "~2.9.1",
|
|
112
|
-
"@geekmidas/manifest": "10.0.0-alpha.
|
|
112
|
+
"@geekmidas/manifest": "10.0.0-alpha.185"
|
|
113
113
|
},
|
|
114
114
|
"peerDependencies": {
|
|
115
115
|
"@aws-sdk/client-route-53": ">=3.1136.0",
|