shapewall 0.6.0 → 0.7.1

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 (127) hide show
  1. package/CHANGELOG.md +267 -0
  2. package/README.md +39 -2
  3. package/THIRD_PARTY.md +15 -0
  4. package/dist/agent/package-lock.json +594 -2
  5. package/dist/client/assets/{BoardChat-DdwBcb2N.js → BoardChat-Bv4UDOjO.js} +1 -1
  6. package/dist/client/assets/{BuzzDialog-DpUcnU6S.js → BuzzDialog-DwEAN6va.js} +1 -1
  7. package/dist/client/assets/{ChecksPanel-CngYV4yz.js → ChecksPanel-C6r_Tc9g.js} +1 -1
  8. package/dist/client/assets/{History-CD0saQA5.js → History-ajFROfWC.js} +1 -1
  9. package/dist/client/assets/{LocalSettings-MZy2baig.js → LocalSettings-BSbmmpbN.js} +1 -1
  10. package/dist/client/assets/{Management-CSvZ-SHO.js → Management-mo8uv2qG.js} +1 -1
  11. package/dist/client/assets/{QuickConnect-foLh2QUm.js → QuickConnect-DlaijESK.js} +1 -1
  12. package/dist/client/assets/{ShareDialog-DPWDftoL.js → ShareDialog-CdLdd6WQ.js} +1 -1
  13. package/dist/client/assets/{app-update-dialog-CtiXpTRD.js → app-update-dialog-BHVNR5Cp.js} +1 -1
  14. package/dist/client/assets/{circle-x-CteRBtXC.js → circle-x-D5MkDLJk.js} +1 -1
  15. package/dist/client/assets/index-B4AoX3ZW.css +2 -0
  16. package/dist/client/assets/index-CQeHY7en.js +37 -0
  17. package/dist/client/assets/{play-BjRNIGSf.js → play--xrZ7VCR.js} +1 -1
  18. package/dist/client/assets/{refresh-cw-r_tZiFfB.js → refresh-cw-B-npxKae.js} +1 -1
  19. package/dist/client/assets/{ui-zQpn-PdL.js → ui-2lMx-4bc.js} +2 -2
  20. package/dist/client/build-info.json +1 -1
  21. package/dist/client/index.html +3 -3
  22. package/dist/client/sw.js +2 -2
  23. package/dist/console/assets/LocalAccountsApp-C1sCag6a.js +1 -0
  24. package/dist/console/assets/LocalConsole-LXQmzRFT.js +2 -0
  25. package/dist/console/assets/LocalUsage-Br3Ddp7_.js +1 -0
  26. package/dist/console/assets/app-update-dialog-CVniDJKA.js +1 -0
  27. package/dist/console/assets/app-version-CTHwlY6g.js +1 -0
  28. package/dist/console/assets/console-CMNNLtFw.js +11 -0
  29. package/dist/console/assets/console-sMMn_Rwc.css +2 -0
  30. package/dist/console/assets/local-agents-DwYJ9cPb.js +6 -0
  31. package/dist/console/assets/minus-887msXez.js +1 -0
  32. package/dist/console/assets/tailnet--wXsG3uh.js +2 -0
  33. package/dist/console/assets/theme-CPfJOmcz.js +1 -0
  34. package/dist/console/assets/ui-DnyJhoQU.js +41 -0
  35. package/dist/console/assets/usage-C5CJHejQ.js +5 -0
  36. package/dist/console/assets/usage-CIPWnHaS.css +1 -0
  37. package/dist/console/assets/usage-DjmUlnXL.js +56 -0
  38. package/dist/console/build-info.json +1 -1
  39. package/dist/console/console.html +8 -2
  40. package/docs/agent-hardening.md +31 -17
  41. package/docs/agents.md +35 -0
  42. package/docs/architecture.md +10 -4
  43. package/docs/deployment.md +39 -17
  44. package/docs/design-system.md +56 -7
  45. package/docs/hosted.md +1004 -43
  46. package/docs/images/board-overview.png +0 -0
  47. package/docs/images/journeys.png +0 -0
  48. package/docs/images/live-comment.png +0 -0
  49. package/docs/images/phone-comment.png +0 -0
  50. package/docs/images/phone-overview.png +0 -0
  51. package/docs/images/variant.png +0 -0
  52. package/docs/where-to-run.md +82 -1
  53. package/package.json +6 -1
  54. package/src/agent/backends/acp.js +224 -26
  55. package/src/agent/routes.js +21 -0
  56. package/src/agent/usage-log.js +251 -0
  57. package/src/cli/args.js +24 -0
  58. package/src/cli/help.js +37 -2
  59. package/src/cli/init.js +2 -1
  60. package/src/cli/serve.js +20 -5
  61. package/src/cli.js +8 -0
  62. package/src/hosted/access-cli.js +99 -1
  63. package/src/hosted/activity-core.js +232 -0
  64. package/src/hosted/activity.js +375 -0
  65. package/src/hosted/admin.js +80 -13
  66. package/src/hosted/agent-approvals.js +2 -2
  67. package/src/hosted/agent-routes.js +3 -3
  68. package/src/hosted/agents.js +11 -4
  69. package/src/hosted/app.js +89 -7
  70. package/src/hosted/auth-routes.js +156 -15
  71. package/src/hosted/auth.js +123 -20
  72. package/src/hosted/board-routes.js +3 -3
  73. package/src/hosted/chat-frames.js +5 -15
  74. package/src/hosted/chat-permissions.js +12 -0
  75. package/src/hosted/chat-routes.js +8 -8
  76. package/src/hosted/chat-store.js +20 -3
  77. package/src/hosted/comment-files.js +5 -2
  78. package/src/hosted/console-routes.js +111 -34
  79. package/src/hosted/db.js +130 -0
  80. package/src/hosted/device-routes.js +25 -3
  81. package/src/hosted/device.js +23 -4
  82. package/src/hosted/guards.js +337 -27
  83. package/src/hosted/http.js +6 -3
  84. package/src/hosted/membership.js +13 -2
  85. package/src/hosted/operator-access.js +418 -0
  86. package/src/hosted/operator.js +106 -2
  87. package/src/hosted/ops-cli.js +238 -3
  88. package/src/hosted/pages.js +2 -0
  89. package/src/hosted/passkey-policy.js +75 -0
  90. package/src/hosted/permissions.js +14 -6
  91. package/src/hosted/presence.js +14 -2
  92. package/src/hosted/projects.js +2 -1
  93. package/src/hosted/public.js +4 -4
  94. package/src/hosted/ratelimit.js +6 -0
  95. package/src/hosted/retention.js +18 -2
  96. package/src/hosted/server.js +123 -11
  97. package/src/hosted/shares.js +2 -2
  98. package/src/hosted/step-up-settings.js +68 -0
  99. package/src/hosted/step-up.js +135 -0
  100. package/src/hosted/tailnet-identity.js +24 -0
  101. package/src/hosted/tailnet-routes.js +342 -0
  102. package/src/hosted/tailnet.js +220 -0
  103. package/src/hosted/tailscale.js +75 -9
  104. package/src/hosted/tenancy.js +48 -1
  105. package/src/hosted/token-api.js +2 -2
  106. package/src/hosted/tokens.js +9 -2
  107. package/src/hosted/usage-core.js +624 -0
  108. package/src/hosted/usage-layout.js +724 -0
  109. package/src/hosted/usage-routes.js +375 -0
  110. package/src/hosted/usage-shape.js +256 -0
  111. package/src/hosted/usage.js +641 -0
  112. package/src/remote/agent-connect.js +37 -1
  113. package/src/remote/agent-link.js +2 -0
  114. package/src/remote/login.js +33 -8
  115. package/src/remote/share.js +1 -1
  116. package/src/remote/tailnet-cli.js +547 -0
  117. package/src/server/app.js +15 -0
  118. package/src/server/pairing-routes.js +34 -5
  119. package/src/server/tailscale.js +97 -4
  120. package/src/tailnet-proof.js +766 -0
  121. package/dist/client/assets/index-Cxz1UVcV.css +0 -2
  122. package/dist/client/assets/index-uUZVBYUS.js +0 -37
  123. package/dist/console/assets/LocalAccountsApp-DIdy1KnN.js +0 -1
  124. package/dist/console/assets/LocalConsole-DfcQztF-.js +0 -1
  125. package/dist/console/assets/app-update-dialog-ttl9lF5A.js +0 -1
  126. package/dist/console/assets/console-OqAjD0kV.js +0 -55
  127. package/dist/console/assets/console-kvjrAArQ.css +0 -2
