@stacksjs/rpx 0.11.14 → 0.11.15

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.
@@ -0,0 +1,264 @@
1
+ /**
2
+ * On-demand TLS for rpx: issue a real (Let's Encrypt, http-01) certificate for
3
+ * an unknown host the first time it's needed, gated by an `ask` callback and/or
4
+ * an `allowedSuffixes` allowlist.
5
+ *
6
+ * ## The Bun limitation this works around (verified on Bun 1.3.14 + 1.4.0)
7
+ *
8
+ * Bun.serve has **no working `SNICallback`**, and `server.reload({ tls })` does
9
+ * **NOT** update certificates at runtime. So rpx cannot mint a cert *during* the
10
+ * TLS handshake (the way Caddy's on-demand TLS does). Instead this manager
11
+ * implements on-demand as **ask-gated issuance + listener recreate**:
12
+ *
13
+ * - rpx serves the ACME `http-01` challenge from its own `:80` listener (same
14
+ * process, so the challenge token is reachable the instant we register it).
15
+ * - issuance is triggered before the HTTPS request — either reactively from
16
+ * the `:80` handler (first plaintext hit for the host), or programmatically
17
+ * via {@link OnDemandCertManager.ensureCert} (e.g. a tunnel server
18
+ * pre-warming a subdomain's cert at registration time).
19
+ * - once a cert is issued it's written to `certsDir` and added to the live SNI
20
+ * set; the manager then asks its host to rebuild the `:443` listener so the
21
+ * new cert is actually served (a sub-second `server.stop()` + re-`Bun.serve`).
22
+ *
23
+ * Concurrency: per-host in-flight de-dupe means N concurrent `ensureCert(host)`
24
+ * calls drive exactly one ACME order. Failures are logged and negatively cached
25
+ * for a short window so we don't hammer Let's Encrypt (which is rate-limited).
26
+ */
27
+ import type { Http01Store, ObtainCertificateOptions, ObtainCertificateResult } from '@stacksjs/tlsx'
28
+ import type { OnDemandTlsConfig } from './types'
29
+ import type { SniTlsEntry } from './sni'
30
+ import * as fsp from 'node:fs/promises'
31
+ import * as path from 'node:path'
32
+ import { defaultHttp01Store, obtainCertificate } from '@stacksjs/tlsx'
33
+ import { debugLog } from './utils'
34
+
35
+ /**
36
+ * The issuance function the manager calls. Defaults to tlsx's
37
+ * {@link obtainCertificate}; tests inject a stub so the suite never touches
38
+ * Let's Encrypt.
39
+ */
40
+ export type CertIssuer = (options: ObtainCertificateOptions) => Promise<ObtainCertificateResult>
41
+
42
+ export interface OnDemandCertManagerOptions {
43
+ /** Resolved on-demand config (already merged with defaults). */
44
+ config: OnDemandTlsConfig
45
+ /** Where issued PEMs are written / read. Required (resolved by the caller). */
46
+ certsDir: string
47
+ /** Initial SNI set to seed from (e.g. productionCerts already on disk). */
48
+ initial?: SniTlsEntry[]
49
+ /**
50
+ * Called after a new cert is added to the SNI set so the host can rebuild its
51
+ * `:443` listener (Bun can't hot-update tls — see file header).
52
+ */
53
+ onCertAdded?: (entries: SniTlsEntry[]) => void | Promise<void>
54
+ /** http-01 challenge store rpx's `:80` listener serves from. */
55
+ http01Store?: Http01Store
56
+ /** Inject the issuer (tests stub this). Defaults to tlsx `obtainCertificate`. */
57
+ issuer?: CertIssuer
58
+ verbose?: boolean
59
+ /** How long to negatively-cache a failed host before retrying. Default 60s. */
60
+ negativeCacheMs?: number
61
+ }
62
+
63
+ const DEFAULT_NEGATIVE_CACHE_MS = 60_000
64
+
65
+ /**
66
+ * True if `host` is covered by the `allowedSuffixes` allowlist: it equals a
67
+ * suffix, or is a subdomain of one (`a.example.com` for suffix `example.com`).
68
+ */
69
+ export function matchesAllowedSuffix(host: string, suffixes: string[] | undefined): boolean {
70
+ if (!suffixes || suffixes.length === 0)
71
+ return false
72
+ return suffixes.some((s) => {
73
+ const suffix = s.startsWith('.') ? s.slice(1) : s
74
+ return host === suffix || host.endsWith(`.${suffix}`)
75
+ })
76
+ }
77
+
78
+ /** Strict-ish hostname guard so we never feed junk Host headers into ACME. */
79
+ export function isLikelyHostname(host: string): boolean {
80
+ if (!host || host.length > 253)
81
+ return false
82
+ if (host.includes('/') || host.includes(':') || host.includes(' '))
83
+ return false
84
+ // No wildcards (http-01 can't do them) and must contain a dot (a real FQDN).
85
+ if (host.startsWith('*'))
86
+ return false
87
+ return /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(host)
88
+ }
89
+
90
+ /**
91
+ * Holds the live SNI cert set and lazily issues certs for approved hosts.
92
+ *
93
+ * The set is keyed by SNI server name; `ensureCert(host)` is the entry point for
94
+ * both the reactive `:80` path and programmatic pre-warming.
95
+ */
96
+ export class OnDemandCertManager {
97
+ private readonly config: OnDemandTlsConfig
98
+ private readonly certsDir: string
99
+ private readonly onCertAdded?: (entries: SniTlsEntry[]) => void | Promise<void>
100
+ private readonly http01Store: Http01Store
101
+ private readonly issuer: CertIssuer
102
+ private readonly verbose: boolean
103
+ private readonly negativeCacheMs: number
104
+
105
+ /** Live SNI set, keyed by server name. */
106
+ private readonly certs = new Map<string, SniTlsEntry>()
107
+ /** In-flight issuances, keyed by host — de-dupes concurrent ensureCert calls. */
108
+ private readonly inFlight = new Map<string, Promise<boolean>>()
109
+ /** host → epoch-ms until which we refuse to retry after a failure. */
110
+ private readonly negativeCache = new Map<string, number>()
111
+
112
+ constructor(opts: OnDemandCertManagerOptions) {
113
+ this.config = opts.config
114
+ this.certsDir = opts.certsDir
115
+ this.onCertAdded = opts.onCertAdded
116
+ this.http01Store = opts.http01Store ?? defaultHttp01Store
117
+ this.issuer = opts.issuer ?? obtainCertificate
118
+ this.verbose = opts.verbose ?? false
119
+ this.negativeCacheMs = opts.negativeCacheMs ?? DEFAULT_NEGATIVE_CACHE_MS
120
+ for (const e of opts.initial ?? [])
121
+ this.certs.set(e.serverName, e)
122
+ }
123
+
124
+ /** The http-01 store rpx's `:80` listener must serve challenge tokens from. */
125
+ get challengeStore(): Http01Store {
126
+ return this.http01Store
127
+ }
128
+
129
+ /** A snapshot of the current SNI set for `Bun.serve({ tls })`. */
130
+ sniEntries(): SniTlsEntry[] {
131
+ return Array.from(this.certs.values())
132
+ }
133
+
134
+ /** True if a usable cert for `host` is already loaded in the live set. */
135
+ hasCert(host: string): boolean {
136
+ return this.certs.has(host)
137
+ }
138
+
139
+ /**
140
+ * Decide whether rpx may issue a cert for `host`. A host is approved when the
141
+ * `allowedSuffixes` allowlist matches OR `ask(host)` resolves truthy. With
142
+ * neither configured, every host is refused (fail-closed, anti-abuse).
143
+ */
144
+ async isApproved(host: string): Promise<boolean> {
145
+ if (!isLikelyHostname(host))
146
+ return false
147
+ if (matchesAllowedSuffix(host, this.config.allowedSuffixes))
148
+ return true
149
+ if (this.config.ask) {
150
+ try {
151
+ return await this.config.ask(host)
152
+ }
153
+ catch (err) {
154
+ debugLog('on-demand', `ask(${host}) threw: ${(err as Error).message}`, this.verbose)
155
+ return false
156
+ }
157
+ }
158
+ return false
159
+ }
160
+
161
+ /**
162
+ * Ensure a cert exists for `host`, issuing one via ACME http-01 if needed.
163
+ *
164
+ * No-ops (resolves `true`) when a cert is already loaded. Otherwise checks
165
+ * approval, then drives issuance — de-duping concurrent calls for the same
166
+ * host so only one ACME order runs. Resolves `false` when refused or on a
167
+ * negatively-cached failure. Never throws; errors are logged + cached.
168
+ */
169
+ async ensureCert(host: string): Promise<boolean> {
170
+ if (!this.config.enabled)
171
+ return false
172
+ if (this.certs.has(host))
173
+ return true
174
+
175
+ const inFlight = this.inFlight.get(host)
176
+ if (inFlight)
177
+ return inFlight
178
+
179
+ const until = this.negativeCache.get(host)
180
+ if (until !== undefined && Date.now() < until) {
181
+ debugLog('on-demand', `${host} negatively cached for ${until - Date.now()}ms`, this.verbose)
182
+ return false
183
+ }
184
+
185
+ const promise = this.issue(host).finally(() => {
186
+ this.inFlight.delete(host)
187
+ })
188
+ this.inFlight.set(host, promise)
189
+ return promise
190
+ }
191
+
192
+ private async issue(host: string): Promise<boolean> {
193
+ // A concurrent caller may have already loaded it while we were queued.
194
+ if (this.certs.has(host))
195
+ return true
196
+
197
+ // Maybe it's already on disk (issued by a prior run) — adopt without ACME.
198
+ if (await this.loadFromDisk(host))
199
+ return true
200
+
201
+ if (!(await this.isApproved(host))) {
202
+ debugLog('on-demand', `refused issuance for ${host} (not approved)`, this.verbose)
203
+ return false
204
+ }
205
+
206
+ try {
207
+ debugLog('on-demand', `issuing cert for ${host} (staging=${this.config.staging ?? false})`, this.verbose)
208
+ const result = await this.issuer({
209
+ domains: [host],
210
+ method: 'http-01',
211
+ http01Store: this.http01Store,
212
+ email: this.config.email,
213
+ staging: this.config.staging,
214
+ })
215
+ await this.persist(host, result.fullChainPem, result.keyPem)
216
+ const entry: SniTlsEntry = { serverName: host, cert: result.fullChainPem, key: result.keyPem }
217
+ this.certs.set(host, entry)
218
+ this.negativeCache.delete(host)
219
+ debugLog('on-demand', `issued + installed cert for ${host}`, this.verbose)
220
+ await this.onCertAdded?.(this.sniEntries())
221
+ return true
222
+ }
223
+ catch (err) {
224
+ this.negativeCache.set(host, Date.now() + this.negativeCacheMs)
225
+ debugLog('on-demand', `issuance for ${host} failed: ${(err as Error).message}`, this.verbose)
226
+ return false
227
+ }
228
+ }
229
+
230
+ /** Try to load an already-present `<host>.{crt,key}` pair from `certsDir`. */
231
+ private async loadFromDisk(host: string): Promise<boolean> {
232
+ const { certPath, keyPath } = this.pathsFor(host)
233
+ try {
234
+ const [cert, key] = await Promise.all([
235
+ fsp.readFile(certPath, 'utf8'),
236
+ fsp.readFile(keyPath, 'utf8'),
237
+ ])
238
+ const entry: SniTlsEntry = { serverName: host, cert, key }
239
+ this.certs.set(host, entry)
240
+ debugLog('on-demand', `adopted existing on-disk cert for ${host}`, this.verbose)
241
+ await this.onCertAdded?.(this.sniEntries())
242
+ return true
243
+ }
244
+ catch {
245
+ return false
246
+ }
247
+ }
248
+
249
+ private pathsFor(host: string): { certPath: string, keyPath: string } {
250
+ return {
251
+ certPath: path.join(this.certsDir, `${host}.crt`),
252
+ keyPath: path.join(this.certsDir, `${host}.key`),
253
+ }
254
+ }
255
+
256
+ private async persist(host: string, certPem: string, keyPem: string): Promise<void> {
257
+ await fsp.mkdir(this.certsDir, { recursive: true }).catch(() => {})
258
+ const { certPath, keyPath } = this.pathsFor(host)
259
+ await Promise.all([
260
+ fsp.writeFile(certPath, certPem, 'utf8'),
261
+ fsp.writeFile(keyPath, keyPem, { encoding: 'utf8', mode: 0o600 }),
262
+ ])
263
+ }
264
+ }
package/src/types.ts CHANGED
@@ -113,6 +113,60 @@ export interface ProductionTlsConfig {
113
113
  certsDir?: string
114
114
  }
