@dbx-tools/tunnel 0.9.4 → 0.9.6

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/src/plugin.ts CHANGED
@@ -24,18 +24,19 @@ import {
24
24
  type ResourceRequirement,
25
25
  ResourceType,
26
26
  } from "@databricks/appkit";
27
- import { plugin as appkitPlugin, brand as appkitBrand } from "@dbx-tools/appkit";
27
+ import { pluginRegistry, brandContext } from "@dbx-tools/appkit";
28
28
  import {
29
29
  auth as passwordlessAuth,
30
- storage as authStorage,
30
+ authStorage,
31
31
  type AuthorizeIdentity,
32
+ type AuthEmailOptions,
32
33
  type AuthStorageConfig,
33
34
  type AuthStorageMode,
34
35
  type PasswordlessAuthRuntime,
35
36
  } from "@dbx-tools/auth-gate";
36
- import { config as coreConfig } from "@dbx-tools/core";
37
- import type { AuthStatus } from "@dbx-tools/shared-auth";
38
- import { brand, log, string } from "@dbx-tools/shared-core";
37
+ import { configUtils } from "@dbx-tools/core";
38
+ import { AUTH_BASE_PATH } from "@dbx-tools/shared-auth";
39
+ import { brandUtils, log, stringUtils } from "@dbx-tools/shared-core";
39
40
  import type { RequestHandler } from "express";
40
41
  import { TUNNEL_CONFIG } from "./_config.ts";
41
42
  import { looksLikeEmail, matchesAllowlist } from "./allowlist.ts";
@@ -188,19 +189,8 @@ export interface AuthGateConfig extends BasePluginConfig, AuthStorageConfig {
188
189
  insecure?: boolean;
189
190
  }
190
191
 
191
- /** Branding/messaging passed to {@link AuthGateConfig.sendCode}. */
192
- export interface SendCodeOptions {
193
- subject: string;
194
- brandName: string;
195
- message: string;
196
- /**
197
- * Lifetime of the code being sent, in seconds - the RESOLVED
198
- * {@link AuthGateConfig.codeTtlSeconds}, so the email can state the real
199
- * expiry ("This code expires in 10 minutes") instead of a vague "shortly"
200
- * that drifts from the configured TTL.
201
- */
202
- codeTtlSeconds: number;
203
- }
192
+ /** Branding and expiry metadata passed to {@link AuthGateConfig.sendCode}. */
193
+ export type SendCodeOptions = AuthEmailOptions;
204
194
 
205
195
  /** Resolved gate config with env fallbacks + defaults applied. */
