@dbx-tools/cli-tunnel 0.6.58 → 0.6.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +1 -364
  2. package/index.ts +2 -19
  3. package/lib/index.d.ts +2 -19
  4. package/lib/index.js +2 -15
  5. package/lib/src/app.d.ts +12 -126
  6. package/lib/src/app.js +22 -260
  7. package/lib/src/cli.d.ts +19 -22
  8. package/lib/src/cli.js +143 -128
  9. package/lib/src/options.d.ts +46 -0
  10. package/lib/src/options.js +51 -0
  11. package/lib/src/proxy.d.ts +27 -37
  12. package/lib/src/proxy.js +115 -220
  13. package/lib/tsconfig.tsbuildinfo +1 -1
  14. package/package.json +15 -81
  15. package/src/app.ts +20 -291
  16. package/src/cli.ts +152 -162
  17. package/src/options.ts +85 -0
  18. package/src/proxy.ts +139 -261
  19. package/bin/dbx-tools-tunnel.ts +0 -13
  20. package/lib/bin/dbx-tools-tunnel.d.ts +0 -2
  21. package/lib/bin/dbx-tools-tunnel.js +0 -14
  22. package/lib/src/allowlist.d.ts +0 -32
  23. package/lib/src/allowlist.js +0 -57
  24. package/lib/src/env.d.ts +0 -57
  25. package/lib/src/env.js +0 -60
  26. package/lib/src/headers.d.ts +0 -108
  27. package/lib/src/headers.js +0 -140
  28. package/lib/src/otp.d.ts +0 -49
  29. package/lib/src/otp.js +0 -124
  30. package/lib/src/plugin.d.ts +0 -147
  31. package/lib/src/plugin.js +0 -138
  32. package/lib/src/portr.d.ts +0 -40
  33. package/lib/src/portr.js +0 -93
  34. package/lib/src/rate-limit.d.ts +0 -35
  35. package/lib/src/rate-limit.js +0 -53
  36. package/lib/src/signing-key.d.ts +0 -86
  37. package/lib/src/signing-key.js +0 -170
  38. package/src/allowlist.ts +0 -60
  39. package/src/env.ts +0 -72
  40. package/src/headers.ts +0 -155
  41. package/src/otp.ts +0 -137
  42. package/src/plugin.ts +0 -269
  43. package/src/portr.ts +0 -113
  44. package/src/rate-limit.ts +0 -59
  45. package/src/signing-key.ts +0 -201
package/src/app.ts CHANGED
@@ -1,301 +1,30 @@
1
1
  /**
2
- * The tunnel gate's tiny AppKit "app" - `createApp` WITHOUT a `server()` plugin.
2
+ * The GATE half of the wrapper: a server-less AppKit app whose only job is to
3
+ * expose the `authGate` handlers the proxy calls.
3
4
  *
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`.
5
+ * The in-process plugin path (`authGate` in the app's own `plugins`) has a real
6
+ * HTTP server to mount routes on. A wrapper does not - the app it fronts is a
7
+ * separate process it must not reach into - so the gate's login routes live on
8
+ * the proxy instead, and this app exists purely to give the plugin the runtime it
9
+ * needs: a `CacheManager` for the one-time-code store and signing key, and the
10
+ * sibling `email` plugin's transport for delivering a code.
12
11
  *
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.
12
+ * Lazily imported by `cli.ts`, so `dbx tunnel --insecure` (and `install` /
13
+ * `status`) never load AppKit, the Databricks SDK, or the SMTP stack.
24
14
  *
25
15
  * @module
26
16
  */
27
17
 
