@dbx-tools/tunnel 0.6.60

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,170 @@
1
+ /**
2
+ * The gate's HS256 session-signing key, persisted in AppKit's cache.
3
+ *
4
+ * The key decides whether a session COOKIE still verifies. Before this module the
5
+ * fallback was `randomBytes(32)` per process, so every restart invalidated every
6
+ * outstanding cookie and each signed-in user had to request a new code - painful
7
+ * for a tunnel, which restarts whenever the app it wraps does. Now the key is
8
+ * stored in the cache AppKit already configured (memory, or Lakebase when the
9
+ * host wires a persistent `CacheStorage`), so with persistent storage a restart
10
+ * keeps sessions alive for {@link KEY_TTL_SECONDS}.
11
+ *
12
+ * An explicitly configured `TUNNEL_AUTH_JWT_SECRET` still wins outright. That is
13
+ * the right answer for a fleet: an operator-held secret needs no shared cache and
14
+ * no convergence, and it survives a cache flush.
15
+ *
16
+ * ## get / generate / get
17
+ *
18
+ * Two instances booting at once both miss, so both would generate - and the loser
19
+ * would sign cookies with a key the winner rejects. Resolution is a re-READ after
20
+ * the write: whatever the cache holds afterwards is the key everyone adopts, so
21
+ * the instances converge on ONE value instead of trusting the one they minted.
22
+ * (`set` is not conditional in the cache API - there is no `setnx` to lean on -
23
+ * and this runs once per process, so the extra round-trip is free.)
24
+ *
25
+ * A pathological interleave can still cost a key: if A writes between B's write
26
+ * and B's re-read, B adopts A's key while A adopts its own. The cost is bounded -
27
+ * a cookie minted in that window fails to verify and the holder signs in again -
28
+ * and it cannot produce a key one instance TRUSTS but another rejects for longer
29
+ * than the window itself. Set `TUNNEL_AUTH_JWT_SECRET` to remove the race
30
+ * entirely.
31
+ *
32
+ * ## Forcing every session to end
33
+ *
34
+ * {@link resolveSessionCutoff} reads a date from `TUNNEL_AUTH_SESSION_CUTOFF` (or
35
+ * `--session-cutoff`), and that date is part of the cache KEY. Moving it forward
36
+ * makes every prior key unreachable, so every cookie signed against it stops
37
+ * verifying - the log-everyone-out switch, without having to find and flush a
38
+ * cache entry. The cutoff is also asserted against each token's `iat`, so a
39
+ * cookie that predates it is refused even if it was signed with the key that is
40
+ * somehow still current.
41
+ *
42
+ * @module
43
+ */
44
+ import { randomBytes } from "node:crypto";
45
+ import { CacheManager } from "@databricks/appkit";
46
+ import { env, log, object } from "@dbx-tools/shared-core";
47
+ import { JWT_SECRET_ENV, SESSION_CUTOFF_ENV } from "./env.js";
48
+ const logger = log.logger("tunnel:signing-key");
49
+ /**
50
+ * How long a cached signing key lives: 30 days.
51
+ *
52
+ * This is the ceiling on how long a session cookie can stay valid across
53
+ * restarts, so it is deliberately >= the default session TTL - a key that expired
54
+ * before the cookies it signed would log everyone out for no reason.
55
+ */
56
+ export const KEY_TTL_SECONDS = 30 * 24 * 60 * 60;
57
+ /** Cache-key prefix for the signing key, namespaced away from other cache use. */
58
+ const KEY_PREFIX = "tunnel:auth:signing-key:";
59
+ /** Bytes of entropy in a generated key (256-bit, matching HS256's hash width). */
60
+ const KEY_BYTES = 32;
61
+ /**
62
+ * Resolve the force-clear cutoff as epoch MILLISECONDS, or `0` when unset.
63
+ *
64
+ * Accepts whatever `object.toDate` accepts - a `Date`, `2026-08-02`, an ISO
65
+ * instant, epoch seconds or millis from `date +%s`, or a relative duration
66
+ * (`-30d`, `7 days ago`), which is the spelling an operator reaching for this
67
+ * usually wants: sign out everyone who signed in more than a month ago.
68
+ *
69
+ * An UNPARSEABLE value is ignored with a warning rather than throwing: this is
70
+ * the switch that logs a fleet back in, and failing to boot over a typo is worse
71
+ * than not rotating.
72
+ */
73
+ export function resolveSessionCutoff(configured) {
74
+ const raw = configured ?? env.text(SESSION_CUTOFF_ENV) ?? undefined;
75
+ if (raw === undefined || raw === null || raw === "")
76
+ return 0;
77
+ const date = object.toDate(raw);
78
+ if (!date) {
79
+ logger.warn(`ignoring unparseable ${env.name(SESSION_CUTOFF_ENV)}`, { value: String(raw) });
80
+ return 0;
81
+ }
82
+ return clampToPast(date.getTime());
83
+ }
84
+ /**
85
+ * Hold the cutoff at "now", because a FUTURE cutoff would refuse the sessions it
86
+ * is about to mint as well as the old ones - an app nobody can sign in to, from a
87
+ * mistyped year, with the fix hidden behind understanding this flag. Clamped, a
88
+ * future date means what an operator setting it always meant: clear everything
89
+ * outstanding, then carry on.
90
+ */
91
+ function clampToPast(cutoffMs) {
92
+ const now = Date.now();
93
+ if (cutoffMs <= now)
94
+ return cutoffMs;
95
+ logger.warn(`${env.name(SESSION_CUTOFF_ENV)} is in the future - clamping to now`, {
96
+ configured: new Date(cutoffMs).toISOString(),
97
+ });
98
+ return now;
99
+ }
100
+ /** The cache key for one cutoff, so moving the cutoff orphans every earlier key. */
101
+ function cacheKey(cutoffMs) {
102
+ return `${KEY_PREFIX}${cutoffMs}`;
103
+ }
104
+ function decode(stored) {
105
+ return new Uint8Array(Buffer.from(stored.secret, "base64url"));
106
+ }
107
+ /**
108
+ * Load the signing key for `cutoffMs` from the cache, minting and storing one
109
+ * when absent. See the module docs for why the write is followed by a re-read.
110
+ */
111
+ async function loadFromCache(cutoffMs) {
112
+ const cache = CacheManager.getInstanceSync();
113
+ const key = cacheKey(cutoffMs);
114
+ const existing = await cache.get(key);
115
+ if (existing?.secret) {
116
+ logger.info("reusing cached signing key", { createdAt: existing.createdAt });
117
+ return decode(existing);
118
+ }
119
+ const minted = {
120
+ secret: Buffer.from(randomBytes(KEY_BYTES)).toString("base64url"),
121
+ createdAt: new Date().toISOString(),
122
+ };
123
+ await cache.set(key, minted, { ttl: KEY_TTL_SECONDS });
124
+ // Re-read rather than trusting `minted`: another instance that raced this boot
125
+ // may have written first, and adopting whatever is stored is what makes the two
126
+ // converge on one key.
127
+ const settled = (await cache.get(key)) ?? minted;
128
+ logger.info("stored a new signing key", {
129
+ createdAt: settled.createdAt,
130
+ ttlSeconds: KEY_TTL_SECONDS,
131
+ adopted: settled.createdAt === minted.createdAt ? "own" : "concurrent-instance",
132
+ });
133
+ return decode(settled);
134
+ }
135
+ let pending;
136
+ /**
137
+ * The signing key for this gate, resolved once per process.
138
+ *
139
+ * Resolved ONCE, so `configuredCutoff` is honoured only on the first call - the
140
+ * plugin's `setup()` passes its resolved value there, before any request can
141
+ * reach the lazy path.
142
+ *
143
+ * `TUNNEL_AUTH_JWT_SECRET` when set, else the cache-backed key. A cache that is
144
+ * unavailable degrades to an ephemeral per-process key (the previous behaviour)
145
+ * rather than refusing to sign: the key only validates an ALREADY-issued session,
146
+ * so losing it costs sessions, never admission - a caller still needs a code
147
+ * delivered to an allow-listed address.
148
+ */
149
+ export function signingKey(configuredCutoff) {
150
+ pending ??= (async () => {
151
+ const cutoffMs = resolveSessionCutoff(configuredCutoff);
152
+ const configured = env.text(JWT_SECRET_ENV);
153
+ if (configured) {
154
+ return { key: new TextEncoder().encode(configured), cutoffMs };
155
+ }
156
+ try {
157
+ return { key: await loadFromCache(cutoffMs), cutoffMs };
158
+ }
159
+ catch (error) {
160
+ logger.warn(`no ${env.name(JWT_SECRET_ENV)} and the cache is unavailable - using an ephemeral per-process key; sessions will not survive a restart`, { error });
161
+ return { key: new Uint8Array(randomBytes(KEY_BYTES)), cutoffMs };
162
+ }
163
+ })();
164
+ return pending;
165
+ }
166
+ /** Reset the per-process key (tests, or after changing the env in-process). */
167
+ export function resetSigningKey() {
168
+ pending = undefined;
169
+ }
170
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2lnbmluZy1rZXkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvc2lnbmluZy1rZXkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztHQTBDRztBQUVILE9BQU8sRUFBRSxXQUFXLEVBQUUsTUFBTSxhQUFhLENBQUM7QUFDMUMsT0FBTyxFQUFFLFlBQVksRUFBRSxNQUFNLG9CQUFvQixDQUFDO0FBQ2xELE9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cmVkKSwgY3V0b2ZmTXMgfTtcbiAgICB9XG4gICAgdHJ5IHtcbiAgICAgIHJldHVybiB7IGtleTogYXdhaXQgbG9hZEZyb21DYWNoZShjdXRvZmZNcyksIGN1dG9mZk1zIH07XG4gICAgfSBjYXRjaCAoZXJyb3IpIHtcbiAgICAgIGxvZ2dlci53YXJuKFxuICAgICAgICBgbm8gJHtlbnYubmFtZShKV1RfU0VDUkVUX0VOVil9IGFuZCB0aGUgY2FjaGUgaXMgdW5hdmFpbGFibGUgLSB1c2luZyBhbiBlcGhlbWVyYWwgcGVyLXByb2Nlc3Mga2V5OyBzZXNzaW9ucyB3aWxsIG5vdCBzdXJ2aXZlIGEgcmVzdGFydGAsXG4gICAgICAgIHsgZXJyb3IgfSxcbiAgICAgICk7XG4gICAgICByZXR1cm4geyBrZXk6IG5ldyBVaW50OEFycmF5KHJhbmRvbUJ5dGVzKEtFWV9CWVRFUykpLCBjdXRvZmZNcyB9O1xuICAgIH1cbiAgfSkoKTtcbiAgcmV0dXJuIHBlbmRpbmc7XG59XG5cbi8qKiBSZXNldCB0aGUgcGVyLXByb2Nlc3Mga2V5ICh0ZXN0cywgb3IgYWZ0ZXIgY2hhbmdpbmcgdGhlIGVudiBpbi1wcm9jZXNzKS4gKi9cbmV4cG9ydCBmdW5jdGlvbiByZXNldFNpZ25pbmdLZXkoKTogdm9pZCB7XG4gIHBlbmRpbmcgPSB1bmRlZmluZWQ7XG59XG4iXX0=
@@ -0,0 +1 @@
1
+ {"root":["../src/allowlist.ts","../src/app.ts","../src/env.ts","../src/headers.ts","../src/interceptor.ts","../src/otp.ts","../src/plugin.ts","../src/portr.ts","../src/proxy.ts","../src/rate-limit.ts","../src/signing-key.ts","../index.ts"],"version":"5.9.3"}
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@dbx-tools/tunnel",
3
+ "repository": {
4
+ "type": "git",
5
+ "url": "git+https://github.com/reggie-db/dbx-tools.git",
6
+ "directory": "packages/node/tunnel"
7
+ },
8
+ "scripts": {
9
+ "build": "projen build",
10
+ "compile": "projen compile",
11
+ "default": "projen default",
12
+ "package": "projen package",
13
+ "post-compile": "projen post-compile",
14
+ "pre-compile": "projen pre-compile",
15
+ "prepack": "projen prepack",
16
+ "test": "projen test",
17
+ "watch": "projen watch",
18
+ "projen": "projen"
19
+ },
20
+ "devDependencies": {
21
+ "@types/bun": "^1.3.14",
22
+ "@types/node": "^24.6.0",
23
+ "typescript": "^5.9.3"
24
+ },
25
+ "dependencies": {
26
+ "@databricks/appkit": "^0.43.0",
27
+ "@dbx-tools/appkit": "0.6.60",
28
+ "@dbx-tools/core": "0.6.60",
29
+ "@dbx-tools/email": "0.6.60",
30
+ "@dbx-tools/shared-core": "0.6.60",
31
+ "@dbx-tools/shared-email": "0.6.60",
32
+ "http-proxy-3": "^1.23.3",
33
+ "jose": "^6.2.3"
34
+ },
35
+ "main": "./lib/index.js",
36
+ "license": "UNLICENSED",
37
+ "publishConfig": {
38
+ "access": "public",
39
+ "main": "./lib/index.js",
40
+ "types": "./lib/index.d.ts",
41
+ "exports": {
42
+ ".": {
43
+ "types": "./lib/index.d.ts",
44
+ "default": "./lib/index.js"
45
+ },
46
+ "./package.json": "./package.json"
47
+ }
48
+ },
49
+ "version": "0.6.60",
50
+ "types": "./lib/index.d.ts",
51
+ "type": "module",
52
+ "exports": {
53
+ ".": {
54
+ "types": "./lib/index.d.ts",
55
+ "default": "./lib/index.js"
56
+ },
57
+ "./package.json": "./package.json"
58
+ },
59
+ "files": [
60
+ "index.ts",
61
+ "src",
62
+ "lib"
63
+ ],
64
+ "dbxToolsConfig": {
65
+ "tags": [
66
+ "node"
67
+ ]
68
+ },
69
+ "//": "~~ Generated by projen. To modify, edit .projenrc.js and run \"bunx projen\"."
70
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Unified access allow-list matching for the email-OTP gate.
3
+ *
4
+ * Each pattern in the configured list is one of three shapes:
5
+ *
6
+ * - **domain shortcut** - `example.com` or `@example.com`: matches any
7
+ * address whose domain equals it. This is the gate's OWN semantic (a bare
8
+ * value means "the domain", not "the whole address"), so it is handled here.
9
+ * - **glob** - contains `*` or `?`, e.g. `*@example.com`: matched against the
10
+ * WHOLE address with shell-style wildcards.
11
+ * - **regex** - wrapped in slashes, `/.../ [flags]`: tested against the whole
12
+ * address. An invalid regex never matches (it is skipped with a warning
13
+ * rather than throwing).
14
+ *
15
+ * Only the first shape is this module's business: the glob and regex shapes are
16
+ * delegated to `@dbx-tools/shared-core`'s {@link pattern.toPattern}, which is
17
+ * where that compilation lives for every allow-list in the repo (the tunnel's
18
+ * inbound-header policy uses the same one). Matching is case-insensitive
19
+ * throughout.
20
+ *
21
+ * An EMPTY list matches nobody (fail closed): an app that enables the gate but
22
+ * configures no patterns lets no one in, which is the safe default.
23
+ *
24
+ * @module
25
+ */
26
+
27
+ import { pattern } from "@dbx-tools/shared-core";
28
+
29
+ /** True when `email` matches a single allow-list `pattern`. */
30
+ function matchesPattern(email: string, entry: string): boolean {
31
+ const trimmed = entry.trim();
32
+ if (!trimmed) return false;
33
+ const address = email.trim().toLowerCase();
34
+
35
+ // A bare value with no wildcard and no regex delimiters is a DOMAIN shortcut,
36
+ // the one shape shared-core cannot infer: there it would mean whole-string
37
+ // equality against the address, which is never what an operator writing
38
+ // `example.com` in an access list intends.
39
+ if (!trimmed.startsWith("/") && !trimmed.includes("*") && !trimmed.includes("?")) {
40
+ const domain = trimmed.replace(/^@/, "").toLowerCase();
41
+ const at = address.lastIndexOf("@");
42
+ return at >= 0 && address.slice(at + 1) === domain;
43
+ }
44
+
45
+ return pattern.toPattern(trimmed)?.(address) ?? false;
46
+ }
47
+
48
+ /**
49
+ * True when `email` is allowed by ANY pattern in `patterns`. An empty (or
50
+ * missing) list allows nobody - the gate fails closed.
51
+ */
52
+ export function matchesAllowlist(email: string, patterns: readonly string[] | undefined): boolean {
53
+ if (!email || !patterns || patterns.length === 0) return false;
54
+ return patterns.some((entry) => matchesPattern(email, entry));
55
+ }
56
+
57
+ /** Rough shape check so a clearly-invalid address is rejected before any work. */
58
+ export function looksLikeEmail(value: string): boolean {
59
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
60
+ }
package/src/app.ts ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * The tunnel gate's tiny AppKit "app" - `createApp` WITHOUT a `server()` plugin.
3
+ *
4
+ * There is no HTTP server here: the tunnel proxy is the server, and it calls the
5
+ * gate handlers in-process. `createApp` is used only for what it auto-wires:
6
+ * - `CacheManager` (Lakebase when this process can reach it, else memory) -
7
+ * which the OTP `CodeStore` and the session signing key use for storage + TTL
8
+ * eviction;
9
+ * - the `email()` transport (SMTP / outbox), primed from env, so `sendCode` can
10
+ * deliver the one-time code;
11
+ * - dbx-tools auto-configuration + branding via `@dbx-tools/appkit`.
12
+ *
13
+ * It returns the {@link AuthGateApi} the proxy drives. `sendCode` is wired here
14
+ * (the plugin can't resolve HOW to send on its own) to the email plugin's
15
+ * transport. A sign-in code is SYSTEM mail - no on-behalf-of user asked for it
16
+ * and no reply to it reaches anyone - so it sends from the email config's
17
+ * do-not-reply address (`no-reply@EMAIL_DOMAIN` unless EMAIL_SYSTEM_FROM names
18
+ * another).
19
+ *
20
+ * FAIL FAST: a gate that can't email a code is useless, so if email does not
21
+ * resolve to SMTP mode (real delivery), this throws - unless `insecure` is set
22
+ * (`--insecure` / `TUNNEL_INSECURE=true`), in which case the caller runs the
23
+ * tunnel OPEN with no gate.
24
+ *
25
+ * @module
26
+ */
27
+
28
+ import { createApp as createAppNs, lakebaseResolver } from "@dbx-tools/appkit";
29
+ import { brand as nodeBrand } from "@dbx-tools/core";
30
+ import { brand as emailBrand, email, sender, transport } from "@dbx-tools/email";
31
+ import { env, log, string } from "@dbx-tools/shared-core";
32
+ import { authGate, type AuthGateApi, type AuthGateConfig, type SendCodeOptions } from "./plugin.ts";
33
+
34
+ const logger = log.logger("tunnel:app");
35
+
36
+ /**
37
+ * A code TTL as the plain phrase the email states ("10 minutes", "45 seconds").
38
+ *
39
+ * Whole minutes read as minutes; anything else stays in seconds rather than
40
+ * rounding, so a 90-second TTL is not advertised as "1 minute" and a recipient is
41
+ * never told the code lives longer than it does.
42
+ */
43
+ export function expiresIn(seconds: number): string {
44
+ return seconds >= 60 && seconds % 60 === 0
45
+ ? string.pluralize(seconds / 60, "minute")
46
+ : string.pluralize(seconds, "second");
47
+ }
48
+
49
+ /** The parts of {@link SendCodeOptions} the code email's copy is built from. */
50
+ type CodeCopy = Pick<SendCodeOptions, "message" | "codeTtlSeconds">;
51
+
52
+ /** The reassurance line closing both parts. */
53
+ const IGNORE_LINE = "If you did not request this code, you can ignore this email.";
54
+
55
+ /**
56
+ * The HTML part's source: the full branded template, with the code as a large
57
+ * styled heading (`## ` is what makes it prominent in an inbox).
58
+ */
59
+ export function codeEmailHtmlBody(code: string, opts: CodeCopy): string {
60
+ return [
61
+ opts.message,
62
+ "",
63
+ `## ${code}`,
64
+ "",
65
+ `This code expires in ${expiresIn(opts.codeTtlSeconds)}.`,
66
+ "",
67
+ IGNORE_LINE,
68
+ ].join("\n");
69
+ }
70
+
71
+ /**
72
+ * The `text/plain` part, supplied EXPLICITLY rather than rendered from the tree
73
+ * above. Both parts say the same thing; only the line layout differs.
74
+ *
75
+ * The prompt and the code share ONE line ("Your verification code is: 123456").
76
+ * That single-line shape is what iOS, Gmail, Outlook, and Android code detection
77
+ * keys on most reliably - the heuristics look for a code in the same sentence as
78
+ * a recognized prompt, so splitting them across lines makes detection dependent
79
+ * on the client, and any blank line between them defeats it outright.
80
+ *
81
+ * The GENERATED text part cannot hold that shape at all: it is a rendering of the
82
+ * HTML, so it carries the brand header/footer and turns the code heading's CSS
83
+ * margin into blank lines, arriving as `prompt\n\n\ncode`.
84
+ *
85
+ * The code is visible text in BOTH parts, never an image, so a client scraping
86
+ * either one finds it. No trailer line follows the copy - Apple's domain-bound
87
+ * `@domain #code` footer is deliberately NOT emitted, since it constrains the
88
+ * code to one origin and is not what the broadly-compatible shape needs.
89
+ */
90
+ export function codeEmailTextBody(code: string, opts: CodeCopy): string {
91
+ return [
92
+ `${opts.message} ${code}`,
93
+ `This code expires in ${expiresIn(opts.codeTtlSeconds)}.`,
94
+ "",
95
+ IGNORE_LINE,
96
+ ].join("\n");
97
+ }
98
+
99
+ /**
100
+ * The SUBJECT line, with the code in it: `"123456 is your verification code"`.
101
+ *
102
+ * The code has to be here, not only in the body, because of what mobile autofill
103
+ * actually reads. iOS offers a code from an incoming NOTIFICATION - natively for
104
+ * Messages and Mail, and since iOS 26 for any app's notification text, which is
105
+ * what finally made Gmail work - and a notification contains the sender, the
106
+ * subject, and a short snippet. Nothing else. A code that lives in the body is
107
+ * invisible to it, however cleanly the body is formatted, which is why a perfectly
108
+ * shaped `text/plain` part still produced no autofill prompt in Gmail.
109
+ *
110
+ * `<code> is your <thing>` rather than `<thing>: <code>` because the leading code
111
+ * survives TRUNCATION: a notification and an inbox list both cut the subject, and
112
+ * the platform heuristics want the code in the same sentence as a recognized
113
+ * prompt ("code", "verification"). Putting it first keeps both intact no matter
114
+ * where the cut lands.
115
+ *
116
+ * `subject` is the configured line ("Your verification code"), lower-cased at its
117
+ * first word so the sentence reads naturally, and left ALONE when it does not look
118
+ * like the conventional phrasing - an operator who set a deliberate subject gets
119
+ * theirs with the code prefixed, not a mangled hybrid.
120
+ */
121
+ export function codeEmailSubject(code: string, subject: string): string {
122
+ const trimmed = subject.trim();
123
+ const conventional = /^your\s+/i.exec(trimmed);
124
+ const rest = conventional ? trimmed.slice(conventional[0].length) : trimmed;
125
+ return conventional ? `${code} is your ${rest}` : `${code} - ${trimmed}`;
126
+ }
127
+
128
+ /**
129
+ * The PREHEADER: the snippet beside the subject in an inbox list, and the body of
130
+ * the push notification. Carries the code for the same reason the subject does -
131
+ * it is the other half of what a notification shows - and repeats the prompt
132
+ * wording so a heuristic scanning the snippet alone finds a code next to a phrase
133
+ * it recognizes.
134
+ */
135
+ export function codeEmailPreview(code: string, opts: CodeCopy): string {
136
+ return `${opts.message} ${code}`;
137
+ }
138
+
139
+ const { createApp } = createAppNs;
140
+ const { applyLakebaseEnv } = lakebaseResolver;
141
+ const { resolveSystemSenderAddress } = sender;
142
+ const { getEmailRuntime, sendEmail } = transport;
143
+ const { emailBrandFromContext } = emailBrand;
144
+ const { loadBrandContext } = nodeBrand;
145
+
146
+ /**
147
+ * Env vars whose presence means a Lakebase database was bound to this deployment.
148
+ * `LAKEBASE_ENDPOINT` is what a Databricks App `postgres` resource binding sets;
149
+ * `PGHOST` is the local/manual spelling.
150
+ */
151
+ const LAKEBASE_ENV = ["LAKEBASE_ENDPOINT", "PGHOST"] as const;
152
+
153
+ /**
154
+ * Upper bound on resolving the Lakebase connection. The gate is in the request
155
+ * path for every visitor, so a slow workspace API must not hold up boot
156
+ * indefinitely; a memory cache is a degraded gate, an unbooted one is no gate.
157
+ */
158
+ const LAKEBASE_RESOLVE_TIMEOUT_MS = 60_000;
159
+
160
+ /**
161
+ * Fill in the Lakebase connection env AppKit's cache needs, so `CacheManager`
162
+ * chooses PERSISTENT storage instead of memory.
163
+ *
164
+ * This is what makes the gate's session signing key and outstanding one-time
165
+ * codes survive a restart. `applyLakebaseEnv` is the SHARED helper AppKit
166
+ * auto-configuration uses, so the gate gets exactly the env a pool needs -
167
+ * `LAKEBASE_ENDPOINT`, `PGHOST`, `PGDATABASE`, and `PGUSER` - rather than a
168
+ * hand-rolled subset. All four matter: `createLakebasePool()` throws without any
169
+ * one of them, and a Databricks App `postgres` resource binding supplies only the
170
+ * first. Without them the pool cannot be built, the cache silently degrades to
171
+ * in-memory, and every redeploy signs out every user (the exact symptom this
172
+ * exists to prevent).
173
+ *
174
+ * It is called here rather than left to `createApp`'s `autoConfigure` because that
175
+ * gates on a `lakebase()` plugin being registered - and this app registers none,
176
+ * having no server to mount Lakebase routes on. Calling the helper directly also
177
+ * lets the gate be stricter than `autoConfigure` is:
178
+ *
179
+ * - It runs ONLY when a Lakebase env var is present. A tunnel is a wrapper
180
+ * around someone else's app and must not invent infrastructure, so with
181
+ * nothing bound it skips rather than falling through the resolver's
182
+ * list-or-CREATE-a-project path.
183
+ * - `autoCreate: false` for the same reason, in case a project happens to exist.
184
+ * - Every failure is a WARNING, never a throw. The cache is an optimization for
185
+ * session durability; admission still requires a code delivered to an
186
+ * allow-listed address, so a gate with a memory cache is safe, just forgetful.
187
+ */
188
+ export async function resolveCacheStorageEnv(): Promise<boolean> {
189
+ if (!env.text(LAKEBASE_ENV)) {
190
+ logger.info(
191
+ `no ${env.name(LAKEBASE_ENV)} - the gate cache stays in memory; sessions and codes will not survive a restart`,
192
+ );
193
+ return false;
194
+ }
195
+ try {
196
+ const { resolved, user } = await applyLakebaseEnv(
197
+ { autoCreate: false },
198
+ AbortSignal.timeout(LAKEBASE_RESOLVE_TIMEOUT_MS),
199
+ );
200
+ logger.info("lakebase resolved for the gate cache", {
201
+ host: resolved.host,
202
+ database: resolved.database,
203
+ endpoint: resolved.endpoint,
204
+ user,
205
+ });
206
+ return true;
207
+ } catch (error) {
208
+ logger.warn(
209
+ "could not resolve lakebase - the gate cache stays in memory; sessions and codes will not survive a restart",
210
+ { error },
211
+ );
212
+ return false;
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Boot the gate app and return the API the proxy calls. Throws when email is not
218
+ * in SMTP mode (no way to deliver a code) so a misconfigured gate fails fast at
219
+ * startup rather than silently accepting nobody; the caller may catch this and
220
+ * fall back to insecure/open mode when the operator opted in.
221
+ */
222
+ export async function startGateApp(config: AuthGateConfig): Promise<AuthGateApi> {
223
+ // The host app's own brand (`branding/brand.yaml` discovered from cwd) or the
224
+ // dbx-tools default. This is the ONE brand source for the gate: it styles the
225
+ // code email (accent band, font, logo) via the email plugin AND supplies the
226
+ // display name the copy uses, so a deployment that themes its app themes its
227
+ // sign-in email with it. An explicit `brandName` still wins (see below).
228
+ const context = await loadBrandContext();
229
+
230
+ // Before `createApp`, because AppKit resolves the cache's storage during it and
231
+ // reads the connection out of `process.env` when it does. See the function's
232
+ // docs for why the gate resolves this itself.
233
+ await resolveCacheStorageEnv();
234
+
235
+ // `sendCode` delivers the OTP through the email plugin's SHARED transport, which
236
+ // the `email()` plugin primes during its `setup()` (awaited by `createApp`
237
+ // below). Using the module-level `sendEmail` avoids a circular dependency on the
238
+ // app handle's inferred type. The `From` is the SYSTEM sender: a verification
239
+ // code is machine-generated and unanswerable, so it must not arrive from a
240
+ // person's address inviting a reply.
241
+ const sendCode: NonNullable<AuthGateConfig["sendCode"]> = async (to, code, opts) => {
242
+ const from = resolveSystemSenderAddress(getEmailRuntime().config);
243
+ await sendEmail(
244
+ {
245
+ to: [to],
246
+ // The code rides in the SUBJECT and the preheader, not just the body:
247
+ // those two strings are the whole of a push notification, and a
248
+ // notification is what mobile autofill reads. See `codeEmailSubject`.
249
+ subject: codeEmailSubject(code, opts.subject),
250
+ body: codeEmailHtmlBody(code, opts),
251
+ },
252
+ from,
253
+ undefined,
254
+ { text: codeEmailTextBody(code, opts), preview: codeEmailPreview(code, opts) },
255
+ );
256
+ };
257
+
258
+ // `createApp` namespaces each plugin's exports on the handle by manifest name;
259
+ // `handle.authGate` is the in-process gate API the proxy drives.
260
+ //
261
+ // `autoConfigure: false` because {@link resolveCacheStorageEnv} above already
262
+ // ran the one piece of it this app wants (`applyLakebaseEnv`), on this app's
263
+ // terms - no auto-create, and a warning instead of a throw.
264
+ const handle = await createApp({
265
+ autoConfigure: false,
266
+ plugins: [
267
+ // Brand the code email from the resolved context, the same bridge every
268
+ // other dbx-tools email surface uses (accent + font inlined, logo only when
269
+ // it is a fetchable URL - a package-export path cannot load in an inbox).
270
+ email({ brand: emailBrandFromContext(context) }),
271
+ // `brandName` falls back to the resolved context's display name, so the
272
+ // email copy names the app rather than a generic placeholder. Spelled as an
273
+ // explicit `??` rather than a key before `...config`: commander sets
274
+ // `brandName` on the options object whether or not the flag was passed, so
275
+ // spreading it would clobber the context name with `undefined`.
276
+ authGate({ ...config, brandName: config.brandName ?? context.name, sendCode }),
277
+ ],
278
+ });
279
+
280
+ // Fail fast: the gate needs SMTP to email codes. `getEmailRuntime()` resolves to
281
+ // `mode: "file"` (outbox) or throws when no SMTP creds are configured - neither
282
+ // can deliver to a real inbox, so refuse to bring up a gate that lets nobody in.
283
+ if (getEmailRuntime().config.mode !== "smtp") {
284
+ throw new Error(
285
+ "email is not configured for SMTP delivery - the OTP gate cannot send codes. " +
286
+ "Set SMTP_HOST/SMTP_USER/SMTP_PASSWORD, or pass --insecure / TUNNEL_INSECURE=true to run the tunnel open.",
287
+ );
288
+ }
289
+
290
+ logger.info("gate app ready (no server; proxy-driven)");
291
+ return handle.authGate as AuthGateApi;
292
+ }