@dbx-tools/tunnel 0.9.154 → 0.9.158

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/headers.ts CHANGED
@@ -59,7 +59,13 @@
59
59
  * @module
60
60
  */
61
61
 
62
- import { pattern, token, type Predicate } from "@dbx-tools/shared-core";
62
+ import {
63
+ type Predicate,
64
+ toPatternMatcher,
65
+ ACCESS_TOKEN_HEADER,
66
+ USER_ID_HEADER,
67
+ USER_EMAIL_HEADER,
68
+ } from "@dbx-tools/shared-core";
63
69
 
64
70
  /**
65
71
  * Headers the gate strips UNCONDITIONALLY, before the allow-list is consulted -
@@ -76,9 +82,9 @@ import { pattern, token, type Predicate } from "@dbx-tools/shared-core";
76
82
  * so a host app that does read it cannot be fed one.
77
83
  */
78
84
  export const PROTECTED_HEADERS: readonly string[] = [
79
- token.ACCESS_TOKEN_HEADER,
80
- token.USER_ID_HEADER,
81
- token.USER_EMAIL_HEADER,
85
+ ACCESS_TOKEN_HEADER,
86
+ USER_ID_HEADER,
87
+ USER_EMAIL_HEADER,
82
88
  "x-forwarded-preferred-username",
83
89
  "x-forwarded-host",
84
90
  "x-forwarded-proto",
@@ -129,7 +135,7 @@ export interface HeaderPolicy {
129
135
  */
130
136
  export function toHeaderPolicy(configured: readonly string[] = []): HeaderPolicy {
131
137
  const patterns = [...DEFAULT_FORWARD_HEADERS, ...configured];
132
- const allowed: Predicate<string> = pattern.toPatternMatcher(patterns);
138
+ const allowed: Predicate<string> = toPatternMatcher(patterns);
133
139
  const protectedNames = new Set(PROTECTED_HEADERS);
134
140
 
135
141
  const forwards = (name: string): boolean => {
@@ -17,7 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { Interceptor, InterceptorContext } from "@dbx-tools/appkit";
20
- import { errorUtils, log, object, options as sharedOptions } from "@dbx-tools/shared-core";
20
+ import { log, toError, toNumber, tcpPortOrZeroSchema } from "@dbx-tools/shared-core";
21
21
  import { z } from "zod";
22
22
  import { installFrp, resolveFrpConfig, superviseFrp, writeFrpConfig } from "./frp.ts";
23
23
  import { startPathProxy } from "./path-proxy.ts";
@@ -26,8 +26,7 @@ import { installPortr, resolvePortrConfig, supervisePortr, writePortrConfig } fr
26
26
  const logger = log.logger("tunnel:interceptor");
27
27
 
28
28
  const text = (description: string) => z.string().trim().min(1).optional().describe(description);
29
- const port = (description: string) =>
30
- sharedOptions.tcpPortOrZeroSchema.optional().describe(description);
29
+ const port = (description: string) => tcpPortOrZeroSchema.optional().describe(description);
31
30
 
32
31
  export const TunnelTransportSchema = z
33
32
  .enum(["portr", "frp", "both"])
@@ -102,7 +101,7 @@ export function resolveTunnelTransport(transport?: string): TunnelTransport {
102
101
 
103
102
  /** Resolve the public port portr should target: explicit, else the Apps contract. */
104
103
  function resolvePublicPort(port?: number): number {
105
- return port ?? object.toNumber(process.env.DATABRICKS_APP_PORT) ?? 8000;
104
+ return port ?? toNumber(process.env.DATABRICKS_APP_PORT) ?? 8000;
106
105
  }
107
106
 
108
107
  /**
@@ -179,7 +178,7 @@ export function tunnelInterceptor(
179
178
  for (const result of results) {
180
179
  if (result.status === "rejected") {
181
180
  logger.error("tunnel failed to start", {
182
- error: errorUtils.toError(result.reason),
181
+ error: toError(result.reason),
183
182
  });
184
183
  continue;
185
184
  }
package/src/login-page.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
 
9
9
  import { AUTH_BASE_PATH } from "@dbx-tools/shared-auth";
10
- import { stringUtils } from "@dbx-tools/shared-core";
10
+ import { escapeHtml, dedent } from "@dbx-tools/shared-core";
11
11
  import { LOGIN_CLIENT_SOURCE } from "./generated/_login-client.ts";
12
12
 
13
13
  /** Brand label and validated return path rendered into the standalone sign-in page. */
@@ -22,11 +22,11 @@ export interface LoginPageOptions {
22
22
 
23
23
  /** The login page HTML for a `text/html` request to a gated path with no session. */
24
24
  export function loginPageHtml(options: LoginPageOptions): string {
25
- const brand = stringUtils.escapeHtml(options.brandName);
26
- const passkeyNamePrefix = stringUtils.escapeHtml(options.passkeyNamePrefix ?? "");
27
- const returnTo = stringUtils.escapeHtml(options.returnTo);
25
+ const brand = escapeHtml(options.brandName);
26
+ const passkeyNamePrefix = escapeHtml(options.passkeyNamePrefix ?? "");
27
+ const returnTo = escapeHtml(options.returnTo);
28
28
  // prettier-ignore
29
- return stringUtils.dedent(
29
+ return dedent(
30
30
  // ============================================================================
31
31
  /*html*/`
32
32
  <!doctype html>
package/src/plugin.ts CHANGED
@@ -24,18 +24,21 @@ import {
24
24
  type ResourceRequirement,
25
25
  ResourceType,
26
26
  } from "@databricks/appkit";
27
- import { brandContext, pluginRegistry } from "@dbx-tools/appkit";
27
+ import { getBrandContext, instance } from "@dbx-tools/appkit";
28
28
  import {
29
- auth as passwordlessAuth,
30
- authStorage,
31
29
  type AuthorizeIdentity,
32
30
  type AuthEmailOptions,
33
31
  type AuthStorageMode,
34
32
  type PasswordlessAuthRuntime,
33
+ normalizeLogoutRedirectPath,
34
+ createPasswordlessAuth,
35
+ AuthStorageConfigSchema,
36
+ resolveAuthStorageConfig,
37
+ createAuthStorage,
35
38
  } from "@dbx-tools/auth-gate";
36
- import { configUtils, projectUtils } from "@dbx-tools/core";
39
+ import { configUtils, projectUtils, string, positiveInt, boolean } from "@dbx-tools/core";
37
40
  import { AUTH_BASE_PATH } from "@dbx-tools/shared-auth";
38
- import { brandUtils, log, stringUtils } from "@dbx-tools/shared-core";
41
+ import { log, defaultBrandContext, parseList, trimToNull } from "@dbx-tools/shared-core";
39
42
  import type { RequestHandler } from "express";
40
43
  import { z } from "zod";
41
44
  import { TUNNEL_CONFIG } from "./_config.ts";
@@ -95,7 +98,7 @@ const textOrList = (description: string) =>
95
98
  .optional()
96
99
  .describe(description);
97
100
 
98
- export const AuthGateConfigSchema = authStorage.AuthStorageConfigSchema.extend({
101
+ export const AuthGateConfigSchema = AuthStorageConfigSchema.extend({
99
102
  allow: textOrList("Email allow-list patterns."),
100
103
  subject: text("Verification email subject."),
101
104
  brandName: text("Verification email brand name."),
@@ -178,7 +181,7 @@ const DEFAULTS = {
178
181
  // same identity the rest of the app presents. A host with its own
179
182
  // `branding/brand.yaml` overrides it by passing `brandName`; the shared default
180
183
  // is the fallback when nothing is configured.
181
- brandName: brandUtils.defaultBrandContext.name,
184
+ brandName: defaultBrandContext.name,
182
185
  message: "Your verification code is:",
183
186
  // 30 days, the same window the cache-backed signing key is stored for.
184
187
  sessionTtlSeconds: KEY_TTL_SECONDS,
@@ -189,48 +192,38 @@ const DEFAULTS = {
189
192
 
190
193
  /** Merge {@link AuthGateConfig} over env over defaults into a resolved config. */
191
194
  export function resolveAuthGateConfig(config: AuthGateConfig): ResolvedAuthGateConfig {
192
- const storage = authStorage.resolveAuthStorageConfig({
195
+ const storage = resolveAuthStorageConfig({
193
196
  storage:
194
197
  config.storage ??
195
198
  (configUtils.text("TUNNEL_AUTH_STORAGE", TUNNEL_CONFIG) as AuthStorageMode | undefined),
196
199
  sqlitePath: config.sqlitePath ?? configUtils.text("TUNNEL_AUTH_SQLITE_PATH", TUNNEL_CONFIG),
197
200
  });
198
- const publicDomain = configUtils.string(
199
- config.publicDomain,
200
- "TUNNEL_PUBLIC_DOMAIN",
201
- TUNNEL_CONFIG,
202
- );
201
+ const publicDomain = string(config.publicDomain, "TUNNEL_PUBLIC_DOMAIN", TUNNEL_CONFIG);
203
202
  const frpPublicDomain = configUtils.text("TUNNEL_FRP_PUBLIC_DOMAIN", TUNNEL_CONFIG);
204
203
  const brandName =
205
- configUtils.string(config.brandName, "TUNNEL_AUTH_BRAND_NAME", TUNNEL_CONFIG) ??
206
- DEFAULTS.brandName;
204
+ string(config.brandName, "TUNNEL_AUTH_BRAND_NAME", TUNNEL_CONFIG) ?? DEFAULTS.brandName;
207
205
  return {
208
206
  // Both sources are unioned rather than one overriding: a deployment-wide
209
207
  // TUNNEL_AUTH_ALLOW and a per-invocation `--allow` should both grant access.
210
208
  // Hence `parseList` on each rather than `config.list`, which stops at the
211
209
  // first source that yields anything.
212
210
  allow: [
213
- ...stringUtils.parseList(config.allow),
214
- ...stringUtils.parseList(configUtils.text("TUNNEL_AUTH_ALLOW", TUNNEL_CONFIG)),
211
+ ...parseList(config.allow),
212
+ ...parseList(configUtils.text("TUNNEL_AUTH_ALLOW", TUNNEL_CONFIG)),
215
213
  ],
216
- subject:
217
- configUtils.string(config.subject, "TUNNEL_AUTH_SUBJECT", TUNNEL_CONFIG) ?? DEFAULTS.subject,
214
+ subject: string(config.subject, "TUNNEL_AUTH_SUBJECT", TUNNEL_CONFIG) ?? DEFAULTS.subject,
218
215
  brandName,
219
216
  passkeyNamePrefix:
220
- configUtils.string(
221
- config.passkeyNamePrefix,
222
- "TUNNEL_AUTH_PASSKEY_NAME_PREFIX",
223
- TUNNEL_CONFIG,
224
- ) ?? projectUtils.name(),
225
- message:
226
- configUtils.string(config.message, "TUNNEL_AUTH_MESSAGE", TUNNEL_CONFIG) ?? DEFAULTS.message,
227
- sessionTtlSeconds: configUtils.positiveInt(
217
+ string(config.passkeyNamePrefix, "TUNNEL_AUTH_PASSKEY_NAME_PREFIX", TUNNEL_CONFIG) ??
218
+ projectUtils.name(),
219
+ message: string(config.message, "TUNNEL_AUTH_MESSAGE", TUNNEL_CONFIG) ?? DEFAULTS.message,
220
+ sessionTtlSeconds: positiveInt(
228
221
  config.sessionTtlSeconds,
229
222
  "TUNNEL_AUTH_SESSION_TTL",
230
223
  DEFAULTS.sessionTtlSeconds,
231
224
  TUNNEL_CONFIG,
232
225
  ),
233
- codeTtlSeconds: configUtils.positiveInt(
226
+ codeTtlSeconds: positiveInt(
234
227
  config.codeTtlSeconds,
235
228
  "TUNNEL_AUTH_CODE_TTL",
236
229
  DEFAULTS.codeTtlSeconds,
@@ -238,27 +231,27 @@ export function resolveAuthGateConfig(config: AuthGateConfig): ResolvedAuthGateC
238
231
  ),
239
232
  maxAttempts: config.maxAttempts ?? DEFAULTS.maxAttempts,
240
233
  sessionCutoffMs: resolveSessionCutoff(config.sessionCutoff),
241
- logoutRedirectPath: passwordlessAuth.normalizeLogoutRedirectPath(
242
- configUtils.string(config.logoutRedirectPath, "TUNNEL_AUTH_LOGOUT_REDIRECT", TUNNEL_CONFIG) ??
234
+ logoutRedirectPath: normalizeLogoutRedirectPath(
235
+ string(config.logoutRedirectPath, "TUNNEL_AUTH_LOGOUT_REDIRECT", TUNNEL_CONFIG) ??
243
236
  DEFAULTS.logoutRedirectPath,
244
237
  ),
245
238
  publicDomain,
246
239
  publicDomains: [
247
240
  ...new Set(
248
- [publicDomain, frpPublicDomain, ...stringUtils.parseList(config.publicDomains)].filter(
241
+ [publicDomain, frpPublicDomain, ...parseList(config.publicDomains)].filter(
249
242
  (value): value is string => !!value,
250
243
  ),
251
244
  ),
252
245
  ],
253
246
  forwardHeaders: [
254
- ...stringUtils.parseList(config.forwardHeaders),
255
- ...stringUtils.parseList(configUtils.text("TUNNEL_FORWARD_HEADERS", TUNNEL_CONFIG)),
247
+ ...parseList(config.forwardHeaders),
248
+ ...parseList(configUtils.text("TUNNEL_FORWARD_HEADERS", TUNNEL_CONFIG)),
256
249
  ],
257
250
  gatePaths: [
258
- ...stringUtils.parseList(config.gatePaths),
259
- ...stringUtils.parseList(configUtils.text("TUNNEL_GATE_PATHS", TUNNEL_CONFIG)),
251
+ ...parseList(config.gatePaths),
252
+ ...parseList(configUtils.text("TUNNEL_GATE_PATHS", TUNNEL_CONFIG)),
260
253
  ],
261
- insecure: configUtils.boolean(config.insecure, "TUNNEL_INSECURE", TUNNEL_CONFIG) ?? false,
254
+ insecure: boolean(config.insecure, "TUNNEL_INSECURE", TUNNEL_CONFIG) ?? false,
262
255
  storage: storage.mode,
263
256
  sqlitePath: storage.sqlitePath,
264
257
  };
@@ -305,7 +298,7 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
305
298
  private readonly runtimes = new Map<string, PasswordlessAuthRuntime>();
306
299
 
307
300
  static getResourceRequirements(config: AuthGateConfig): ResourceRequirement[] {
308
- if (authStorage.resolveAuthStorageConfig(config).mode !== "lakebase") return [];
301
+ if (resolveAuthStorageConfig(config).mode !== "lakebase") return [];
309
302
  return [
310
303
  {
311
304
  type: ResourceType.POSTGRES,
@@ -325,7 +318,7 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
325
318
  override async setup(): Promise<void> {
326
319
  this.resolved = resolveAuthGateConfig(this.config);
327
320
  if (!this.config.brandName && !configUtils.text("TUNNEL_AUTH_BRAND_NAME", TUNNEL_CONFIG)) {
328
- this.resolved.brandName = brandContext.getBrandContext().name;
321
+ this.resolved.brandName = getBrandContext().name;
329
322
  }
330
323
 
331
324
  if (this.resolved.insecure) {
@@ -340,12 +333,12 @@ export class AuthGatePlugin extends Plugin<AuthGateConfig> {
340
333
  // before mounting the gate. Request-scoped `asUser` context cannot change
341
334
  // the storage identity after this point.
342
335
  this.context?.onLifecycle("setup:complete", async () => {
343
- const pool = pluginRegistry.instance(this.context, lakebase)?.exports().pool;
336
+ const pool = instance(this.context, lakebase)?.exports().pool;
344
337
  for (const origin of new Set(origins)) {
345
- const storage = await authStorage.createAuthStorage(this.resolved, pool);
338
+ const storage = await createAuthStorage(this.resolved, pool);
346
339
  this.runtimes.set(
347
340
  new URL(origin).hostname.toLowerCase(),
348
- await passwordlessAuth.createPasswordlessAuth({
341
+ await createPasswordlessAuth({
349
342
  storage,
350
343
  baseURL: origin,
351
344
  trustedOrigins: [origin],
@@ -460,7 +453,7 @@ function _authHostname(headers?: Headers, request?: Request): string | undefined
460
453
  }
461
454
 
462
455
  function authOrigin(publicDomain?: string): string {
463
- const value = stringUtils.trimToNull(publicDomain);
456
+ const value = trimToNull(publicDomain);
464
457
  if (!value) return "http://localhost";
465
458
  if (/^https?:\/\//i.test(value)) return new URL(value).origin;
466
459
  const host = value.split("/")[0]!;
package/src/portr.ts CHANGED
@@ -12,9 +12,9 @@
12
12
  import { mkdir, writeFile } from "node:fs/promises";
13
13
  import os from "node:os";
14
14
  import { delimiter, join } from "node:path";
15
- import { bin, configUtils, exec } from "@dbx-tools/core";
16
- import type { ChildProcessResult, ChildProcessTerminationOptions } from "@dbx-tools/core/exec";
17
- import { log, options as sharedOptions, stringUtils } from "@dbx-tools/shared-core";
15
+ import { ensure, parseVersion, string, text, spawnSync, spawn } from "@dbx-tools/core";
16
+ import type { ChildProcessResult, ChildProcessTerminationOptions } from "@dbx-tools/core";
17
+ import { log, tcpPortOrZeroSchema, dedent } from "@dbx-tools/shared-core";
18
18
  import { z } from "zod";
19
19
  import { TUNNEL_CONFIG } from "./_config.ts";
20
20
  import { superviseProcessForever, type ProcessSupervisor } from "./supervisor.ts";
@@ -52,7 +52,7 @@ export const PortrOptionsSchema = z
52
52
  subdomain: z.string().trim().min(1).optional().describe("Portr subdomain."),
53
53
  sshUrl: z.string().trim().min(1).optional().describe("Portr SSH control endpoint."),
54
54
  token: z.string().trim().min(1).optional().describe("Portr authentication token."),
55
- port: sharedOptions.tcpPortOrZeroSchema.describe("Public listener port."),
55
+ port: tcpPortOrZeroSchema.describe("Public listener port."),
56
56
  })
57
57
  .strict()
58
58
  .describe("Portr tunnel resolution options.");
@@ -68,8 +68,8 @@ export type PortrOptions = z.input<typeof PortrOptionsSchema>;
68
68
  export function resolvePortrConfig(opts: PortrOptions): PortrConfig | undefined {
69
69
  const options = PortrOptionsSchema.parse(opts);
70
70
  // PORTR_* is upstream portr's own namespace, so it keeps its name.
71
- const token = configUtils.string(options.token, "PORTR_TOKEN");
72
- const domain = configUtils.string(options.publicDomain, "TUNNEL_PUBLIC_DOMAIN", TUNNEL_CONFIG);
71
+ const token = string(options.token, "PORTR_TOKEN");
72
+ const domain = string(options.publicDomain, "TUNNEL_PUBLIC_DOMAIN", TUNNEL_CONFIG);
73
73
  if (!token) return undefined;
74
74
  let subdomain = options.subdomain;
75
75
  let server: string | undefined;
@@ -77,9 +77,9 @@ export function resolvePortrConfig(opts: PortrOptions): PortrConfig | undefined
77
77
  subdomain ??= domain.split(".")[0];
78
78
  server = domain.slice(domain.indexOf(".") + 1);
79
79
  }
80
- server ??= configUtils.text("PORTR_SERVER");
80
+ server ??= text("PORTR_SERVER");
81
81
  if (!subdomain || !server || server === domain) return undefined;
82
- const sshUrl = configUtils.string(options.sshUrl, "PORTR_SSH_URL") ?? `${server}:4444`;
82
+ const sshUrl = string(options.sshUrl, "PORTR_SSH_URL") ?? `${server}:4444`;
83
83
  return { subdomain, server, sshUrl, token, port: options.port };
84
84
  }
85
85
 
@@ -106,13 +106,13 @@ function portrDownloadUrl(): string {
106
106
  /** Install portr when absent and return the environment used by its process. */
107
107
  export async function installPortr(options: PortrInstallOptions = {}): Promise<NodeJS.ProcessEnv> {
108
108
  const homeDir = options.homeDir ?? os.homedir();
109
- const context = await bin.ensure("portr", portrDownloadUrl, {
109
+ const context = await ensure("portr", portrDownloadUrl, {
110
110
  autoUnpackage: true,
111
111
  homeDir,
112
112
  minVersion: PORTR_MIN_VERSION,
113
113
  selector: ({ source }) => join(source, "portr"),
114
114
  versionParser: (output) => {
115
- const version = bin.parseVersion(output);
115
+ const version = parseVersion(output);
116
116
  return version === PORTR_VERSION ? version : undefined;
117
117
  },
118
118
  });
@@ -148,7 +148,7 @@ export async function writePortrConfig(
148
148
  `
149
149
  // ============================================================================
150
150
  );
151
- const contents = stringUtils.dedent(template, { trimEnd: false });
151
+ const contents = dedent(template, { trimEnd: false });
152
152
  await writeFile(path, contents);
153
153
  }
154
154
 
@@ -159,14 +159,14 @@ export function startPortr(
159
159
  options: ChildProcessTerminationOptions = {},
160
160
  ): ChildProcessResult {
161
161
  // Reclaim the subdomain from any portr left by a previous boot in this container.
162
- exec.spawnSync("pkill", ["-x", "portr"], {
162
+ spawnSync("pkill", ["-x", "portr"], {
163
163
  stdin: "ignore",
164
164
  stdout: "ignore",
165
165
  stderr: "ignore",
166
166
  });
167
167
 
168
168
  logger.info(`portr tunneling https://${config.subdomain}.${config.server} -> :${config.port}`);
169
- return exec.spawn("portr", ["start"], {
169
+ return spawn("portr", ["start"], {
170
170
  ...options,
171
171
  env: childEnv,
172
172
  stdin: "inherit",
@@ -1,6 +1,6 @@
1
1
  /** Request-scoped trace tags derived from the configured tunnel transport. */
2
2
  import type { IncomingMessage } from "node:http";
3
- import { net } from "@dbx-tools/shared-core";
3
+ import { ipInCidr } from "@dbx-tools/shared-core";
4
4
 
5
5
  import { resolveFrpConfig } from "./frp.ts";
6
6
  import { resolveTunnelTransport } from "./interceptor.ts";
@@ -26,7 +26,7 @@ function isLoopbackRequest(request: IncomingMessage): boolean {
26
26
  const normalized = remoteAddress.startsWith("::ffff:")
27
27
  ? remoteAddress.slice("::ffff:".length)
28
28
  : remoteAddress;
29
- return Boolean(net.ipInCidr(normalized, "127.0.0.0/8") || net.ipInCidr(normalized, "::1/128"));
29
+ return Boolean(ipInCidr(normalized, "127.0.0.0/8") || ipInCidr(normalized, "::1/128"));
30
30
  }
31
31
 
32
32
  /**
@@ -44,8 +44,8 @@
44
44
 
45
45
  import { randomBytes } from "node:crypto";
46
46
  import { CacheManager } from "@databricks/appkit";
47
- import { configUtils } from "@dbx-tools/core";
48
- import { errorUtils, log, object } from "@dbx-tools/shared-core";
47
+ import { configUtils, text } from "@dbx-tools/core";
48
+ import { log, toError, toDate } from "@dbx-tools/shared-core";
49
49
  import { TUNNEL_CONFIG } from "./_config.ts";
50
50
 
51
51
  const logger = log.logger("tunnel:signing-key");
@@ -86,10 +86,10 @@ interface StoredKey {
86
86
  * than not rotating.
87
87
  */
88
88
  export function resolveSessionCutoff(configured?: string | number | Date): number {
89
- const raw = configured ?? configUtils.text("TUNNEL_AUTH_SESSION_CUTOFF", TUNNEL_CONFIG);
89
+ const raw = configured ?? text("TUNNEL_AUTH_SESSION_CUTOFF", TUNNEL_CONFIG);
90
90
  if (raw === undefined || raw === null || raw === "") return 0;
91
91
 
92
- const date = object.toDate(raw);
92
+ const date = toDate(raw);
93
93
  if (!date) {
94
94
  logger.warn(
95
95
  `ignoring unparseable ${configUtils.name("TUNNEL_AUTH_SESSION_CUTOFF", TUNNEL_CONFIG)}`,
@@ -187,7 +187,7 @@ let pending: Promise<SigningKey> | undefined;
187
187
  export function signingKey(configuredCutoff?: string | number | Date): Promise<SigningKey> {
188
188
  pending ??= (async () => {
189
189
  const cutoffMs = resolveSessionCutoff(configuredCutoff);
190
- const configured = configUtils.text("TUNNEL_AUTH_JWT_SECRET", TUNNEL_CONFIG);
190
+ const configured = text("TUNNEL_AUTH_JWT_SECRET", TUNNEL_CONFIG);
191
191
  if (configured) {
192
192
  return { key: new TextEncoder().encode(configured), cutoffMs };
193
193
  }
@@ -196,7 +196,7 @@ export function signingKey(configuredCutoff?: string | number | Date): Promise<S
196
196
  } catch (error) {
197
197
  logger.warn(
198
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`,
199
- { error: errorUtils.toError(error) },
199
+ { error: toError(error) },
200
200
  );
201
201
  return { key: new Uint8Array(randomBytes(KEY_BYTES)), cutoffMs };
202
202
  }
package/src/supervisor.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { exec } from "@dbx-tools/core";
2
- import type { ChildProcessResult } from "@dbx-tools/core/exec";
3
- import { asyncUtils, errorUtils, type Logger } from "@dbx-tools/shared-core";
1
+ import { onParentTerminationSignal } from "@dbx-tools/core";
2
+ import type { ChildProcessResult } from "@dbx-tools/core";
3
+ import { type Logger, boundedRetryDelay, sleep, toError } from "@dbx-tools/shared-core";
4
4
 
5
5
  const STABLE_CONNECTION_MS = 60_000;
6
6
  /** How long to wait after a child start before the first public liveness probe. */
@@ -53,7 +53,7 @@ export function superviseProcessForever(options: ProcessSupervisorOptions): Proc
53
53
  if (!stoppingChild) return Promise.resolve();
54
54
  stopping ??= stoppingChild.shutdown().catch((error) => {
55
55
  options.logger.error(`${options.name} did not stop`, {
56
- error: errorUtils.toError(error),
56
+ error: toError(error),
57
57
  });
58
58
  });
59
59
  return stopping;
@@ -73,7 +73,7 @@ export function superviseProcessForever(options: ProcessSupervisorOptions): Proc
73
73
  void terminateChild();
74
74
  };
75
75
  process.once("exit", onProcessExit);
76
- const stopParentSignal = exec.onParentTerminationSignal(() => {
76
+ const stopParentSignal = onParentTerminationSignal(() => {
77
77
  abortRestartLoop();
78
78
  });
79
79
 
@@ -87,15 +87,15 @@ export function superviseProcessForever(options: ProcessSupervisorOptions): Proc
87
87
  stopping = undefined;
88
88
  outcome = await processOutcome(child, controller.signal, options);
89
89
  } catch (error) {
90
- outcome = { error: errorUtils.toError(error) };
90
+ outcome = { error: toError(error) };
91
91
  }
92
92
  if (controller.signal.aborted) return;
93
93
  child = undefined;
94
94
  if (Date.now() - startedAt >= STABLE_CONNECTION_MS) failures = 0;
95
- const delayMs = asyncUtils.boundedRetryDelay(failures++, options.retryDelaysMs);
95
+ const delayMs = boundedRetryDelay(failures++, options.retryDelaysMs);
96
96
  options.logger.warn(`${options.name} stopped; retrying`, { ...outcome, delayMs });
97
97
  try {
98
- await asyncUtils.sleep(delayMs, controller.signal);
98
+ await sleep(delayMs, controller.signal);
99
99
  } catch {
100
100
  return;
101
101
  }
@@ -104,7 +104,7 @@ export function superviseProcessForever(options: ProcessSupervisorOptions): Proc
104
104
 
105
105
  void run().catch((error) =>
106
106
  options.logger.error(`${options.name} supervisor failed`, {
107
- error: errorUtils.toError(error),
107
+ error: toError(error),
108
108
  }),
109
109
  );
110
110
  return {
@@ -157,7 +157,7 @@ function processOutcome(
157
157
  // Probe errors (DNS blips, timeouts) are not proof the tunnel is dead;
158
158
  // only an explicit unhealthy result triggers a restart.
159
159
  options.logger.debug(`${options.name} health probe errored; ignoring`, {
160
- error: errorUtils.toError(error),
160
+ error: toError(error),
161
161
  });
162
162
  healthy = true;
163
163
  }
@@ -185,7 +185,7 @@ function processOutcome(
185
185
  () => finish(outcome),
186
186
  (error) => {
187
187
  options.logger.error(`${options.name} did not stop`, {
188
- error: errorUtils.toError(error),
188
+ error: toError(error),
189
189
  });
190
190
  finish(outcome);
191
191
  },
package/src/vite.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Vite host configuration derived from the tunnel auth-gate owner.
3
+ *
4
+ * @module
5
+ */
6
+ import { resolveAuthGateConfig, type AuthGateConfig } from "./plugin.ts";
7
+
8
+ /** Hostnames Vite should accept for configured public tunnel domains. */
9
+ export function tunnelAllowedHosts(config: AuthGateConfig = {}): string[] {
10
+ const hosts = new Set<string>();
11
+ for (const value of resolveAuthGateConfig(config).publicDomains) {
12
+ const host = hostname(value);
13
+ if (host) hosts.add(host);
14
+ }
15
+ return [...hosts];
16
+ }
17
+
18
+ function hostname(value: string): string | undefined {
19
+ try {
20
+ return new URL(value.includes("://") ? value : `https://${value}`).hostname;
21
+ } catch {
22
+ return undefined;
23
+ }
24
+ }
package/exports.ts DELETED
@@ -1 +0,0 @@
1
- export { tunnelInterceptor } from "./src/interceptor.ts";
package/lib/exports.d.ts DELETED
@@ -1 +0,0 @@
1
- export { tunnelInterceptor } from "./src/interceptor.ts";
package/lib/exports.js DELETED
@@ -1,2 +0,0 @@
1
- export { tunnelInterceptor } from "./src/interceptor.js";
2
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXhwb3J0cy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL2V4cG9ydHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLGlCQUFpQixFQUFFLE1BQU0sc0JBQXNCLENBQUMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgeyB0dW5uZWxJbnRlcmNlcHRvciB9IGZyb20gXCIuL3NyYy9pbnRlcmNlcHRvci50c1wiO1xuIl19