28
- import { getUsernameWithApiLookup } from "@databricks/appkit";
29
- import { createApp as createAppNs, lakebaseResolver } from "@dbx-tools/appkit";
30
- import { brand as nodeBrand } from "@dbx-tools/core";
31
- import { brand as emailBrand, email, sender, transport } from "@dbx-tools/email";
32
- import { env, log, string } from "@dbx-tools/shared-core";
33
- import { authGate, type AuthGateApi, type AuthGateConfig, type SendCodeOptions } from "./plugin.ts";
34
-
35
- const logger = log.logger("tunnel:app");
36
-
37
- /**
38
- * A code TTL as the plain phrase the email states ("10 minutes", "45 seconds").
39
- *
40
- * Whole minutes read as minutes; anything else stays in seconds rather than
41
- * rounding, so a 90-second TTL is not advertised as "1 minute" and a recipient is
42
- * never told the code lives longer than it does.
43
- */
44
- export function expiresIn(seconds: number): string {
45
- return seconds >= 60 && seconds % 60 === 0
46
- ? string.pluralize(seconds / 60, "minute")
47
- : string.pluralize(seconds, "second");
48
- }
49
-
50
- /** The parts of {@link SendCodeOptions} the code email's copy is built from. */
51
- type CodeCopy = Pick<SendCodeOptions, "message" | "codeTtlSeconds">;
52
-
53
- /** The reassurance line closing both parts. */
54
- const IGNORE_LINE = "If you did not request this code, you can ignore this email.";
55
-
56
- /**
57
- * The HTML part's source: the full branded template, with the code as a large
58
- * styled heading (`## ` is what makes it prominent in an inbox).
59
- */
60
- export function codeEmailHtmlBody(code: string, opts: CodeCopy): string {
61
- return [
62
- opts.message,
63
- "",
64
- `## ${code}`,
65
- "",
66
- `This code expires in ${expiresIn(opts.codeTtlSeconds)}.`,
67
- "",
68
- IGNORE_LINE,
69
- ].join("\n");
70
- }
71
-
72
- /**
73
- * The `text/plain` part, supplied EXPLICITLY rather than rendered from the tree
74
- * above. Both parts say the same thing; only the line layout differs.
75
- *
76
- * The prompt and the code share ONE line ("Your verification code is: 123456").
77
- * That single-line shape is what iOS, Gmail, Outlook, and Android code detection
78
- * keys on most reliably - the heuristics look for a code in the same sentence as
79
- * a recognized prompt, so splitting them across lines makes detection dependent
80
- * on the client, and any blank line between them defeats it outright.
81
- *
82
- * The GENERATED text part cannot hold that shape at all: it is a rendering of the
83
- * HTML, so it carries the brand header/footer and turns the code heading's CSS
84
- * margin into blank lines, arriving as `prompt\n\n\ncode`.
85
- *
86
- * The code is visible text in BOTH parts, never an image, so a client scraping
87
- * either one finds it. No trailer line follows the copy - Apple's domain-bound
88
- * `@domain #code` footer is deliberately NOT emitted, since it constrains the
89
- * code to one origin and is not what the broadly-compatible shape needs.
90
- */
91
- export function codeEmailTextBody(code: string, opts: CodeCopy): string {
92
- return [
93
- `${opts.message} ${code}`,
94
- `This code expires in ${expiresIn(opts.codeTtlSeconds)}.`,
95
- "",
96
- IGNORE_LINE,
97
- ].join("\n");
98
- }
99
-
100
- /**
101
- * The SUBJECT line, with the code in it: `"123456 is your verification code"`.
102
- *
103
- * The code has to be here, not only in the body, because of what mobile autofill
104
- * actually reads. iOS offers a code from an incoming NOTIFICATION - natively for
105
- * Messages and Mail, and since iOS 26 for any app's notification text, which is
106
- * what finally made Gmail work - and a notification contains the sender, the
107
- * subject, and a short snippet. Nothing else. A code that lives in the body is
108
- * invisible to it, however cleanly the body is formatted, which is why a perfectly
109
- * shaped `text/plain` part still produced no autofill prompt in Gmail.
110
- *
111
- * `<code> is your <thing>` rather than `<thing>: <code>` because the leading code
112
- * survives TRUNCATION: a notification and an inbox list both cut the subject, and
113
- * the platform heuristics want the code in the same sentence as a recognized
114
- * prompt ("code", "verification"). Putting it first keeps both intact no matter
115
- * where the cut lands.
116
- *
117
- * `subject` is the configured line ("Your verification code"), lower-cased at its
118
- * first word so the sentence reads naturally, and left ALONE when it does not look
119
- * like the conventional phrasing - an operator who set a deliberate subject gets
120
- * theirs with the code prefixed, not a mangled hybrid.
121
- */
122
- export function codeEmailSubject(code: string, subject: string): string {
123
- const trimmed = subject.trim();
124
- const conventional = /^your\s+/i.exec(trimmed);
125
- const rest = conventional ? trimmed.slice(conventional[0].length) : trimmed;
126
- return conventional ? `${code} is your ${rest}` : `${code} - ${trimmed}`;
127
- }
128
-
129
- /**
130
- * The PREHEADER: the snippet beside the subject in an inbox list, and the body of
131
- * the push notification. Carries the code for the same reason the subject does -
132
- * it is the other half of what a notification shows - and repeats the prompt
133
- * wording so a heuristic scanning the snippet alone finds a code next to a phrase
134
- * it recognizes.
135
- */
136
- export function codeEmailPreview(code: string, opts: CodeCopy): string {
137
- return `${opts.message} ${code}`;
138
- }
139
-
140
- const { createApp } = createAppNs;
141
- const { applyLakebaseToEnv, resolveLakebaseConnection } = lakebaseResolver;
142
- const { resolveSystemSenderAddress } = sender;
143
- const { getEmailRuntime, sendEmail } = transport;
144
- const { emailBrandFromContext } = emailBrand;
145
- const { loadBrandContext } = nodeBrand;
146
-
147
- /**
148
- * Env vars whose presence means a Lakebase database was bound to this deployment.
149
- * `LAKEBASE_ENDPOINT` is what a Databricks App `postgres` resource binding sets;
150
- * `PGHOST` is the local/manual spelling.
151
- */
152
- const LAKEBASE_ENV = ["LAKEBASE_ENDPOINT", "PGHOST"] as const;
153
-
154
- /**
155
- * Upper bound on resolving the Lakebase connection. The gate is in the request
156
- * path for every visitor, so a slow workspace API must not hold up boot
157
- * indefinitely; a memory cache is a degraded gate, an unbooted one is no gate.
158
- */
159
- const LAKEBASE_RESOLVE_TIMEOUT_MS = 60_000;
160
-
161
- /**
162
- * Fill in the Lakebase connection env AppKit's cache needs, so `CacheManager`
163
- * chooses PERSISTENT storage instead of memory.
164
- *
165
- * This is what makes the gate's session signing key and outstanding one-time
166
- * codes survive a restart, and it has to be done explicitly here. AppKit picks
167
- * Lakebase for the cache only when `createLakebasePool()` succeeds, and that pool
168
- * reads FOUR things off `process.env`: `LAKEBASE_ENDPOINT`, `PGHOST`,
169
- * `PGDATABASE`, and a username (`PGUSER`, or `DATABRICKS_CLIENT_ID` for a service
170
- * principal). A Databricks App `postgres` resource binding supplies only
171
- * `LAKEBASE_ENDPOINT`. The resolver turns that one value into the host and
172
- * database; the username is looked up separately, because missing it fails pool
173
- * construction just as hard as a missing host - and it is what a LOCAL run (a
174
- * developer on a PAT, with no `DATABRICKS_CLIENT_ID`) is always missing. Without
175
- * all four the pool cannot be built, the cache silently degrades to in-memory, and
176
- * every redeploy signs out every user (the exact symptom this exists to prevent).
177
- *
178
- * `@dbx-tools/appkit`'s `createApp` would normally do this via `autoConfigure`,
179
- * but it gates that on a `lakebase()` plugin being registered - and this app
180
- * registers none, because it has no server to mount Lakebase routes on. Calling
181
- * the resolver directly also lets the gate be stricter than `autoConfigure` is:
182
- *
183
- * - It runs ONLY when a Lakebase env var is present. A tunnel is a wrapper
184
- * around someone else's app and must not invent infrastructure, so with
185
- * nothing bound it skips rather than falling through the resolver's
186
- * list-or-CREATE-a-project path.
187
- * - `autoCreate: false` for the same reason, in case a project happens to exist.
188
- * - Every failure is a WARNING, never a throw. The cache is an optimization for
189
- * session durability; admission still requires a code delivered to an
190
- * allow-listed address, so a gate with a memory cache is safe, just forgetful.
191
- */
192
- export async function resolveCacheStorageEnv(): Promise<boolean> {
193
- if (!env.text(LAKEBASE_ENV)) {
194
- logger.info(
195
- `no ${env.name(LAKEBASE_ENV)} - the gate cache stays in memory; sessions and codes will not survive a restart`,
196
- );
197
- return false;
198
- }
199
- try {
200
- const resolved = await resolveLakebaseConnection(
201
- { autoCreate: false },
202
- AbortSignal.timeout(LAKEBASE_RESOLVE_TIMEOUT_MS),
203
- );
204
- applyLakebaseToEnv(resolved);
205
- // `??=` so an explicitly configured PGUSER stays authoritative. The lookup
206
- // falls back to the workspace API and returns undefined rather than throwing,
207
- // so a failure here just leaves the pool to find its own username.
208
- const user = await getUsernameWithApiLookup({});
209
- if (user) process.env.PGUSER ??= user;
210
- logger.info("lakebase resolved for the gate cache", {
211
- host: resolved.host,
212
- database: resolved.database,
213
- endpoint: resolved.endpoint,
214
- user: process.env.PGUSER,
215
- });
216
- return true;
217
- } catch (error) {
218
- logger.warn(
219
- "could not resolve lakebase - the gate cache stays in memory; sessions and codes will not survive a restart",
220
- { error },
221
- );
222
- return false;
223
- }
224
- }
18
+ import { appkit } from "@dbx-tools/appkit";
19
+ import { email } from "@dbx-tools/email";
20
+ import { authGate, type AuthGateApi, type AuthGateConfig } from "@dbx-tools/tunnel";
225
21
 
