@dbx-tools/tunnel 0.9.40 → 0.9.43

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/frp.ts CHANGED
@@ -15,7 +15,8 @@ import os from "node:os";
15
15
  import { delimiter, join } from "node:path";
16
16
 
17
17
  import { bin, configUtils } from "@dbx-tools/core";
18
- import { log } from "@dbx-tools/shared-core";
18
+ import { log, options as sharedOptions } from "@dbx-tools/shared-core";
19
+ import { z } from "zod";
19
20
  import { TUNNEL_CONFIG } from "./_config.ts";
20
21
  import { superviseProcessForever, type ProcessSupervisor } from "./supervisor.ts";
21
22
 
@@ -43,6 +44,24 @@ export interface FrpConfig {
43
44
  targetPort: number;
44
45
  }
45
46
 
47
+ export const FrpOptionsSchema = z
48
+ .object({
49
+ publicDomain: z.string().trim().min(1).optional().describe("FRP public HTTP host."),
50
+ server: z.string().trim().min(1).optional().describe("FRP control host."),
51
+ serverPort: sharedOptions.tcpPortOrZeroSchema.optional().describe("FRP control port."),
52
+ protocol: z.string().trim().min(1).optional().describe("FRP transport protocol."),
53
+ token: z.string().trim().min(1).optional().describe("FRP authentication token."),
54
+ proxyName: z.string().trim().min(1).optional().describe("FRP proxy registration name."),
55
+ path: z.string().trim().min(1).optional().describe("FRP public path."),
56
+ stripPrefix: z.boolean().optional().describe("Strip the FRP path before forwarding."),
57
+ port: sharedOptions.tcpPortOrZeroSchema.describe("Public listener port."),
58
+ targetPort: sharedOptions.tcpPortOrZeroSchema.optional().describe("Private target port."),
59
+ })
60
+ .strict()
61
+ .describe("FRP tunnel resolution options.");
62
+
63
+ export type FrpOptions = z.input<typeof FrpOptionsSchema>;
64
+
46
65
  function bareHost(value: string | undefined): string | undefined {
47
66
  if (!value) return undefined;
48
67
  const normalized = value
@@ -59,35 +78,25 @@ function normalizePath(value: string | undefined): string {
59
78
  }
60
79
 
61
80
  /** Resolve frpc config from the public domain and FRP-specific environment. */
62
- export function resolveFrpConfig(opts: {
63
- publicDomain?: string;
64
- server?: string;
65
- serverPort?: string | number;
66
- protocol?: string;
67
- token?: string;
68
- proxyName?: string;
69
- path?: string;
70
- stripPrefix?: boolean;
71
- port: number;
72
- targetPort?: number;
73
- }): FrpConfig | undefined {
81
+ export function resolveFrpConfig(opts: FrpOptions): FrpConfig | undefined {
82
+ const options = FrpOptionsSchema.parse(opts);
74
83
  const publicDomain = bareHost(
75
84
  configUtils.string(
76
- opts.publicDomain,
85
+ options.publicDomain,
77
86
  ["TUNNEL_FRP_PUBLIC_DOMAIN", "TUNNEL_PUBLIC_DOMAIN"],
78
87
  TUNNEL_CONFIG,
79
88
  ),
80
89
  );
81
90
  if (!publicDomain) return undefined;
82
- const server = bareHost(configUtils.string(opts.server, "FRP_SERVER")) ?? publicDomain;
83
- const serverPort = configUtils.port(opts.serverPort, "FRP_SERVER_PORT", 443);
84
- const protocol = configUtils.string(opts.protocol, "FRP_PROTOCOL") ?? "wss";
85
- const token = configUtils.string(opts.token, ["FRP_TOKEN", "TUNNEL_TOKEN"]);
91
+ const server = bareHost(configUtils.string(options.server, "FRP_SERVER")) ?? publicDomain;
92
+ const serverPort = configUtils.port(options.serverPort, "FRP_SERVER_PORT", 443);
93
+ const protocol = configUtils.string(options.protocol, "FRP_PROTOCOL") ?? "wss";
94
+ const token = configUtils.string(options.token, ["FRP_TOKEN", "TUNNEL_TOKEN"]);
86
95
  const proxyName =
87
- configUtils.string(opts.proxyName, "FRP_PROXY_NAME") ?? publicDomain.split(".")[0] ?? "app";
96
+ configUtils.string(options.proxyName, "FRP_PROXY_NAME") ?? publicDomain.split(".")[0] ?? "app";
88
97
  const appName = configUtils.string(undefined, "DATABRICKS_APP_NAME") ?? proxyName;
89
- const path = normalizePath(configUtils.string(opts.path, "FRP_PATH") ?? appName);
90
- const stripPrefix = configUtils.boolean(opts.stripPrefix, "FRP_STRIP_PREFIX") ?? path !== "/";
98
+ const path = normalizePath(configUtils.string(options.path, "FRP_PATH") ?? appName);
99
+ const stripPrefix = configUtils.boolean(options.stripPrefix, "FRP_STRIP_PREFIX") ?? path !== "/";
91
100
  return {
92
101
  publicDomain,
93
102
  server,
@@ -97,8 +106,8 @@ export function resolveFrpConfig(opts: {
97
106
  proxyName,
98
107
  path,
99
108
  stripPrefix,
100
- port: opts.port,
101
- targetPort: opts.targetPort ?? opts.port,
109
+ port: options.port,
110
+ targetPort: options.targetPort ?? options.port,
102
111
  };
103
112
  }
104
113
 
@@ -18,49 +18,44 @@
18
18
  */
19
19
 
20
20
  import type { Interceptor, InterceptorContext } from "@dbx-tools/appkit";
21
- import { log, object } from "@dbx-tools/shared-core";
21
+ import { log, object, options as sharedOptions } from "@dbx-tools/shared-core";
22
+ import { z } from "zod";
22
23
  import { installFrp, resolveFrpConfig, superviseFrp, writeFrpConfig } from "./frp.ts";
23
24
  import { startPathProxy } from "./path-proxy.ts";
24
25
  import { installPortr, resolvePortrConfig, supervisePortr, writePortrConfig } from "./portr.ts";
25
26
 
26
27
  const logger = log.logger("tunnel:interceptor");
27
28
 
28
- /** Options for {@link tunnelInterceptor} (each also resolvable from env). */
29
- export interface TunnelInterceptorOptions {
30
- /** Tunnel clients to run. Env `TUNNEL_TRANSPORT`; defaults to `portr`. */
31
- transport?: TunnelTransport;
32
- /** Public host to serve on. Env `TUNNEL_PUBLIC_DOMAIN`. */
33
- publicDomain?: string;
34
- /** portr subdomain (else derived from {@link publicDomain}). */
35
- subdomain?: string;
36
- /** Portr SSH control endpoint. Env `PORTR_SSH_URL`; defaults to the Portr host on port `4444`. */
37
- portrSshUrl?: string;
38
- /**
39
- * The PUBLIC port portr forwards to - the port the app itself listens on.
40
- * Defaults to the Databricks Apps runtime contract `DATABRICKS_APP_PORT`
41
- * (then `8000`), which is the port the platform routes to.
42
- */
43
- port?: number;
44
- /** frps control host; defaults to the FRP public domain. Env `FRP_SERVER`. */
45
- frpServer?: string;
46
- /** FRP public HTTP host. Env `TUNNEL_FRP_PUBLIC_DOMAIN`. */
47
- frpPublicDomain?: string;
48
- /** frps control port. Env `FRP_SERVER_PORT`; defaults to `443`. */
49
- frpServerPort?: number;
50
- /** frpc transport protocol. Env `FRP_PROTOCOL`; defaults to `wss`. */
51
- frpProtocol?: string;
52
- /** frps auth token. Env `FRP_TOKEN` (or `TUNNEL_TOKEN`). */
53
- frpToken?: string;
54
- /** frp proxy registration name. Env `FRP_PROXY_NAME`. */
55
- frpProxyName?: string;
56
- /** FRP path location. Env `FRP_PATH`; defaults to `DATABRICKS_APP_NAME`. */
57
- frpPath?: string;
58
- /** Strip the FRP path before forwarding. Env `FRP_STRIP_PREFIX`; defaults true for non-root paths. */
59
- frpStripPrefix?: boolean;
60
- }
29
+ const text = (description: string) => z.string().trim().min(1).optional().describe(description);
30
+ const port = (description: string) =>
31
+ sharedOptions.tcpPortOrZeroSchema.optional().describe(description);
32
+
33
+ export const TunnelTransportSchema = z
34
+ .enum(["portr", "frp", "both"])
35
+ .describe("Public tunnel clients supported by the interceptor and CLI.");
36
+
37
+ export const TunnelInterceptorOptionsSchema = z
38
+ .object({
39
+ transport: TunnelTransportSchema.optional().describe("Public tunnel transport."),
40
+ publicDomain: text("Public tunnel host."),
41
+ subdomain: text("Portr subdomain."),
42
+ portrSshUrl: text("Portr SSH control endpoint."),
43
+ port: port("Public listener port."),
44
+ frpServer: text("FRP control host."),
45
+ frpPublicDomain: text("FRP public HTTP host."),
46
+ frpServerPort: port("FRP control port."),
47
+ frpProtocol: text("FRP transport protocol."),
48
+ frpToken: text("FRP authentication token."),
49
+ frpProxyName: text("FRP proxy registration name."),
50
+ frpPath: text("FRP path location."),
51
+ frpStripPrefix: z.boolean().optional().describe("Strip the FRP path before forwarding."),
52
+ })
53
+ .strict()
54
+ .describe("Tunnel interceptor options.");
55
+
56
+ export type TunnelTransport = z.infer<typeof TunnelTransportSchema>;
61
57
 
62
- /** Public tunnel clients supported by the interceptor and CLI. */
63
- export type TunnelTransport = "portr" | "frp" | "both";
58
+ export type TunnelInterceptorOptions = z.input<typeof TunnelInterceptorOptionsSchema>;
64
59
 
65
60
  interface TunnelAuxiliary {
66
61
  stop(): void;
@@ -104,8 +99,7 @@ const defaultRuntime: TunnelRuntime = {
104
99
  /** Resolve and validate the tunnel transport selector. */
105
100
  export function resolveTunnelTransport(transport?: string): TunnelTransport {
106
101
  const resolved = transport ?? process.env.TUNNEL_TRANSPORT ?? "portr";
107
- if (resolved === "portr" || resolved === "frp" || resolved === "both") return resolved;
108
- throw new TypeError(`invalid tunnel transport: ${resolved} (expected portr, frp, or both)`);
102
+ return TunnelTransportSchema.parse(resolved);
109
103
  }
110
104
 
111
105
  /** Resolve the public port portr should target: explicit, else the Apps contract. */
package/src/plugin.ts CHANGED
@@ -30,7 +30,6 @@ import {
30
30
  authStorage,
31
31
  type AuthorizeIdentity,
32
32
  type AuthEmailOptions,
33
- type AuthStorageConfig,
34
33
  type AuthStorageMode,
35
34
  type PasswordlessAuthRuntime,
36
35
  } from "@dbx-tools/auth-gate";
@@ -38,6 +37,7 @@ import { configUtils } from "@dbx-tools/core";
38
37
  import { AUTH_BASE_PATH } from "@dbx-tools/shared-auth";
39
38
  import { brandUtils, log, stringUtils } from "@dbx-tools/shared-core";
40
39
  import type { RequestHandler } from "express";
40
+ import { z } from "zod";
41
41
  import { TUNNEL_CONFIG } from "./_config.ts";
42
42
  import { looksLikeEmail, matchesAllowlist } from "./allowlist.ts";
43
43
  import { mountGate, type GateOptions } from "./gate.ts";
@@ -88,107 +88,56 @@ export function mountGateOnContext(context: GateMountContext, options: GateOptio
88
88
  );
89
89
  }
90
90
 
91
- /** Options for the {@link authGate} plugin (all resolvable from env - see below). */
92
- export interface AuthGateConfig extends BasePluginConfig, AuthStorageConfig {
93
- /** Allow-list patterns (domain / glob / `/regex/`). Empty = allow nobody. Env TUNNEL_AUTH_ALLOW. */
94
- allow?: string | string[];
95
- /**
96
- * Subject line for the code email. Env TUNNEL_AUTH_SUBJECT.
97
- *
98
- * Defaults to "Your verification code". The wording of the subject and
99
- * {@link message} is deliberately the conventional phrasing rather than
100
- * anything branded: iOS, Gmail, Outlook, and Android all detect a one-time
101
- * code from this shape and offer to autofill it, and a novel phrasing is what
102
- * breaks that detection.
103
- *
104
- * This is the subject TEMPLATE, not the literal line sent: the code is spliced
105
- * into it (`"123456 is your verification code"`) because a push notification
106
- * shows only the subject and preheader, and that notification is what mobile
107
- * autofill reads. See `codeEmailSubject` in `./code-email.ts`.
108
- */
109
- subject?: string;
110
- /**
111
- * Display name used in the code email copy. Env TUNNEL_AUTH_BRAND_NAME.
112
- *
113
- * Defaults to the brand context's `name` - the app's own `branding/brand.yaml`
114
- * when it has one, else the dbx-tools default. Set this only to override the
115
- * brand for this gate.
116
- */
117
- brandName?: string;
118
- /**
119
- * Line shown immediately above the code in the email. Env TUNNEL_AUTH_MESSAGE.
120
- *
121
- * Keep the code on its OWN line directly after this text - that adjacency is
122
- * what the platform code-detection heuristics key on.
123
- */
124
- message?: string;
125
- /**
126
- * Session lifetime (seconds). Env TUNNEL_AUTH_SESSION_TTL. Default 2592000 (30d).
127
- *
128
- * Matched to the cache-backed signing key's own 30-day TTL (see
129
- * `./signing-key.ts`): the cookie and the key that validates it should expire
130
- * together, or one silently outlives the other.
131
- */
132
- sessionTtlSeconds?: number;
133
- /** One-time-code lifetime (seconds). Env TUNNEL_AUTH_CODE_TTL. Default 600 (10m). */
134
- codeTtlSeconds?: number;
135
- /** Max verify attempts per issued code. Default 5. */
136
- maxAttempts?: number;
137
- /**
138
- * Force-clear cutoff: every session issued BEFORE it stops verifying, so moving
139
- * it forward signs everyone out. Env TUNNEL_AUTH_SESSION_CUTOFF.
140
- *
141
- * Anything `object.toDate` accepts: a `Date`, `2026-08-02`, an ISO instant,
142
- * epoch seconds/millis, or a relative duration (`-30d`, `7 days ago`). Unset
143
- * means no cutoff.
144
- */
145
- sessionCutoff?: string | number | Date;
146
- /**
147
- * Same-origin path returned after a successful logout. Env
148
- * `TUNNEL_AUTH_LOGOUT_REDIRECT`. Defaults to `/`, where the AuthGate presents
149
- * login again.
150
- */
151
- logoutRedirectPath?: string;
152
- /**
153
- * Deliver a code to an address. Defaults to sending through the host app's
154
- * shared `@dbx-tools/email` transport (see `./send-code`); override to wire a
155
- * different delivery path.
156
- */
157
- sendCode?: (email: string, code: string, opts: SendCodeOptions) => Promise<void>;
158
- /**
159
- * Identity authorization independent of authentication. Defaults to the
160
- * configured allow-list and is re-evaluated for every accepted session.
161
- */
162
- authorizeIdentity?: AuthorizeIdentity;
163
- /**
164
- * The public `<subdomain>.<server>` that identifies portr traffic by its `Host`
165
- * header. Only requests whose `Host` matches this are gated; everything else
166
- * (the platform front door, other local callers) passes through. Env
167
- * `TUNNEL_PUBLIC_DOMAIN`. When absent, the gate is inert (nothing is tunnel
168
- * traffic).
169
- */
170
- publicDomain?: string;
171
- /** Additional public tunnel domains accepted by the gate. */
172
- publicDomains?: string | string[];
173
- /**
174
- * Extra `x-` request headers tunnel traffic may forward (literal / glob /
175
- * `/regex/`), unioned with the built-in allow-list. Env `TUNNEL_FORWARD_HEADERS`.
176
- */
177
- forwardHeaders?: string | string[];
178
- /**
179
- * Path prefixes to gate beyond the built-in `/api/` (literal prefixes, comma-
180
- * or space-separated as a string). For an app whose privileged surface is not
181
- * under `/api/` — e.g. a WebSocket at `/ws` — list those prefixes so they
182
- * require a session too. Env `TUNNEL_GATE_PATHS`.
183
- */
184
- gatePaths?: string | string[];
185
- /**
186
- * Run OPEN with no gate (env `TUNNEL_INSECURE=true`). The login routes and gate
187
- * middleware are not mounted, and the SMTP fail-fast is skipped. Use only when
188
- * the tunnel is deliberately public.
189
- */
190
- insecure?: boolean;
191
- }
91
+ const text = (description: string) => z.string().trim().min(1).optional().describe(description);
92
+ const textOrList = (description: string) =>
93
+ z
94
+ .union([z.string(), z.array(z.string())])
95
+ .optional()
96
+ .describe(description);
97
+
98
+ export const AuthGateConfigSchema = authStorage.AuthStorageConfigSchema.extend({
99
+ allow: textOrList("Email allow-list patterns."),
100
+ subject: text("Verification email subject."),
101
+ brandName: text("Verification email brand name."),
102
+ message: text("Verification email message."),
103
+ sessionTtlSeconds: z.coerce
104
+ .number<number>()
105
+ .positive()
106
+ .optional()
107
+ .describe("Session lifetime in seconds."),
108
+ codeTtlSeconds: z.coerce
109
+ .number<number>()
110
+ .positive()
111
+ .optional()
112
+ .describe("One-time-code lifetime in seconds."),
113
+ maxAttempts: z.coerce
114
+ .number<number>()
115
+ .int()
116
+ .positive()
117
+ .optional()
118
+ .describe("Maximum verification attempts per code."),
119
+ sessionCutoff: z
120
+ .union([z.string(), z.number(), z.date()])
121
+ .optional()
122
+ .describe("Session invalidation cutoff."),
123
+ logoutRedirectPath: text("Same-origin path returned after logout."),
124
+ publicDomain: text("Primary public tunnel domain."),
125
+ publicDomains: textOrList("Additional public tunnel domains."),
126
+ forwardHeaders: textOrList("Additional forwarded request header patterns."),
127
+ gatePaths: textOrList("Additional path prefixes requiring authentication."),
128
+ insecure: z.boolean().optional().describe("Run without an authentication gate."),
129
+ })
130
+ .strict()
131
+ .describe("Serializable authentication gate configuration.");
132
+
133
+ type SerializableAuthGateConfig = z.input<typeof AuthGateConfigSchema>;
134
+
135
+ /** Options for the {@link authGate} plugin. */
136
+ export type AuthGateConfig = BasePluginConfig &
137
+ SerializableAuthGateConfig & {
138
+ sendCode?: (email: string, code: string, opts: SendCodeOptions) => Promise<void>;
139
+ authorizeIdentity?: AuthorizeIdentity;
140
+ };
192
141
 
193
142
  /** Branding and expiry metadata passed to {@link AuthGateConfig.sendCode}. */
194
143
  export type SendCodeOptions = AuthEmailOptions;
package/src/portr.ts CHANGED
@@ -18,7 +18,8 @@ import { StringDecoder } from "node:string_decoder";
18
18
  import { promisify } from "node:util";
19
19
 
20
20
  import { bin, configUtils } from "@dbx-tools/core";
21
- import { log, stringUtils } from "@dbx-tools/shared-core";
21
+ import { log, options as sharedOptions, stringUtils } from "@dbx-tools/shared-core";
22
+ import { z } from "zod";
22
23
  import { TUNNEL_CONFIG } from "./_config.ts";
23
24
  import { superviseProcessForever, type ProcessSupervisor } from "./supervisor.ts";
24
25
 
@@ -64,24 +65,32 @@ export interface PortrConfig {
64
65
  port: number;
65
66
  }
66
67
 
68
+ export const PortrOptionsSchema = z
69
+ .object({
70
+ publicDomain: z.string().trim().min(1).optional().describe("Public tunnel domain."),
71
+ subdomain: z.string().trim().min(1).optional().describe("Portr subdomain."),
72
+ sshUrl: z.string().trim().min(1).optional().describe("Portr SSH control endpoint."),
73
+ token: z.string().trim().min(1).optional().describe("Portr authentication token."),
74
+ port: sharedOptions.tcpPortOrZeroSchema.describe("Public listener port."),
75
+ })
76
+ .strict()
77
+ .describe("Portr tunnel resolution options.");
78
+
79
+ export type PortrOptions = z.input<typeof PortrOptionsSchema>;
80
+
67
81
  /**
68
82
  * Resolve portr config from `TUNNEL_PUBLIC_DOMAIN` + `PORTR_TOKEN`, or an
69
83
  * explicit `subdomain`. The domain is `<subdomain>.<server>` (e.g.
70
84
  * `demo.apps.dbx.tools`). Returns `undefined` (no tunnel) when the token or a
71
85
  * usable domain is absent.
72
86
  */
73
- export function resolvePortrConfig(opts: {
74
- publicDomain?: string;
75
- subdomain?: string;
76
- sshUrl?: string;
77
- token?: string;
78
- port: number;
79
- }): PortrConfig | undefined {
87
+ export function resolvePortrConfig(opts: PortrOptions): PortrConfig | undefined {
88
+ const options = PortrOptionsSchema.parse(opts);
80
89
  // PORTR_* is upstream portr's own namespace, so it keeps its name.
81
- const token = configUtils.string(opts.token, "PORTR_TOKEN");
82
- const domain = configUtils.string(opts.publicDomain, "TUNNEL_PUBLIC_DOMAIN", TUNNEL_CONFIG);
90
+ const token = configUtils.string(options.token, "PORTR_TOKEN");
91
+ const domain = configUtils.string(options.publicDomain, "TUNNEL_PUBLIC_DOMAIN", TUNNEL_CONFIG);
83
92
  if (!token) return undefined;
84
- let subdomain = opts.subdomain;
93
+ let subdomain = options.subdomain;
85
94
  let server: string | undefined;
86
95
  if (domain) {
87
96
  subdomain ??= domain.split(".")[0];
@@ -89,8 +98,8 @@ export function resolvePortrConfig(opts: {
89
98
  }
90
99
  server ??= configUtils.text("PORTR_SERVER");
91
100
  if (!subdomain || !server || server === domain) return undefined;
92
- const sshUrl = configUtils.string(opts.sshUrl, "PORTR_SSH_URL") ?? `${server}:4444`;
93
- return { subdomain, server, sshUrl, token, port: opts.port };
101
+ const sshUrl = configUtils.string(options.sshUrl, "PORTR_SSH_URL") ?? `${server}:4444`;
102
+ return { subdomain, server, sshUrl, token, port: options.port };
94
103
  }
95
104
 
96
105
  /** GitHub release asset name for the current or supplied OS/architecture. */