@dbx-tools/cli-tunnel 0.6.59 → 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 -123
  6. package/lib/src/app.js +22 -250
  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 -282
  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,292 +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 { 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
- }
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";
215
21
 
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
- */
22
+ /** Boot the gate app and return the handlers the proxy authenticates against. */
222
23
  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;
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;
292
30
  }