206
196
  export interface ResolvedAuthGateConfig {
@@ -236,7 +226,7 @@ const DEFAULTS = {
236
226
  // same identity the rest of the app presents. A host with its own
237
227
  // `branding/brand.yaml` overrides it by passing `brandName`; the shared default
238
228
  // is the fallback when nothing is configured.
239
- brandName: brand.defaultBrandContext.name,
229
+ brandName: brandUtils.defaultBrandContext.name,
240
230
  message: "Your verification code is:",
241
231
  // 30 days, the same window the cache-backed signing key is stored for.
242
232
  sessionTtlSeconds: KEY_TTL_SECONDS,
@@ -250,77 +240,73 @@ export function resolveAuthGateConfig(config: AuthGateConfig): ResolvedAuthGateC
250
240
  const storage = authStorage.resolveAuthStorageConfig({
251
241
  storage:
252
242
  config.storage ??
253
- (coreConfig.text("AUTH_STORAGE", TUNNEL_CONFIG) as AuthStorageMode | undefined),
254
- sqlitePath: config.sqlitePath ?? coreConfig.text("AUTH_SQLITE_PATH", TUNNEL_CONFIG),
243
+ (configUtils.text("TUNNEL_AUTH_STORAGE", TUNNEL_CONFIG) as AuthStorageMode | undefined),
244
+ sqlitePath: config.sqlitePath ?? configUtils.text("TUNNEL_AUTH_SQLITE_PATH", TUNNEL_CONFIG),
255
245
  });
256
- const publicDomain = coreConfig.string(config.publicDomain, "PUBLIC_DOMAIN", TUNNEL_CONFIG);
257
- const frpPublicDomain = coreConfig.text("FRP_PUBLIC_DOMAIN", TUNNEL_CONFIG);
246
+ const publicDomain = configUtils.string(
247
+ config.publicDomain,
248
+ "TUNNEL_PUBLIC_DOMAIN",
249
+ TUNNEL_CONFIG,
250
+ );
251
+ const frpPublicDomain = configUtils.text("TUNNEL_FRP_PUBLIC_DOMAIN", TUNNEL_CONFIG);
258
252
  return {
259
253
  // Both sources are unioned rather than one overriding: a deployment-wide
260
254
  // TUNNEL_AUTH_ALLOW and a per-invocation `--allow` should both grant access.
261
255
  // Hence `parseList` on each rather than `config.list`, which stops at the
262
256
  // first source that yields anything.
263
257
  allow: [
264
- ...string.parseList(config.allow),
265
- ...string.parseList(coreConfig.text(["AUTH_ALLOW", "EMAIL_AUTH_ALLOW"], TUNNEL_CONFIG)),
258
+ ...stringUtils.parseList(config.allow),
259
+ ...stringUtils.parseList(configUtils.text("TUNNEL_AUTH_ALLOW", TUNNEL_CONFIG)),
266
260
  ],
267
- subject: coreConfig.string(config.subject, "AUTH_SUBJECT", TUNNEL_CONFIG) ?? DEFAULTS.subject,
261
+ subject:
262
+ configUtils.string(config.subject, "TUNNEL_AUTH_SUBJECT", TUNNEL_CONFIG) ?? DEFAULTS.subject,
268
263
  brandName:
269
- coreConfig.string(config.brandName, "AUTH_BRAND_NAME", TUNNEL_CONFIG) ?? DEFAULTS.brandName,
270
- message: coreConfig.string(config.message, "AUTH_MESSAGE", TUNNEL_CONFIG) ?? DEFAULTS.message,
271
- sessionTtlSeconds: coreConfig.positiveInt(
264
+ configUtils.string(config.brandName, "TUNNEL_AUTH_BRAND_NAME", TUNNEL_CONFIG) ??
265
+ DEFAULTS.brandName,
266
+ message:
267
+ configUtils.string(config.message, "TUNNEL_AUTH_MESSAGE", TUNNEL_CONFIG) ?? DEFAULTS.message,
268
+ sessionTtlSeconds: configUtils.positiveInt(
272
269
  config.sessionTtlSeconds,
273
- "AUTH_SESSION_TTL",
270
+ "TUNNEL_AUTH_SESSION_TTL",
274
271
  DEFAULTS.sessionTtlSeconds,
275
272
  TUNNEL_CONFIG,
276
273
  ),
277
- codeTtlSeconds: coreConfig.positiveInt(
274
+ codeTtlSeconds: configUtils.positiveInt(
278
275
  config.codeTtlSeconds,
279
- "AUTH_CODE_TTL",
276
+ "TUNNEL_AUTH_CODE_TTL",
280
277
  DEFAULTS.codeTtlSeconds,
281
278
  TUNNEL_CONFIG,
282
279
  ),
283
280
  maxAttempts: config.maxAttempts ?? DEFAULTS.maxAttempts,
284
281
  sessionCutoffMs: resolveSessionCutoff(config.sessionCutoff),
285
282
  logoutRedirectPath: passwordlessAuth.normalizeLogoutRedirectPath(
286
- coreConfig.string(config.logoutRedirectPath, "AUTH_LOGOUT_REDIRECT", TUNNEL_CONFIG) ??
283
+ configUtils.string(config.logoutRedirectPath, "TUNNEL_AUTH_LOGOUT_REDIRECT", TUNNEL_CONFIG) ??
287
284
  DEFAULTS.logoutRedirectPath,
288
285
  ),
289
286
  publicDomain,
290
287
  publicDomains: [
291
288
  ...new Set(
292
- [publicDomain, frpPublicDomain, ...string.parseList(config.publicDomains)].filter(
289
+ [publicDomain, frpPublicDomain, ...stringUtils.parseList(config.publicDomains)].filter(
293
290
  (value): value is string => !!value,
294
291
  ),
295
292
  ),
296
293
  ],
297
294
  forwardHeaders: [
298
- ...string.parseList(config.forwardHeaders),
299
- ...string.parseList(coreConfig.text("FORWARD_HEADERS", TUNNEL_CONFIG)),
295
+ ...stringUtils.parseList(config.forwardHeaders),
296
+ ...stringUtils.parseList(configUtils.text("TUNNEL_FORWARD_HEADERS", TUNNEL_CONFIG)),
300
297
  ],
301
298
  gatePaths: [
302
- ...string.parseList(config.gatePaths),
303
- ...string.parseList(coreConfig.text("GATE_PATHS", TUNNEL_CONFIG)),
299
+ ...stringUtils.parseList(config.gatePaths),
300
+ ...stringUtils.parseList(configUtils.text("TUNNEL_GATE_PATHS", TUNNEL_CONFIG)),
304
301
  ],
305
- insecure: coreConfig.boolean(config.insecure, "INSECURE", TUNNEL_CONFIG) ?? false,
302
+ insecure: configUtils.boolean(config.insecure, "TUNNEL_INSECURE", TUNNEL_CONFIG) ?? false,
306
303
  storage: storage.mode,
307
304
  sqlitePath: storage.sqlitePath,
308
305
  };
309
306
  }
310
307
 
311
- /** The handlers the gate middleware calls in-process (returned by {@link AuthGatePlugin.exports}). */
312
- export interface AuthGateApi {
313
- /** Better Auth and compatibility routes under `/api/email/auth/*`. */
314
- handler(request: Request): Promise<Response>;
315
- /** Resolve the authorized email for request headers, or undefined. */
316
- session(headers: Headers): Promise<string | undefined>;
317
- /** The gate status payload. */
318
- status(headers: Headers): Promise<AuthStatus>;
319
- /** Whether the runtime exposes passkey enrollment and authentication. */
320
- readonly passkeysEnabled: boolean;
321
- /** Close auth storage owned by this runtime. */
322
- close(): Promise<void>;
323
- }
308
+ /** The owning passwordless runtime exposed by {@link AuthGatePlugin.exports}. */
309
+ export type AuthGateApi = PasswordlessAuthRuntime;
324
310
 
325
311
  /**
326
312
  * AppKit plugin adapting `@dbx-tools/auth-gate` to tunnel traffic. On `setup()` it registers the login
@@ -376,14 +362,14 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
376
362
 
377
363
  override async setup(): Promise<void> {
378
364
  this.resolved = resolveAuthGateConfig(this.config);
379
- if (!this.config.brandName && !coreConfig.text("AUTH_BRAND_NAME", TUNNEL_CONFIG)) {
380
- this.resolved.brandName = appkitBrand.getBrandContext().name;
365
+ if (!this.config.brandName && !configUtils.text("TUNNEL_AUTH_BRAND_NAME", TUNNEL_CONFIG)) {
366
+ this.resolved.brandName = brandContext.getBrandContext().name;
381
367
  }
382
368
 
383
369
  if (this.resolved.insecure) {
384
370
  logger.warn("insecure mode - the tunnel runs OPEN with no auth gate");
385
371
  } else {
386
- const lakebasePlugin = appkitPlugin.instance(this.context, lakebase);
372
+ const lakebasePlugin = pluginRegistry.instance(this.context, lakebase);
387
373
  const { key } = await signingKey(this.resolved.sessionCutoffMs);
388
374
  const origins = this.resolved.publicDomains.length
389
375
  ? this.resolved.publicDomains.map(authOrigin)
@@ -399,7 +385,7 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
399
385
  storage,
400
386
  baseURL: origin,
401
387
  trustedOrigins: [origin],
402
- basePath: "/api/email/auth",
388
+ basePath: AUTH_BASE_PATH,
403
389
  appName: this.resolved.brandName,
404
390
  secret: Buffer.from(key).toString("base64url"),
405
391
  sessionTtlSeconds: this.resolved.sessionTtlSeconds,
@@ -485,6 +471,7 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
485
471
  return this.runtimes.get(host) ?? this.runtimes.values().next().value;
486
472
  };
487
473
  return {
474
+ basePath: AUTH_BASE_PATH,
488
475
  passkeysEnabled: [...this.runtimes.values()].some((entry) => entry.passkeysEnabled),
489
476
  handler: (request) =>
490
477
  runtime(request.headers, request)?.handler(request) ??
@@ -499,7 +486,7 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
499
486
  }
500
487
 
501
488
  function authOrigin(publicDomain?: string): string {
502
- const value = string.trimToNull(publicDomain);
489
+ const value = stringUtils.trimToNull(publicDomain);
503
490
  if (!value) return "http://localhost";
504
491
  if (/^https?:\/\//i.test(value)) return new URL(value).origin;
505
492
  const host = value.split("/")[0]!;
package/src/portr.ts CHANGED
@@ -17,7 +17,7 @@ import { Transform } from "node:stream";
17
17
  import { StringDecoder } from "node:string_decoder";
18
18
  import { promisify } from "node:util";
19
19
 
20
- import { bin, config } from "@dbx-tools/core";
20
+ import { bin, configUtils } from "@dbx-tools/core";
21
21
  import { log } from "@dbx-tools/shared-core";
22
22
  import { TUNNEL_CONFIG } from "./_config.ts";
23
23
  import { superviseProcessForever, type ProcessSupervisor } from "./supervisor.ts";
@@ -78,8 +78,8 @@ export function resolvePortrConfig(opts: {
78
78
  port: number;
79
79
  }): PortrConfig | undefined {
80
80
  // PORTR_* is upstream portr's own namespace, so it keeps its name.
81
- const token = config.string(opts.token, "PORTR_TOKEN");
82
- const domain = config.string(opts.publicDomain, "PUBLIC_DOMAIN", TUNNEL_CONFIG);
81
+ const token = configUtils.string(opts.token, "PORTR_TOKEN");
82
+ const domain = configUtils.string(opts.publicDomain, "TUNNEL_PUBLIC_DOMAIN", TUNNEL_CONFIG);
83
83
  if (!token) return undefined;
84
84
  let subdomain = opts.subdomain;
85
85
  let server: string | undefined;
@@ -87,9 +87,9 @@ export function resolvePortrConfig(opts: {
87
87
  subdomain ??= domain.split(".")[0];
88
88
  server = domain.slice(domain.indexOf(".") + 1);
89
89
  }
90
- server ??= config.text("PORTR_SERVER");
90
+ server ??= configUtils.text("PORTR_SERVER");
91
91
  if (!subdomain || !server || server === domain) return undefined;
92
- const sshUrl = config.string(opts.sshUrl, "PORTR_SSH_URL") ?? `${server}:4444`;
92
+ const sshUrl = configUtils.string(opts.sshUrl, "PORTR_SSH_URL") ?? `${server}:4444`;
93
93
  return { subdomain, server, sshUrl, token, port: opts.port };
94
94
  }
95
95
 
@@ -44,7 +44,7 @@
44
44
 
45
45
  import { randomBytes } from "node:crypto";
46
46
  import { CacheManager } from "@databricks/appkit";
47
- import { config } from "@dbx-tools/core";
47
+ import { configUtils } from "@dbx-tools/core";
48
48
  import { log, object } from "@dbx-tools/shared-core";
49
49
  import { TUNNEL_CONFIG } from "./_config.ts";
50
50
 
@@ -86,15 +86,17 @@ interface StoredKey {
86
86
  * than not rotating.
87
87
  */
88
88
  export function resolveSessionCutoff(configured?: string | number | Date): number {
89
- const raw =
90
- configured ?? config.text(["AUTH_SESSION_CUTOFF", "AUTH_SESSION_EPOCH"], TUNNEL_CONFIG);
89
+ const raw = configured ?? configUtils.text("TUNNEL_AUTH_SESSION_CUTOFF", TUNNEL_CONFIG);
91
90
  if (raw === undefined || raw === null || raw === "") return 0;
92
91
 
93
92
  const date = object.toDate(raw);
94
93
  if (!date) {
95
- logger.warn(`ignoring unparseable ${config.name("AUTH_SESSION_CUTOFF", TUNNEL_CONFIG)}`, {
96
- value: String(raw),
97
- });
94
+ logger.warn(
95
+ `ignoring unparseable ${configUtils.name("TUNNEL_AUTH_SESSION_CUTOFF", TUNNEL_CONFIG)}`,
96
+ {
97
+ value: String(raw),
98
+ },
99
+ );
98
100
  return 0;
99
101
  }
100
102
  return clampToPast(date.getTime());
@@ -111,7 +113,7 @@ function clampToPast(cutoffMs: number): number {
111
113
  const now = Date.now();
112
114
  if (cutoffMs <= now) return cutoffMs;
113
115
  logger.warn(
114
- `${config.name("AUTH_SESSION_CUTOFF", TUNNEL_CONFIG)} is in the future - clamping to now`,
116
+ `${configUtils.name("TUNNEL_AUTH_SESSION_CUTOFF", TUNNEL_CONFIG)} is in the future - clamping to now`,
115
117
  {
116
118
  configured: new Date(cutoffMs).toISOString(),
117
119
  },
@@ -185,7 +187,7 @@ let pending: Promise<SigningKey> | undefined;
185
187
  export function signingKey(configuredCutoff?: string | number | Date): Promise<SigningKey> {
186
188
  pending ??= (async () => {
187
189
  const cutoffMs = resolveSessionCutoff(configuredCutoff);
188
- const configured = config.text("AUTH_JWT_SECRET", TUNNEL_CONFIG);
190
+ const configured = configUtils.text("TUNNEL_AUTH_JWT_SECRET", TUNNEL_CONFIG);
189
191
  if (configured) {
190
192
  return { key: new TextEncoder().encode(configured), cutoffMs };
191
193
  }
@@ -193,7 +195,7 @@ export function signingKey(configuredCutoff?: string | number | Date): Promise<S
193
195
  return { key: await loadFromCache(cutoffMs), cutoffMs };
194
196
  } catch (error) {
195
197
  logger.warn(
196
- `no ${config.name("AUTH_JWT_SECRET", TUNNEL_CONFIG)} and the cache is unavailable - using an ephemeral per-process key; sessions will not survive a restart`,
198
+ `no ${configUtils.name("TUNNEL_AUTH_JWT_SECRET", TUNNEL_CONFIG)} and the cache is unavailable - using an ephemeral per-process key; sessions will not survive a restart`,
197
199
  { error },
198
200
  );
199
201
  return { key: new Uint8Array(randomBytes(KEY_BYTES)), cutoffMs };
package/src/supervisor.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ChildProcess } from "node:child_process";
2
- import { async as asyncTools, type Logger } from "@dbx-tools/shared-core";
2
+ import { asyncUtils, type Logger } from "@dbx-tools/shared-core";
3
3
 
4
4
  const STABLE_CONNECTION_MS = 60_000;
5
5
  const DEFAULT_SHUTDOWN_GRACE_MS = 10_000;
@@ -82,10 +82,10 @@ export function superviseProcessForever(options: ProcessSupervisorOptions): Proc
82
82
  }
83
83
  if (controller.signal.aborted) return;
84
84
  if (Date.now() - startedAt >= STABLE_CONNECTION_MS) failures = 0;
85
- const delayMs = asyncTools.boundedRetryDelay(failures++, options.retryDelaysMs);
85
+ const delayMs = asyncUtils.boundedRetryDelay(failures++, options.retryDelaysMs);
86
86
  options.logger.warn(`${options.name} stopped; retrying`, { ...outcome, delayMs });
87
87
  try {
88
- await asyncTools.sleep(delayMs, controller.signal);
88
+ await asyncUtils.sleep(delayMs, controller.signal);
89
89
  } catch {
90
90
  return;
91
91
  }