115
115
 
116
+ /**
117
+ * On-demand TLS: issue a real (Let's Encrypt, http-01) certificate for an
118
+ * unknown host the first time it's needed, gated by an `ask` callback and/or an
119
+ * `allowedSuffixes` allowlist to prevent abuse.
120
+ *
121
+ * ## Why this is "ask-gated issuance + listener recreate", not at-handshake
122
+ *
123
+ * Bun (verified on 1.3.14 + 1.4.0) has **no working SNICallback** and
124
+ * `server.reload({ tls })` does **not** update certs at runtime. So rpx cannot
125
+ * mint a cert during the TLS handshake the way Caddy's on-demand TLS does.
126
+ * Instead rpx:
127
+ * 1. Sees the first plaintext request for the host on its `:80` listener.
128
+ * 2. Asks `ask(host)` / checks `allowedSuffixes`; if approved, drives the
129
+ * ACME http-01 flow (serving the challenge from its own `:80`).
130
+ * 3. Writes the PEMs into `certsDir` and rebuilds the `:443` listener with the
131
+ * augmented SNI cert set (a sub-second `server.stop()` + re-`Bun.serve`).
132
+ * The subsequent HTTPS request then finds the freshly-issued cert.
133
+ *
134
+ * Issuance can also be triggered programmatically via the manager's
135
+ * `ensureCert(host)` (e.g. a tunnel server pre-warming a subdomain's cert on
136
+ * registration) so the cert exists before the first browser hit.
137
+ */
138
+ export interface OnDemandTlsConfig {
139
+ /** Master switch. On-demand TLS is opt-in; default `false`. */
140
+ enabled?: boolean
141
+ /**
142
+ * Gate issuance for a given hostname. Return `true` to allow rpx to obtain a
143
+ * cert, `false` to refuse. Combined with {@link allowedSuffixes} (a host is
144
+ * approved if either the suffix allowlist matches OR `ask` returns true). If
145
+ * neither is provided, on-demand issuance refuses every host.
146
+ */
147
+ ask?: (host: string) => boolean | Promise<boolean>
148
+ /**
149
+ * Allowlist of domain suffixes that may be auto-issued without consulting
150
+ * `ask`. A host matches a suffix when it equals it or ends with `.<suffix>`
151
+ * (so `example.com` allows `example.com` and `a.example.com`).
152
+ */
153
+ allowedSuffixes?: string[]
154
+ /** Contact email for the ACME account (recommended by Let's Encrypt). */
155
+ email?: string
156
+ /**
157
+ * Use Let's Encrypt **staging** (untrusted but un-rate-limited) instead of
158
+ * production. Default `false` (real, trusted, rate-limited certs).
159
+ */
160
+ staging?: boolean
161
+ /**
162
+ * Directory where issued PEMs are written (`<host>.crt` / `<host>.key`) and
163
+ * from which existing certs are loaded. Should match the SNI `certsDir` so
164
+ * issued certs survive restarts. Defaults to the daemon's productionCerts
165
+ * `certsDir` when wired through the daemon.
166
+ */
167
+ certsDir?: string
168
+ }
169
+
116
170
  export interface SharedProxyConfig {
117
171
  https: boolean | TlsOption
118
172
  cleanup: boolean | CleanupOptions
@@ -142,6 +196,11 @@ export interface SharedProxyConfig {
142
196
  * instead of the dev self-signed shared cert.
143
197
  */
144
198
  productionCerts?: ProductionTlsConfig
199
+ /**
200
+ * On-demand TLS: lazily issue a real cert for an unknown (but approved) host
201
+ * the first time it's needed. Opt-in — see {@link OnDemandTlsConfig}.
202
+ */
203
+ onDemandTls?: OnDemandTlsConfig
145
204
  }
146
205
 
147
206
  export type SharedProxyOptions = Partial<SharedProxyConfig>