cbaxley commited on
Commit
11b3669
·
unverified ·
1 Parent(s): 674f35f

feat(gateway): detect port-based Tailscale Serve proxies (#330)

Browse files

The existing Tailscale Serve detection only looked for a /gw path handler,
missing configurations where the gateway is proxied on a separate port
(e.g. :8443 → localhost:18789). This caused remote browsers to attempt
direct wss connections to the gateway port, which fails through Tailscale.

Extract Tailscale Serve detection into src/lib/tailscale-serve.ts and
extend it to discover port-based proxy mappings from the Tailscale Serve
JSON config. Also adds the macOS app bundle path for the Tailscale CLI
binary, which is not on PATH when installed via the Mac App Store.

src/app/api/gateways/connect/route.ts CHANGED
@@ -1,9 +1,15 @@
1
  import { NextRequest, NextResponse } from 'next/server'
2
- import { readFileSync } from 'node:fs'
3
  import { requireRole } from '@/lib/auth'
4
  import { getDatabase } from '@/lib/db'
5
  import { buildGatewayWebSocketUrl } from '@/lib/gateway-url'
6
  import { getDetectedGatewayToken } from '@/lib/gateway-runtime'
 
 
 
 
 
 
 
7
 
8
  interface GatewayEntry {
9
  id: number
@@ -35,56 +41,6 @@ function inferBrowserProtocol(request: NextRequest): 'http:' | 'https:' {
35
 
36
  const LOCALHOST_HOSTS = new Set(['127.0.0.1', 'localhost', '::1'])
37
 
38
- /**
39
- * Detect whether Tailscale Serve is proxying a `/gw` route to the gateway.
40
- *
41
- * Checks in order:
42
- * 1. `tailscale serve status --json` — look for a /gw handler (authoritative)
43
- * 2. Fallback: `gateway.tailscale.mode === 'serve'` in openclaw.json (legacy)
44
- */
45
- function detectTailscaleServe(): boolean {
46
- // 1. Check live Tailscale Serve config for a /gw handler
47
- try {
48
- const { execFileSync } = require('node:child_process')
49
- const raw = execFileSync('tailscale', ['serve', 'status', '--json'], {
50
- timeout: 3000,
51
- encoding: 'utf-8',
52
- stdio: ['ignore', 'pipe', 'ignore'],
53
- })
54
- const config = JSON.parse(raw)
55
- const web = config?.Web
56
- if (web) {
57
- for (const host of Object.values(web) as any[]) {
58
- if ((host as any)?.Handlers?.['/gw']) return true
59
- }
60
- }
61
- } catch {
62
- // tailscale CLI not available or not running — fall through
63
- }
64
-
65
- // 2. Legacy: check openclaw.json config
66
- const configPath = process.env.OPENCLAW_CONFIG_PATH || ''
67
- if (!configPath) return false
68
- try {
69
- const raw = readFileSync(configPath, 'utf-8')
70
- const config = JSON.parse(raw)
71
- return config?.gateway?.tailscale?.mode === 'serve'
72
- } catch {
73
- return false
74
- }
75
- }
76
-
77
- /** Cache Tailscale Serve detection with 60-second TTL. */
78
- let _tailscaleServeCache: { value: boolean; expiresAt: number } | null = null
79
- const TAILSCALE_CACHE_TTL_MS = 60_000
80
- function isTailscaleServe(): boolean {
81
- const now = Date.now()
82
- if (!_tailscaleServeCache || now > _tailscaleServeCache.expiresAt) {
83
- _tailscaleServeCache = { value: detectTailscaleServe(), expiresAt: now + TAILSCALE_CACHE_TTL_MS }
84
- }
85
- return _tailscaleServeCache.value
86
- }
87
-
88
  /** Extract the browser-facing hostname from the request. */
89
  function getBrowserHostname(request: NextRequest): string {
90
  const origin = request.headers.get('origin') || request.headers.get('referer') || ''
@@ -114,8 +70,17 @@ function resolveRemoteGatewayUrl(
114
 
115
  // Browser is remote — determine the correct proxied URL
116
  if (isTailscaleServe()) {
117
- // Tailscale Serve proxies /gw → localhost:18789 with TLS
118
- return `wss://${browserHost}/gw`
 
 
 
 
 
 
 
 
 
119
  }
120
 
121
  // No Tailscale Serve — try direct connection to dashboard host on gateway port
 
1
  import { NextRequest, NextResponse } from 'next/server'
 
2
  import { requireRole } from '@/lib/auth'
3
  import { getDatabase } from '@/lib/db'
4
  import { buildGatewayWebSocketUrl } from '@/lib/gateway-url'
5
  import { getDetectedGatewayToken } from '@/lib/gateway-runtime'
6
+ import {
7
+ isTailscaleServe,
8
+ refreshTailscaleCache,
9
+ getCachedTailscaleWeb,
10
+ hasGwPathHandler,
11
+ findTailscaleServePort,
12
+ } from '@/lib/tailscale-serve'
13
 
14
  interface GatewayEntry {
15
  id: number
 
41
 
42
  const LOCALHOST_HOSTS = new Set(['127.0.0.1', 'localhost', '::1'])
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  /** Extract the browser-facing hostname from the request. */
45
  function getBrowserHostname(request: NextRequest): string {
46
  const origin = request.headers.get('origin') || request.headers.get('referer') || ''
 
70
 
71
  // Browser is remote — determine the correct proxied URL
72
  if (isTailscaleServe()) {
73
+ // Check for a /gw path-based proxy first
74
+ refreshTailscaleCache()
75
+ const web = getCachedTailscaleWeb()
76
+ if (hasGwPathHandler(web)) {
77
+ return `wss://${browserHost}/gw`
78
+ }
79
+ // Port-based proxy: find the Tailscale Serve port that proxies to the gateway port
80
+ const tsPort = findTailscaleServePort(web, gateway.port)
81
+ if (tsPort) {
82
+ return `wss://${browserHost}:${tsPort}`
83
+ }
84
  }
85
 
86
  // No Tailscale Serve — try direct connection to dashboard host on gateway port
src/lib/__tests__/tailscale-serve.test.ts ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from 'vitest'
2
+ import { findTailscaleServePort, detectTailscaleServe, hasGwPathHandler } from '@/lib/tailscale-serve'
3
+
4
+ // Realistic Tailscale Serve status JSON matching the structure returned by
5
+ // `tailscale serve status --json`
6
+ const TYPICAL_WEB_CONFIG = {
7
+ 'myhost.tailb5729a.ts.net:8443': {
8
+ Handlers: {
9
+ '/': { Proxy: 'http://localhost:18789' },
10
+ },
11
+ },
12
+ 'myhost.tailb5729a.ts.net:8444': {
13
+ Handlers: {
14
+ '/': { Proxy: 'http://127.0.0.1:3000' },
15
+ },
16
+ },
17
+ 'myhost.tailb5729a.ts.net:3001': {
18
+ Handlers: {
19
+ '/': { Proxy: 'http://127.0.0.1:3002' },
20
+ },
21
+ },
22
+ }
23
+
24
+ const GW_PATH_WEB_CONFIG = {
25
+ 'myhost.tailb5729a.ts.net:443': {
26
+ Handlers: {
27
+ '/': { Proxy: 'http://127.0.0.1:3000' },
28
+ '/gw': { Proxy: 'http://127.0.0.1:18789' },
29
+ },
30
+ },
31
+ }
32
+
33
+ describe('findTailscaleServePort', () => {
34
+ it('finds the external port proxying to a given local port', () => {
35
+ expect(findTailscaleServePort(TYPICAL_WEB_CONFIG, 18789)).toBe(8443)
36
+ expect(findTailscaleServePort(TYPICAL_WEB_CONFIG, 3000)).toBe(8444)
37
+ expect(findTailscaleServePort(TYPICAL_WEB_CONFIG, 3002)).toBe(3001)
38
+ })
39
+
40
+ it('returns null when no handler matches the target port', () => {
41
+ expect(findTailscaleServePort(TYPICAL_WEB_CONFIG, 9999)).toBeNull()
42
+ })
43
+
44
+ it('returns null for null/undefined web config', () => {
45
+ expect(findTailscaleServePort(null, 18789)).toBeNull()
46
+ expect(findTailscaleServePort(undefined, 18789)).toBeNull()
47
+ })
48
+
49
+ it('returns null for empty web config', () => {
50
+ expect(findTailscaleServePort({}, 18789)).toBeNull()
51
+ })
52
+
53
+ it('handles handlers without Proxy field', () => {
54
+ const web = {
55
+ 'myhost.ts.net:443': {
56
+ Handlers: {
57
+ '/': { Path: '/var/www' },
58
+ },
59
+ },
60
+ }
61
+ expect(findTailscaleServePort(web, 3000)).toBeNull()
62
+ })
63
+
64
+ it('matches proxy URLs with trailing slash', () => {
65
+ const web = {
66
+ 'myhost.ts.net:9000': {
67
+ Handlers: {
68
+ '/': { Proxy: 'http://127.0.0.1:4000/' },
69
+ },
70
+ },
71
+ }
72
+ expect(findTailscaleServePort(web, 4000)).toBe(9000)
73
+ })
74
+
75
+ it('does not match partial port numbers', () => {
76
+ const web = {
77
+ 'myhost.ts.net:443': {
78
+ Handlers: {
79
+ '/': { Proxy: 'http://127.0.0.1:18789' },
80
+ },
81
+ },
82
+ }
83
+ // Port 1878 should not match a proxy to 18789
84
+ expect(findTailscaleServePort(web, 1878)).toBeNull()
85
+ // Port 8789 should not match
86
+ expect(findTailscaleServePort(web, 8789)).toBeNull()
87
+ })
88
+ })
89
+
90
+ describe('detectTailscaleServe', () => {
91
+ it('detects /gw path-based proxy', () => {
92
+ expect(detectTailscaleServe(GW_PATH_WEB_CONFIG)).toBe(true)
93
+ })
94
+
95
+ it('detects port-based proxy to gateway default port 18789', () => {
96
+ expect(detectTailscaleServe(TYPICAL_WEB_CONFIG)).toBe(true)
97
+ })
98
+
99
+ it('returns false when no gateway proxy found', () => {
100
+ const web = {
101
+ 'myhost.ts.net:3000': {
102
+ Handlers: {
103
+ '/': { Proxy: 'http://127.0.0.1:3000' },
104
+ },
105
+ },
106
+ }
107
+ expect(detectTailscaleServe(web)).toBe(false)
108
+ })
109
+
110
+ it('returns false for null/undefined web config', () => {
111
+ expect(detectTailscaleServe(null)).toBe(false)
112
+ expect(detectTailscaleServe(undefined)).toBe(false)
113
+ })
114
+
115
+ it('returns false for empty web config with no config path', () => {
116
+ expect(detectTailscaleServe({})).toBe(false)
117
+ })
118
+
119
+ it('handles host entries with no Handlers', () => {
120
+ const web = { 'myhost.ts.net:443': {} }
121
+ expect(detectTailscaleServe(web)).toBe(false)
122
+ })
123
+ })
124
+
125
+ describe('hasGwPathHandler', () => {
126
+ it('returns true when /gw handler exists', () => {
127
+ expect(hasGwPathHandler(GW_PATH_WEB_CONFIG)).toBe(true)
128
+ })
129
+
130
+ it('returns false when no /gw handler exists', () => {
131
+ expect(hasGwPathHandler(TYPICAL_WEB_CONFIG)).toBe(false)
132
+ })
133
+
134
+ it('returns false for null/undefined', () => {
135
+ expect(hasGwPathHandler(null)).toBe(false)
136
+ expect(hasGwPathHandler(undefined)).toBe(false)
137
+ })
138
+ })
src/lib/tailscale-serve.ts ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { readFileSync } from 'node:fs'
2
+
3
+ /** Tailscale CLI binary paths to try (macOS app bundle, then PATH). */
4
+ const TAILSCALE_BINS = [
5
+ '/Applications/Tailscale.app/Contents/MacOS/Tailscale',
6
+ 'tailscale',
7
+ ]
8
+
9
+ export function execTailscaleServeJson(): any | null {
10
+ const { execFileSync } = require('node:child_process')
11
+ for (const bin of TAILSCALE_BINS) {
12
+ try {
13
+ const raw = execFileSync(bin, ['serve', 'status', '--json'], {
14
+ timeout: 3000,
15
+ encoding: 'utf-8',
16
+ stdio: ['ignore', 'pipe', 'ignore'],
17
+ })
18
+ return JSON.parse(raw)
19
+ } catch {
20
+ continue
21
+ }
22
+ }
23
+ return null
24
+ }
25
+
26
+ /**
27
+ * Find the Tailscale Serve port that proxies to a given local port.
28
+ *
29
+ * Looks through the `Web` section of `tailscale serve status --json` for any
30
+ * handler whose Proxy target points at localhost:<targetPort>. Returns the
31
+ * external Tailscale Serve port (e.g. 8443) or null if not found.
32
+ */
33
+ export function findTailscaleServePort(web: Record<string, any> | null | undefined, targetPort: number): number | null {
34
+ if (!web) return null
35
+
36
+ const targetSuffixes = [`:${targetPort}`, `:${targetPort}/`]
37
+ for (const [hostPort, hostConfig] of Object.entries(web) as [string, any][]) {
38
+ const handlers = hostConfig?.Handlers
39
+ if (!handlers) continue
40
+ for (const handler of Object.values(handlers) as any[]) {
41
+ const proxy = handler?.Proxy || ''
42
+ if (targetSuffixes.some(s => proxy.endsWith(s) || proxy === `http://127.0.0.1:${targetPort}` || proxy === `http://localhost:${targetPort}`)) {
43
+ // hostPort is like "hostname:8443"
44
+ const port = parseInt(hostPort.split(':').pop() || '', 10)
45
+ if (port > 0) return port
46
+ }
47
+ }
48
+ }
49
+ return null
50
+ }
51
+
52
+ /**
53
+ * Detect whether Tailscale Serve is proxying to the gateway.
54
+ *
55
+ * Checks the Web config for:
56
+ * 1. A `/gw` path handler (authoritative)
57
+ * 2. Any handler proxying to port 18789 (port-based proxy)
58
+ * 3. Fallback: `gateway.tailscale.mode === 'serve'` in openclaw.json (legacy)
59
+ */
60
+ export function detectTailscaleServe(web: Record<string, any> | null | undefined, configPath?: string): boolean {
61
+ if (web) {
62
+ for (const hostConfig of Object.values(web) as any[]) {
63
+ const handlers = (hostConfig as any)?.Handlers
64
+ if (!handlers) continue
65
+ if ((handlers as any)['/gw']) return true
66
+ // Also detect port-based proxy to gateway (e.g. :8443 → localhost:18789)
67
+ for (const handler of Object.values(handlers) as any[]) {
68
+ const proxy = (handler as any)?.Proxy || ''
69
+ if (proxy.includes(':18789')) return true
70
+ }
71
+ }
72
+ }
73
+
74
+ // Legacy: check openclaw.json config
75
+ const effectivePath = configPath || process.env.OPENCLAW_CONFIG_PATH || ''
76
+ if (!effectivePath) return false
77
+ try {
78
+ const raw = readFileSync(effectivePath, 'utf-8')
79
+ const config = JSON.parse(raw)
80
+ return config?.gateway?.tailscale?.mode === 'serve'
81
+ } catch {
82
+ return false
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Check whether any Tailscale Serve handler has a `/gw` path.
88
+ */
89
+ export function hasGwPathHandler(web: Record<string, any> | null | undefined): boolean {
90
+ if (!web) return false
91
+ for (const hostConfig of Object.values(web) as any[]) {
92
+ if ((hostConfig as any)?.Handlers?.['/gw']) return true
93
+ }
94
+ return false
95
+ }
96
+
97
+ /** Cache Tailscale Serve JSON with 60-second TTL. */
98
+ let _tailscaleServeJsonCache: { value: any; expiresAt: number } | null = null
99
+ let _tailscaleServeCache: { value: boolean; expiresAt: number } | null = null
100
+ const TAILSCALE_CACHE_TTL_MS = 60_000
101
+
102
+ export function refreshTailscaleCache(): void {
103
+ const now = Date.now()
104
+ if (!_tailscaleServeJsonCache || now > _tailscaleServeJsonCache.expiresAt) {
105
+ _tailscaleServeJsonCache = { value: execTailscaleServeJson(), expiresAt: now + TAILSCALE_CACHE_TTL_MS }
106
+ _tailscaleServeCache = null // invalidate derived cache
107
+ }
108
+ }
109
+
110
+ export function getCachedTailscaleWeb(): Record<string, any> | null {
111
+ return _tailscaleServeJsonCache?.value?.Web ?? null
112
+ }
113
+
114
+ export function isTailscaleServe(): boolean {
115
+ refreshTailscaleCache()
116
+ const now = Date.now()
117
+ if (!_tailscaleServeCache || now > _tailscaleServeCache.expiresAt) {
118
+ _tailscaleServeCache = { value: detectTailscaleServe(getCachedTailscaleWeb()), expiresAt: now + TAILSCALE_CACHE_TTL_MS }
119
+ }
120
+ return _tailscaleServeCache.value
121
+ }
122
+
123
+ /** Reset caches — for testing only. */
124
+ export function _resetCaches(): void {
125
+ _tailscaleServeJsonCache = null
126
+ _tailscaleServeCache = null
127
+ }