226
- /**
227
- * Boot the gate app and return the API the proxy calls. Throws when email is not
228
- * in SMTP mode (no way to deliver a code) so a misconfigured gate fails fast at
229
- * startup rather than silently accepting nobody; the caller may catch this and
230
- * fall back to insecure/open mode when the operator opted in.
231
- */
22
+ /** Boot the gate app and return the handlers the proxy authenticates against. */
232
23
  export async function startGateApp(config: AuthGateConfig): Promise<AuthGateApi> {
233
- // The host app's own brand (`branding/brand.yaml` discovered from cwd) or the
234
- // dbx-tools default. This is the ONE brand source for the gate: it styles the
235
- // code email (accent band, font, logo) via the email plugin AND supplies the
236
- // display name the copy uses, so a deployment that themes its app themes its
237
- // sign-in email with it. An explicit `brandName` still wins (see below).
238
- const context = await loadBrandContext();
239
-
240
- // Before `createApp`, because AppKit resolves the cache's storage during it and
241
- // reads the connection out of `process.env` when it does. See the function's
242
- // docs for why the gate resolves this itself.
243
- await resolveCacheStorageEnv();
244
-
245
- // `sendCode` delivers the OTP through the email plugin's SHARED transport, which
246
- // the `email()` plugin primes during its `setup()` (awaited by `createApp`
247
- // below). Using the module-level `sendEmail` avoids a circular dependency on the
248
- // app handle's inferred type. The `From` is the SYSTEM sender: a verification
249
- // code is machine-generated and unanswerable, so it must not arrive from a
250
- // person's address inviting a reply.
251
- const sendCode: NonNullable<AuthGateConfig["sendCode"]> = async (to, code, opts) => {
252
- const from = resolveSystemSenderAddress(getEmailRuntime().config);
253
- await sendEmail(
254
- {
255
- to: [to],
256
- // The code rides in the SUBJECT and the preheader, not just the body:
257
- // those two strings are the whole of a push notification, and a
258
- // notification is what mobile autofill reads. See `codeEmailSubject`.
259
- subject: codeEmailSubject(code, opts.subject),
260
- body: codeEmailHtmlBody(code, opts),
261
- },
262
- from,
263
- undefined,
264
- { text: codeEmailTextBody(code, opts), preview: codeEmailPreview(code, opts) },
265
- );
266
- };
267
-
268
- // `createApp` namespaces each plugin's exports on the handle by manifest name;
269
- // `handle.authGate` is the in-process gate API the proxy drives.
270
- //
271
- // `autoConfigure: false` because {@link resolveCacheStorageEnv} above already
272
- // did the one piece of it this app wants, on this app's terms.
273
- const handle = await createApp({
274
- autoConfigure: false,
275
- plugins: [
276
- // Brand the code email from the resolved context, the same bridge every
277
- // other dbx-tools email surface uses (accent + font inlined, logo only when
278
- // it is a fetchable URL - a package-export path cannot load in an inbox).
279
- email({ brand: emailBrandFromContext(context) }),
280
- // `brandName` falls back to the resolved context's display name, so the
281
- // email copy names the app rather than a generic placeholder. Spelled as an
282
- // explicit `??` rather than a key before `...config`: commander sets
283
- // `brandName` on the options object whether or not the flag was passed, so
284
- // spreading it would clobber the context name with `undefined`.
285
- authGate({ ...config, brandName: config.brandName ?? context.name, sendCode }),
286
- ],
287
- });
288
-
289
- // Fail fast: the gate needs SMTP to email codes. `getEmailRuntime()` resolves to
290
- // `mode: "file"` (outbox) or throws when no SMTP creds are configured - neither
291
- // can deliver to a real inbox, so refuse to bring up a gate that lets nobody in.
292
- if (getEmailRuntime().config.mode !== "smtp") {
293
- throw new Error(
294
- "email is not configured for SMTP delivery - the OTP gate cannot send codes. " +
295
- "Set SMTP_HOST/SMTP_USER/SMTP_PASSWORD, or pass --insecure / TUNNEL_INSECURE=true to run the tunnel open.",
296
- );
297
- }
298
-
299
- logger.info("gate app ready (no server; proxy-driven)");
300
- return handle.authGate as AuthGateApi;
24
+ // No `server()` plugin: nothing here listens. `plugins` order matters - `email`
25
+ // registers its transport before `authGate` looks for a sibling to send with.
26
+ const plugins = await appkit.createApp({ plugins: [email(), authGate(config)] });
27
+ const api = plugins.authGate as AuthGateApi | undefined;
28
+ if (!api) throw new Error("the authGate plugin exposed no api");
29
+ return api;
301
30
  }