@@ -0,0 +1,766 @@
1
+ // Who a request is from, by the identity headers Tailscale's serve proxy
2
+ // adds: the proof that a request really came through that proxy. Shared by
3
+ // the hosted server's tailnet sign-in (src/hosted/server.js) and the local
4
+ // board's `serve --tailscale` owner check (src/server/pairing-routes.js).
5
+ //
6
+ // What Tailscale does (https://tailscale.com/kb/1312/serve, "Identity
7
+ // headers"; ipn/ipnlocal/serve.go addTailscaleIdentityHeaders, read in
8
+ // 1.104): on every request its HTTP proxy forwards, tailscaled removes any
9
+ // Tailscale-User-Login / -Name / -Profile-Pic and Tailscale-Funnel-Request a
10
+ // client sent; for a tailnet device that belongs to a user it sets them
11
+ // (non-ASCII values in RFC 2047 "Q" encoding); for a tagged device and for
12
+ // Funnel traffic it sets none. It sets X-Forwarded-For to the tailnet
13
+ // address the request came from, and joins the path of its target to the
14
+ // request's path.
15
+ //
16
+ // The headers mean something only on a request that proxy sent. The server
17
+ // listens on 127.0.0.1, and other things can open that port and write the
18
+ // same headers:
19
+ // - any program on the machine;
20
+ // - a tailnet peer, when tailscaled runs in userspace-networking mode: its
21
+ // netstack forwards a raw TCP connection to the node's tailnet address,
22
+ // on a port serve does not handle, to 127.0.0.1:<same port>, dialled by
23
+ // tailscaled itself (wgengine/netstack acceptTCP);
24
+ // - a local user through tailscaled's LocalAPI dial (`tailscale nc`,
25
+ // before 1.98), or through tailscaled's own SOCKS5 or HTTP proxy.
26
+ // The last three arrive from a socket that tailscaled owns. So no single
27
+ // check is proof. An identity is believed only when ALL of these hold:
28
+ //
29
+ // 1. THE SECRET. The serve entry this process creates points at
30
+ // http://127.0.0.1:<port>/_ts/<secret>, a random value made at each
31
+ // start. Serve puts that path in front of every request it proxies; a
32
+ // raw forward, a dial or a proxy passes the client's own path. A request
33
+ // without it is never asked who it is. This stops a tailnet peer and
34
+ // anything else that cannot read this machine's serve config. It does
35
+ // NOT stop a local user: any local user can read the serve config
36
+ // through the LocalAPI (`tailscale serve status`), secret included.
37
+ // 2. THE PEER. The connection's other end is a socket owned by root (the
38
+ // user tailscaled runs as), read from the kernel's socket table,
39
+ // /proc/net/tcp. This stops a local user who connects to the port
40
+ // directly with the secret: that socket is their own. (It does not stop
41
+ // one who goes through tailscaled's own serve listener: see 5.) It is
42
+ // only meaningful while tailscaled gives
43
+ // nobody a way to make it dial loopback for them, so the feature is off
44
+ // (the server refuses to start, and trust is suspended while it runs)
45
+ // when tailscaled is in userspace-networking mode, is older than 1.98,
46
+ // runs a SOCKS5 or outbound HTTP proxy, cannot be found or read in
47
+ // /proc, does not run as root, or when this process is in a container
48
+ // or a user namespace where "root" is not the machine's root.
49
+ // 3. TAILSCALED VOUCHES. For each request, tailscaled is asked who owns
50
+ // the address in X-Forwarded-For (LocalAPI whois, through the CLI): it
51
+ // must be a user's device, not tagged, of the same login as the header.
52
+ // Not proof alone (the address is a header too), required in addition.
53
+ // 4. THE HEADERS. Exactly one Tailscale-User-Login, no
54
+ // Tailscale-Funnel-Request, a value that decodes to a plain login.
55
+ // 5. NOT THIS MACHINE. Any program on the server's machine can ask for
56
+ // the serve URL itself (https://<machine>.ts.net/...). tailscaled
57
+ // answers same-machine connections too: the source is the machine's own
58
+ // tailnet address, whois names the machine's owner, serve sets the
59
+ // owner's login and dials loopback as root, with the secret. Checks 1
60
+ // to 4 all pass, for any local user. So an identity whose source is
61
+ // this node is never honoured: X-Forwarded-For must not be one of this
62
+ // node's own tailnet addresses, and the node whois names must not be
63
+ // this node (by its stable id and its addresses, never by a name).
64
+ // When this node cannot be determined, nobody is believed. The owner
65
+ // at the server's own machine uses what does not rest on the tailnet:
66
+ // the settings token on localhost (a local board), a passkey (hosted).
67
+ //
68
+ // What is still trusted: root on the machine, and whoever may change
69
+ // tailscaled's serve config there (the Tailscale operator). Nothing else on
70
+ // the machine, and nothing on the tailnet.
71
+ //
72
+ // The secret never leaves this process except in the argument to `tailscale
73
+ // serve`: it is in no log line, error or response (admit() answers a wrong
74
+ // one with a plain 404).
75
+
76
+ import fs from 'node:fs'
77
+ import { execFile } from 'node:child_process'
78
+ import os from 'node:os'
79
+ import net from 'node:net'
80
+ import { randomBytes, timingSafeEqual } from 'node:crypto'
81
+
82
+ const LOGIN_HEADER = 'tailscale-user-login'
83
+ const NAME_HEADER = 'tailscale-user-name'
84
+ const FUNNEL_HEADER = 'tailscale-funnel-request'
85
+ export const SECRET_PREFIX = '/_ts/'
86
+ export const TAILSCALE_MIN_VERSION = [1, 98]
87
+
88
+ // A tailnet login: user@domain, user@github, name@passkey. ASCII only, as
89
+ // compared (lower case).
90
+ export const TAILNET_LOGIN_RE = /^[a-z0-9][a-z0-9._+-]{0,63}@[a-z0-9][a-z0-9.-]{0,189}$/
91
+
92
+ export function cleanTailnetLogin(value) {
93
+ if (typeof value !== 'string') return null
94
+ const login = value.trim().toLowerCase()
95
+ return login.length <= 254 && TAILNET_LOGIN_RE.test(login) ? login : null
96
+ }
97
+
98
+ const CONTROL_CODES = [
99
+ [0x00, 0x1f],
100
+ [0x7f, 0x9f],
101
+ [0x200b, 0x200f],
102
+ [0x202a, 0x202e],
103
+ [0x2066, 0x2069],
104
+ ]
105
+ const isControl = (code) => CONTROL_CODES.some(([from, to]) => code >= from && code <= to)
106
+ const stripControl = (text) => [...text].filter((char) => !isControl(char.codePointAt(0))).join('')
107
+ const ENCODED_WORD = /^=\?([^?\s]+)\?([QqBb])\?([^?\s]*)\?=$/
108
+
109
+ // A header value as text: plain ASCII as it is, or RFC 2047 encoded words
110
+ // (UTF-8 only; several words are one text). null for anything else: other
111
+ // character sets, a broken escape, bytes that are not UTF-8, raw non-ASCII.
112
+ export function decodeHeaderValue(raw) {
113
+ if (typeof raw !== 'string') return null
114
+ const value = raw.trim()
115
+ if (!value.includes('=?')) return [...value].every((char) => char.charCodeAt(0) >= 0x20 && char.charCodeAt(0) <= 0x7e) ? value : null
116
+ const chunks = []
117
+ for (const word of value.split(/[ \t]+/)) {
118
+ const match = ENCODED_WORD.exec(word)
119
+ if (!match || match[1].toLowerCase() !== 'utf-8') return null
120
+ const text = match[3]
121
+ if (match[2].toLowerCase() === 'b') {
122
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(text) || text.length % 4 !== 0) return null
123
+ chunks.push(Buffer.from(text, 'base64'))
124
+ continue
125
+ }
126
+ const bytes = []
127
+ for (let index = 0; index < text.length; index += 1) {
128
+ const char = text[index]
129
+ if (char === '_') bytes.push(0x20)
130
+ else if (char === '=') {
131
+ const hex = text.slice(index + 1, index + 3)
132
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return null
133
+ bytes.push(Number.parseInt(hex, 16))
134
+ index += 2
135
+ } else if (char.charCodeAt(0) > 0x20 && char.charCodeAt(0) < 0x7f) bytes.push(char.charCodeAt(0))
136
+ else return null
137
+ }
138
+ chunks.push(Buffer.from(bytes))
139
+ }
140
+ try {
141
+ return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))
142
+ } catch {
143
+ return null
144
+ }
145
+ }
146
+
147
+ // How many times a header was sent (Node joins repeats with ", ").
148
+ const sent = (req, name) => {
149
+ let count = 0
150
+ const raw = req.rawHeaders || []
151
+ for (let index = 0; index < raw.length; index += 2) if (String(raw[index]).toLowerCase() === name) count += 1
152
+ return count
153
+ }
154
+
155
+ // { login, name } from a request's identity headers, or { problem } saying
156
+ // why they name nobody. Does not decide whether the headers can be believed.
157
+ export function parseIdentity(req) {
158
+ const headers = req.headers || {}
159
+ if (headers[FUNNEL_HEADER] !== undefined) return { problem: 'funnel' }
160
+ if (headers[LOGIN_HEADER] === undefined) return { problem: 'absent' }
161
+ if (sent(req, LOGIN_HEADER) !== 1) return { problem: 'repeated' }
162
+ const decoded = decodeHeaderValue(headers[LOGIN_HEADER])
163
+ if (decoded === null) return { problem: 'encoding' }
164
+ if (!decoded.trim()) return { problem: 'empty' }
165
+ const login = cleanTailnetLogin(decoded)
166
+ if (!login) return { problem: 'not_a_login' }
167
+ let name = sent(req, NAME_HEADER) === 1 ? decodeHeaderValue(headers[NAME_HEADER]) : null
168
+ name = name ? stripControl(name).replace(/\s+/g, ' ').trim().slice(0, 60) : ''
169
+ return { login, name: name || login.split('@')[0] }
170
+ }
171
+
172
+ // The tailnet address serve says the request came from: exactly one
173
+ // X-Forwarded-For value, an address in Tailscale's ranges (100.64.0.0/10,
174
+ // fd7a:115c:a1e0::/48). null otherwise.
175
+ export function forwardedTailnetAddress(req) {
176
+ if (sent(req, 'x-forwarded-for') !== 1) return null
177
+ const value = String(req.headers['x-forwarded-for'] || '').trim()
178
+ const v4 = /^100\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(value)
179
+ if (v4) {
180
+ const [second, third, fourth] = v4.slice(1).map(Number)
181
+ return second >= 64 && second <= 127 && third <= 255 && fourth <= 255 ? value : null
182
+ }
183
+ return /^fd7a:115c:a1e0(?::[0-9a-f]{0,4}){1,5}$/i.test(value) ? value.toLowerCase() : null
184
+ }
185
+
186
+ // ---- The peer of a loopback connection (Linux) ------------------------------
187
+
188
+ // "0100007F:1F90" for 127.0.0.1:8080, as /proc/net/tcp writes it: the
189
+ // address as the machine holds it in memory (network order bytes read as a
190
+ // native integer), the port as a plain number.
191
+ export function procAddress(address, port, endianness = os.endianness()) {
192
+ const parts = String(address).split('.').map(Number)
193
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null
194
+ const bytes = endianness === 'LE' ? [...parts].reverse() : parts
195
+ return `${bytes.map((byte) => byte.toString(16).padStart(2, '0')).join('')}:${Number(port).toString(16).padStart(4, '0')}`.toUpperCase()
196
+ }
197
+
198
+ // The user id that owns the socket at the other end of a loopback
199
+ // connection, from the text of /proc/net/tcp; null when there is no such
200
+ // row (the peer is gone, or it is not on this machine). While this end is
201
+ // open no other connection can have the same four addresses, so the row
202
+ // cannot belong to anyone else.
203
+ export function peerOwner(table, { remoteAddress, remotePort, localAddress, localPort }, endianness = os.endianness()) {
204
+ const theirs = procAddress(remoteAddress, remotePort, endianness)
205
+ const ours = procAddress(localAddress, localPort, endianness)
206
+ if (!theirs || !ours) return null
207
+ let owner = null
208
+ let rows = 0
209
+ for (const line of String(table).split('\n')) {
210
+ const fields = line.trim().split(/\s+/)
211
+ if (fields.length < 8 || fields[1].toUpperCase() !== theirs || fields[2].toUpperCase() !== ours) continue
212
+ if (!/^\d+$/.test(fields[7])) return null
213
+ owner = Number(fields[7])
214
+ rows += 1
215
+ }
216
+ return rows === 1 ? owner : null
217
+ }
218
+
219
+ const isLoopback = (address) => typeof address === 'string' && /^127\.\d+\.\d+\.\d+$/.test(address)
220
+
221
+ // proof.trusted(socket): whether the connection comes from a socket owned by
222
+ // root. proof.problem(): why this machine cannot tell, or null. There is no
223
+ // way to name another user: a tailscaled that does not run as root (userspace
224
+ // networking) is one the feature refuses anyway.
225
+ export function procPeerProof({ read = () => fs.readFileSync('/proc/net/tcp', 'utf8'), platform = process.platform } = {}) {
226
+ const ownerOf = (socket) => {
227
+ if (!socket || socket.remoteFamily !== 'IPv4' || !isLoopback(socket.remoteAddress) || !isLoopback(socket.localAddress)) return null
228
+ let table
229
+ try {
230
+ table = read()
231
+ } catch {
232
+ return null
233
+ }
234
+ return peerOwner(table, socket)
235
+ }
236
+ return {
237
+ ownerOf,
238
+ trusted: (socket) => ownerOf(socket) === 0,
239
+ problem() {
240
+ if (platform !== 'linux')
241
+ return `this needs Linux: the server proves that a request came from tailscaled by the owner of the connection's other end, which it reads from /proc/net/tcp. On ${platform} it cannot tell tailscaled from any other program on this machine, and that program could sign in as anyone.`
242
+ try {
243
+ if (!/\buid\b/.test(read().split('\n')[0] || '')) return '/proc/net/tcp does not list socket owners here.'
244
+ } catch (error) {
245
+ return `/proc/net/tcp cannot be read (${error.code || error.message}), so the server cannot prove that a request came from tailscaled.`
246
+ }
247
+ return null
248
+ },
249
+ }
250
+ }
251
+
252
+ // The proof must see this process's own connection to its listener as this
253
+ // process's: where it cannot (a container that hides /proc, another network
254
+ // namespace), it could not tell tailscaled from anyone else either. Returns
255
+ // the problem, or null. `server`: a listening net/http server on 127.0.0.1.
256
+ export async function proofSelfTest(server, proof) {
257
+ if (!proof.ownerOf || typeof process.getuid !== 'function') return null
258
+ const accepted = new Promise((resolve) => server.once('connection', resolve))
259
+ const client = net.connect(server.address().port, '127.0.0.1')
260
+ client.on('error', () => {})
261
+ try {
262
+ const socket = await accepted
263
+ const owner = proof.ownerOf(socket)
264
+ socket.destroy()
265
+ return owner === process.getuid()
266
+ ? null
267
+ : 'the check that tells tailscaled from other programs did not recognise a test connection from this process (is /proc/net/tcp hidden or from another network namespace?).'
268
+ } finally {
269
+ client.destroy()
270
+ }
271
+ }
272
+
273
+ // ---- Is tailscaled one whose connections can be believed? -----------------------
274
+
275
+ // tailscaled's debug switches that make its netstack forward connections to
276
+ // loopback (wgengine/netstack): with either, a peer's raw connection can be
277
+ // dialled by tailscaled itself.
278
+ const DEBUG_SWITCHES = ['TS_DEBUG_NETSTACK_LOOPBACK_PORT', 'TS_DEBUG_NETSTACK_SUBNETS']
279
+
280
+ // The pid systemd runs tailscaled.service as, or null (no systemd, no such
281
+ // unit, or it is not running). Any user may ask. Asynchronous: this is asked
282
+ // at start and by the half-minute watch of a running server, and a server
283
+ // must not stand still while systemctl answers.
284
+ export function systemdMainPid(unit = 'tailscaled.service', run = execFile) {
285
+ return new Promise((resolve) => {
286
+ const done = (error, stdout) => {
287
+ const pid = error ? Number.NaN : Number.parseInt(String(stdout).trim(), 10)
288
+ resolve(Number.isSafeInteger(pid) && pid > 0 ? pid : null)
289
+ }
290
+ try {
291
+ run('systemctl', ['show', '--property=MainPID', '--value', unit], { encoding: 'utf8', timeout: 3000 }, done)
292
+ } catch {
293
+ resolve(null)
294
+ }
295
+ })
296
+ }
297
+
298
+ // hostFacts for a real machine: asks systemd which process tailscaled is
299
+ // (without blocking), then reads /proc. What the servers call at start and
300
+ // in their watch; never on the path of a request.
301
+ export async function machineFacts(options = {}) {
302
+ return hostFacts({ ...options, mainPid: await systemdMainPid() })
303
+ }
304
+
305
+ // What this machine says about tailscaled and about where this process runs.
306
+ // { tailscaled: [{ pid, uid, argv, env }], unreadable: n, container: reason | null }
307
+ //
308
+ // Which process is tailscaled:
309
+ // - Where systemd runs it (`mainPid`: the MainPID of tailscaled.service),
310
+ // that process and no other, whatever anything else on the machine is
311
+ // called. It is the daemon the `tailscale` command talks to and the one
312
+ // that dials the serve target.
313
+ // - Otherwise by name (comm "tailscaled"), which anyone can give a program.
314
+ // And in both cases only a process that is root in all four of its ids (the
315
+ // `Uid:` line of /proc/<pid>/status: real, effective, saved, filesystem). A
316
+ // setuid-root program that an ordinary user started under the name
317
+ // "tailscaled" is root only in some of them: it is not tailscaled, and it
318
+ // must neither be believed nor be able to switch the feature off for
319
+ // everyone by being counted as a second daemon. Where this process may read
320
+ // it (it is root itself), the executable must also be a file called
321
+ // tailscaled that root owns.
322
+ // `env`: the names of the debug switches found in its environment, or null
323
+ // when that cannot be read (normal for a server that is not root: what root
324
+ // put in tailscaled's environment is then trusted root configuration).
325
+ // `mainPid`: the unit's main process when the caller asked systemd (machineFacts); null: go by name.
326
+ export function hostFacts({ proc = '/proc', read = fs, env = process.env, mainPid = null } = {}) {
327
+ const facts = { tailscaled: [], unreadable: 0, container: null }
328
+ let pids = []
329
+ try {
330
+ pids = read.readdirSync(proc).filter((name) => /^\d+$/.test(name))
331
+ } catch {
332
+ facts.unreadable += 1
333
+ }
334
+ const main = typeof mainPid === 'function' ? mainPid() : mainPid
335
+ const known = Number.isSafeInteger(main) && main > 0 ? String(main) : null
336
+ if (known && !pids.includes(known)) pids = []
337
+ for (const pid of known ? [known] : pids) {
338
+ if (!known) {
339
+ let comm
340
+ try {
341
+ comm = read.readFileSync(`${proc}/${pid}/comm`, 'utf8').trim()
342
+ } catch {
343
+ continue // gone, or hidden
344
+ }
345
+ if (comm !== 'tailscaled') continue
346
+ }
347
+ // Root in every id, or it is somebody's program under that name: ignored.
348
+ let ids
349
+ try {
350
+ ids = /^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*$/m.exec(read.readFileSync(`${proc}/${pid}/status`, 'utf8'))
351
+ } catch {
352
+ continue // gone
353
+ }
354
+ if (!ids) {
355
+ facts.unreadable += 1
356
+ continue
357
+ }
358
+ if (ids.slice(1).some((id) => id !== '0')) continue
359
+ const uid = 0
360
+ if (!known) {
361
+ try {
362
+ const exe = read.readlinkSync(`${proc}/${pid}/exe`)
363
+ if (!/(^|\/)tailscaled(?: \(deleted\))?$/.test(exe)) continue
364
+ try {
365
+ if (read.statSync(exe.replace(/ \(deleted\)$/, '')).uid !== 0) continue
366
+ } catch {
367
+ /* replaced by an update while it runs: the name is what there is */
368
+ }
369
+ } catch {
370
+ /* not readable by this user: root's process with that name is taken as it is */
371
+ }
372
+ }
373
+ try {
374
+ const argv = read.readFileSync(`${proc}/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean)
375
+ if (!argv.length) throw new Error('empty')
376
+ let env = null
377
+ try {
378
+ const names = read
379
+ .readFileSync(`${proc}/${pid}/environ`, 'utf8')
380
+ .split('\0')
381
+ .map((pair) => pair.split('=')[0])
382
+ env = DEBUG_SWITCHES.filter((name) => names.includes(name))
383
+ } catch {
384
+ env = null
385
+ }
386
+ facts.tailscaled.push({ pid: Number(pid), uid, argv, env })
387
+ } catch {
388
+ facts.unreadable += 1
389
+ }
390
+ }
391
+ const text = (file) => {
392
+ try {
393
+ return read.readFileSync(file, 'utf8')
394
+ } catch {
395
+ return null
396
+ }
397
+ }
398
+ const exists = (file) => {
399
+ try {
400
+ read.statSync(file)
401
+ return true
402
+ } catch {
403
+ return false
404
+ }
405
+ }
406
+ const uidMap = text(`${proc}/self/uid_map`)
407
+ const cgroup = text(`${proc}/1/cgroup`) || ''
408
+ if (uidMap === null) facts.container = 'its user namespace cannot be read'
409
+ else if (!/^\s*0\s+0\s+4294967295\s*$/.test(uidMap.trim()))
410
+ facts.container = 'it runs in a user namespace, where root is not the machine’s root'
411
+ else if (exists('/.dockerenv') || exists('/run/.containerenv')) facts.container = 'it runs in a container'
412
+ else if (env.container || env.KUBERNETES_SERVICE_HOST) facts.container = 'it runs in a container'
413
+ else if (/docker|kubepods|containerd|lxc|libpod/.test(cgroup)) facts.container = 'it runs in a container'
414
+ return facts
415
+ }
416
+
417
+ const flagValue = (argv, name) => {
418
+ for (let index = 0; index < argv.length; index += 1) {
419
+ const arg = argv[index].replace(/^--/, '-')
420
+ if (arg === `-${name}`) return argv[index + 1] ?? ''
421
+ if (arg.startsWith(`-${name}=`)) return arg.slice(name.length + 2)
422
+ }
423
+ return null
424
+ }
425
+
426
+ // Why tailscaled's connections to loopback cannot be taken as the serve
427
+ // proxy's, or null. `status`: the parsed `tailscale status --json`.
428
+ export function tailscaledProblem(status, facts) {
429
+ if (facts.container) return `this process cannot tell whose "root" a connection comes from: ${facts.container}`
430
+ if (facts.unreadable) return 'tailscaled’s command line cannot be read in /proc, so how it runs cannot be checked'
431
+ if (facts.tailscaled.length !== 1)
432
+ return facts.tailscaled.length
433
+ ? 'more than one tailscaled runs on this machine'
434
+ : 'no tailscaled process of root is visible to this server (userspace tailscaled, another machine, container or process namespace?)'
435
+ const daemon = facts.tailscaled[0]
436
+ if (daemon.uid !== 0) return 'tailscaled does not run as root here'
437
+ if (daemon.env?.length)
438
+ return `tailscaled runs with ${daemon.env.join(' and ')} set, which makes it forward connections to this machine’s loopback itself`
439
+ const tun = flagValue(daemon.argv, 'tun')
440
+ if (tun === 'userspace-networking' || status?.TUN !== true)
441
+ return 'tailscaled runs in userspace-networking mode, where it forwards any tailnet device’s raw TCP connection to this machine’s loopback ports itself'
442
+ if (flagValue(daemon.argv, 'socks5-server'))
443
+ return 'tailscaled runs a SOCKS5 proxy (--socks5-server), which opens connections for local programs'
444
+ if (flagValue(daemon.argv, 'outbound-http-proxy-listen'))
445
+ return 'tailscaled runs an outbound HTTP proxy (--outbound-http-proxy-listen), which opens connections for local programs'
446
+ const version = /^(\d+)\.(\d+)/.exec(String(status?.Version || ''))
447
+ if (!version) return 'tailscaled’s version cannot be read'
448
+ const [major, minor] = [Number(version[1]), Number(version[2])]
449
+ if (major < TAILSCALE_MIN_VERSION[0] || (major === TAILSCALE_MIN_VERSION[0] && minor < TAILSCALE_MIN_VERSION[1]))
450
+ return `Tailscale ${major}.${minor} is too old: before ${TAILSCALE_MIN_VERSION.join('.')} any local user can make tailscaled open a connection for them (tailscale nc). Update Tailscale`
451
+ return null
452
+ }
453
+
454
+ // whois from the answer of `tailscale whois --json <address>`: { login,
455
+ // userId, expired, tagged, stableId, addresses } or null (no such peer, or an answer that
456
+ // names no user). stableId and addresses say which node it is.
457
+ export function whoisAnswer(stdout, now = Date.now()) {
458
+ let data
459
+ try {
460
+ data = JSON.parse(stdout)
461
+ } catch {
462
+ return null
463
+ }
464
+ if (!data || typeof data !== 'object' || !data.Node || typeof data.Node !== 'object') return null
465
+ const login = cleanTailnetLogin(data.UserProfile?.LoginName)
466
+ if (!login) return null
467
+ // Tailscale's own id of the user (a number, or a string in newer versions): what a login string stands for.
468
+ const rawUser = data.UserProfile?.ID ?? data.Node.User
469
+ const userId =
470
+ ['number', 'string'].includes(typeof rawUser) && /^[A-Za-z0-9_-]{1,64}$/.test(String(rawUser)) && String(rawUser) !== '0'
471
+ ? String(rawUser)
472
+ : null
473
+ // A node whose key expired is no longer that person's device as far as the tailnet goes.
474
+ const expiry = typeof data.Node.KeyExpiry === 'string' ? Date.parse(data.Node.KeyExpiry) : Number.NaN
475
+ const expired = data.Node.Expired === true || (Number.isFinite(expiry) && expiry > Date.parse('1970-01-02T00:00:00Z') && expiry <= now)
476
+ return {
477
+ login,
478
+ userId,
479
+ expired,
480
+ tagged: Array.isArray(data.Node.Tags) && data.Node.Tags.length > 0,
481
+ stableId: typeof data.Node.StableID === 'string' && data.Node.StableID ? data.Node.StableID : null,
482
+ addresses: (Array.isArray(data.Node.Addresses) ? data.Node.Addresses : [])
483
+ .map((value) => canonicalAddress(String(value).replace(/\/\d+$/, '')))
484
+ .filter(Boolean),
485
+ }
486
+ }
487
+
488
+ // An address in one spelling, to compare: IPv4 as it is, IPv6 as eight
489
+ // groups without leading zeros. null when it is neither.
490
+ export function canonicalAddress(value) {
491
+ const text = String(value ?? '')
492
+ .trim()
493
+ .toLowerCase()
494
+ .replace(/%.*$/, '')
495
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(text))
496
+ return text.split('.').every((part) => Number(part) <= 255) ? text.split('.').map(Number).join('.') : null
497
+ if (!/^[0-9a-f:]+$/.test(text) || !text.includes(':')) return null
498
+ const halves = text.split('::')
499
+ if (halves.length > 2) return null
500
+ const head = halves[0] ? halves[0].split(':') : []
501
+ const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : []
502
+ const missing = 8 - head.length - tail.length
503
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return null
504
+ const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill('0'), ...tail]
505
+ if (groups.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) return null
506
+ return groups.map((group) => Number.parseInt(group, 16).toString(16)).join(':')
507
+ }
508
+
509
+ // This node, from `tailscale status --json`: its stable id and its own
510
+ // tailnet addresses (IPv4 and IPv6). null when either is missing: then
511
+ // nobody is believed.
512
+ export function selfFromStatus(status) {
513
+ const stableId = typeof status?.Self?.ID === 'string' && status.Self.ID ? status.Self.ID : null
514
+ const addresses = [
515
+ ...(Array.isArray(status?.Self?.TailscaleIPs) ? status.Self.TailscaleIPs : []),
516
+ ...(Array.isArray(status?.TailscaleIPs) ? status.TailscaleIPs : []),
517
+ ]
518
+ .map(canonicalAddress)
519
+ .filter(Boolean)
520
+ if (!stableId || !addresses.length) return null
521
+ return { stableId, addresses: [...new Set(addresses)] }
522
+ }
523
+
524
+ // ---- The serve config ------------------------------------------------------------
525
+
526
+ // Tailnet sign-in believes the identity headers only on requests that
527
+ // tailscaled's HTTP proxy sent (src/hosted/tailnet-identity.js). The proxy
528
+ // removes whatever identity headers a client sent and sets its own; a raw
529
+ // TCP forward does neither, so a tailnet device could write any login
530
+ // through one. This says what in a serve config (`tailscale serve status
531
+ // --json`) breaks that, or null when the only thing that reaches this
532
+ // server's local port is the one HTTPS entry this process added:
533
+ // - a TCP forward (plain or TLS-terminated) to the local port;
534
+ // - any other serve entry that proxies to it (another port or path, a
535
+ // foreground session, a service);
536
+ // - Funnel switched on for the tailnet port;
537
+ // - the entry itself gone or changed.
538
+ export function serveProblem(config, { dnsName, httpsPort, localPort, target = `http://127.0.0.1:${localPort}` }) {
539
+ const own = `${dnsName}:${httpsPort}`
540
+ let ours = 0
541
+ const entries = [config, ...Object.values(config?.Foreground || {}), ...Object.values(config?.Services || {})]
542
+ for (const entry of entries) {
543
+ if (!entry || typeof entry !== 'object') continue
544
+ for (const [port, tcp] of Object.entries(entry.TCP || {}))
545
+ if (tcp?.TCPForward && reachesLocalPort(tcp.TCPForward, localPort))
546
+ return `a raw TCP forward on tailnet port ${port} points at this server, and a TCP forward passes identity headers through unchecked`
547
+ for (const [key, web] of Object.entries(entry.Web || {}))
548
+ for (const [mount, handler] of Object.entries(web?.Handlers || {})) {
549
+ if (!handler?.Proxy || !reachesLocalPort(handler.Proxy, localPort)) continue
550
+ if (entry === config && key === own && mount === '/' && handler.Proxy === target) ours += 1
551
+ else return `another tailscale serve entry (${key}${mount}) points at this server`
552
+ }
553
+ for (const [key, on] of Object.entries(entry.AllowFunnel || {})) if (on && key === own) return `Funnel is on for ${own}`
554
+ }
555
+ if (ours !== 1) return 'the tailscale serve entry this server added is gone or was changed'
556
+ return null
557
+ }
558
+
559
+ // Whether a serve target (a Proxy URL, a TCPForward address, or as the CLI
560
+ // also takes them: a bare port, "localhost:3000") can be this machine's
561
+ // loopback on `port`. Every spelling of loopback counts: 127.0.0.0/8,
562
+ // localhost (also with a trailing dot or as a subdomain), ::1 and the
563
+ // IPv4-mapped forms, 0.0.0.0 and ::, an empty host. A host name that cannot
564
+ // be told apart counts too: only an address that is plainly another
565
+ // machine's does not.
566
+ export function reachesLocalPort(value, port) {
567
+ let text = String(value ?? '')
568
+ .trim()
569
+ .toLowerCase()
570
+ if (!text || text.startsWith('unix:')) return false
571
+ if (/^\d+$/.test(text)) return Number(text) === Number(port)
572
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//.exec(text)
573
+ text = text.slice(scheme ? scheme[0].length : 0).replace(/[/?#].*$/, '')
574
+ text = text.slice(text.lastIndexOf('@') + 1)
575
+ let host = text
576
+ let targetPort = null
577
+ const bracket = /^\[([^\]]*)\](?::(\d+))?$/.exec(text)
578
+ if (bracket) {
579
+ host = bracket[1]
580
+ targetPort = bracket[2] ?? null
581
+ } else if ((text.match(/:/g) || []).length === 1) {
582
+ host = text.slice(0, text.indexOf(':'))
583
+ targetPort = text.slice(text.indexOf(':') + 1)
584
+ }
585
+ if (targetPort === null || targetPort === '') targetPort = scheme && /^https/.test(scheme[1]) ? '443' : scheme ? '80' : null
586
+ if (targetPort === null || Number(targetPort) !== Number(port)) return false
587
+ host = host.replace(/\.$/, '').replace(/%.*$/, '')
588
+ if (host === '' || host === 'localhost' || host.endsWith('.localhost')) return true
589
+ if (/^\d+(\.\d+){3}$/.test(host)) return host.startsWith('127.') || host === '0.0.0.0'
590
+ if (host.includes(':')) {
591
+ const mapped = /^(?:0*:)*:?ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(host)
592
+ if (mapped) return mapped[1].startsWith('127.') || mapped[1] === '0.0.0.0'
593
+ return /^(?:0*:)+0*1?$/.test(host) || host === '::'
594
+ }
595
+ // A number in another notation (0x7f.1, 2130706433) or a name that may resolve here.
596
+ return true
597
+ }
598
+
599
+ // ---- The gate ------------------------------------------------------------------
600
+
601
+ export const newServeSecret = () => randomBytes(32).toString('base64url')
602
+ // The local URL a serve entry points at: the port and the secret path.
603
+ export const serveTarget = (port, secret) => `http://127.0.0.1:${port}${SECRET_PREFIX}${secret}`
604
+
605
+ const WHOIS_TTL_MS = 60_000
606
+
607
+ // createTailnetGate({ secret, proof, whois }) ->
608
+ // admit(req, res?) first thing for every request and upgrade (async):
609
+ // takes the secret path off the URL and works out who
610
+ // the request is from. false: it answered (a wrong
611
+ // secret, 404) and the request is over.
612
+ // identityOf(req) { login, name } for an admitted request that passed
613
+ // every check, else null. Synchronous.
614
+ // suspend(reason) / resume() / suspended()
615
+ //
616
+ // ownMachine(req) true when the request named someone but came from this
617
+ // machine itself (so the page can say why it is nobody)
618
+ //
619
+ // whois(address): async, { login, tagged, stableId, addresses } | null (see
620
+ // whoisAnswer). self(): this node now, { stableId, addresses } | null (see
621
+ // selfFromStatus); without it nobody is believed.
622
+ export function createTailnetGate({
623
+ secret,
624
+ proof,
625
+ whois,
626
+ self = () => null,
627
+ interfaces = () => os.networkInterfaces(),
628
+ log = () => {},
629
+ now = () => Date.now(),
630
+ }) {
631
+ if (typeof secret !== 'string' || secret.length < 32) throw new Error('the serve secret: at least 32 characters')
632
+ const marked = Buffer.from(`${SECRET_PREFIX}${secret}`)
633
+ const proven = new WeakMap()
634
+ const vouched = new WeakMap() // socket -> Map(address -> { at, answer })
635
+ const answers = new WeakMap()
636
+ const fromHere = new WeakSet()
637
+ // Every address this machine has right now, asked on each request: `self`
638
+ // comes from `tailscale status` and is half a minute old at worst, and an
639
+ // address that tailscaled was given since must count as this machine at once.
640
+ const localAddresses = () => {
641
+ try {
642
+ return Object.values(interfaces() || {})
643
+ .flat()
644
+ .map((item) => canonicalAddress(item?.address))
645
+ .filter(Boolean)
646
+ } catch {
647
+ return []
648
+ }
649
+ }
650
+ let suspendedFor = null
651
+ let loggedAt = -Infinity
652
+ const refused = (why) => {
653
+ // Forged headers are worth a line, but not one per request.
654
+ if (now() - loggedAt < 60_000) return
655
+ loggedAt = now()
656
+ log(`tailnet identity: ignored identity headers (${why})`)
657
+ }
658
+
659
+ // The secret path, taken off the URL. 'yes' | 'no' (no such path) | 'wrong'.
660
+ function takeSecret(req) {
661
+ const url = String(req.url || '')
662
+ if (!url.startsWith(SECRET_PREFIX)) return 'no'
663
+ const end = url.slice(SECRET_PREFIX.length).search(/[/?]/)
664
+ const head = Buffer.from(end < 0 ? url : url.slice(0, SECRET_PREFIX.length + end))
665
+ if (head.length !== marked.length || !timingSafeEqual(head, marked)) return 'wrong'
666
+ const rest = url.slice(head.length)
667
+ req.url = rest.startsWith('/') ? rest : `/${rest}`
668
+ return 'yes'
669
+ }
670
+
671
+ async function vouch(socket, address, login) {
672
+ let known = vouched.get(socket)
673
+ if (!known) vouched.set(socket, (known = new Map()))
674
+ let entry = known.get(address)
675
+ if (!entry || now() - entry.at > WHOIS_TTL_MS) {
676
+ let answer = null
677
+ try {
678
+ answer = await whois(address)
679
+ } catch {
680
+ answer = null
681
+ }
682
+ entry = { at: now(), answer }
683
+ known.set(address, entry)
684
+ }
685
+ const answer = entry.answer
686
+ if (!answer || answer.tagged || answer.login !== login) return { is: 'no' }
687
+ // A device whose key expired is not let in by the tailnet either.
688
+ if (answer.expired) return { is: 'expired' }
689
+ // Which node: without that it cannot be told from this one.
690
+ const here = self()
691
+ if (!here || !answer.stableId) return { is: 'unknown' }
692
+ const local = localAddresses()
693
+ if (answer.stableId === here.stableId || answer.addresses.some((item) => here.addresses.includes(item) || local.includes(item)))
694
+ return { is: 'self' }
695
+ // Which user: the login is a name, and a name can be given to someone else later. Accounts are held
696
+ // to Tailscale's own id of the user (src/hosted/tailnet.js), so an answer without one names nobody.
697
+ if (!answer.userId) return { is: 'no-user' }
698
+ return { is: 'yes', userId: answer.userId }
699
+ }
700
+
701
+ async function admit(req, res = null) {
702
+ // Once per request (the listener asks first; an application may ask again).
703
+ if (answers.has(req)) return true
704
+ const secretState = takeSecret(req)
705
+ if (secretState === 'wrong') {
706
+ // Never say more: not that the path exists, not what was wrong with it.
707
+ if (res) {
708
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'X-Content-Type-Options': 'nosniff' })
709
+ res.end('Not found')
710
+ } else req.socket?.destroy()
711
+ return false
712
+ }
713
+ let answer = null
714
+ if (req.headers?.[LOGIN_HEADER] !== undefined) {
715
+ const socket = req.socket
716
+ if (suspendedFor) refused(suspendedFor)
717
+ else if (secretState !== 'yes') refused('the request did not come through this server’s serve entry')
718
+ else {
719
+ if (socket && !proven.has(socket)) proven.set(socket, Boolean(proof.trusted(socket)))
720
+ if (!socket || !proven.get(socket)) refused('the connection did not come from tailscaled')
721
+ else {
722
+ const parsed = parseIdentity(req)
723
+ const address = forwardedTailnetAddress(req)
724
+ if (parsed.problem) {
725
+ if (parsed.problem !== 'funnel') refused(`header ${parsed.problem}`)
726
+ } else if (!address) refused('no tailnet address in X-Forwarded-For')
727
+ else {
728
+ const here = self()
729
+ const source = canonicalAddress(address)
730
+ if (!here) refused('this machine’s own tailnet addresses are not known')
731
+ else if (here.addresses.includes(source) || localAddresses().includes(source)) {
732
+ fromHere.add(req)
733
+ refused('the request came from this machine itself')
734
+ } else {
735
+ const vouched = await vouch(socket, address, parsed.login)
736
+ if (vouched.is === 'yes') answer = { ...parsed, userId: vouched.userId }
737
+ else if (vouched.is === 'self') {
738
+ fromHere.add(req)
739
+ refused('the request came from this machine itself')
740
+ } else if (vouched.is === 'unknown') refused('tailscaled does not say which device that address is')
741
+ else if (vouched.is === 'expired') refused('that device’s key has expired')
742
+ else if (vouched.is === 'no-user') refused('tailscaled does not say which user that login is')
743
+ else refused('tailscaled does not say that address is that person’s device')
744
+ }
745
+ }
746
+ }
747
+ }
748
+ }
749
+ answers.set(req, answer)
750
+ return true
751
+ }
752
+
753
+ return {
754
+ admit,
755
+ // Suspended: nobody is believed, also on a request admitted before.
756
+ identityOf: (req) => (suspendedFor || !req ? null : answers.get(req) || null),
757
+ ownMachine: (req) => Boolean(req && fromHere.has(req)),
758
+ suspend(reason) {
759
+ suspendedFor = String(reason || 'suspended')
760
+ },
761
+ resume() {
762
+ suspendedFor = null
763
+ },
764
+ suspended: () => suspendedFor,
765
+ }
766
+ }