pinokiod 8.3.0 → 8.3.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.
@@ -7,7 +7,8 @@
7
7
  Serve-only: nothing is ever exposed publicly (no Funnel).
8
8
 
9
9
  Layout under the Pinokio home:
10
- anywhere/config.json { enabled, hostname }
10
+ anywhere/config.json { enabled, hostname } hostname: pinokio-<id> chosen on first
11
+ enable; installs named before that keep `pinokio`
11
12
  anywhere/tailscaled/tailscaled.state node key + prefs (tailscaled --state)
12
13
  anywhere/tailscaled/ certs, logs (tailscaled --statedir, TS_LOGS_DIR)
13
14
  anywhere/tailscaled/tailscaled.sock LocalAPI socket (mac/linux; falls back to
@@ -26,7 +27,12 @@ const { buildServeConfig, describeServeConfig, sameServeConfig, rewriteHref, LOO
26
27
  const { loadPortMap, savePortMap, assignPorts } = require('./ports')
27
28
  const Util = require('../util')
28
29
 
29
- const DEFAULT_HOSTNAME = 'pinokio'
30
+ const HOSTNAME_ID_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567' // RFC 4648 base32, lowercase
31
+
32
+ // Eight base32 characters, one random byte each (256 is a multiple of 32, so uniform).
33
+ function randomHostname() {
34
+ return 'pinokio-' + Array.from(crypto.randomBytes(8), (byte) => HOSTNAME_ID_ALPHABET[byte % 32]).join('')
35
+ }
30
36
  const DEFAULT_CONNECT_URL_TEMPLATE = 'https://pinokio.co/anywhere/connect#u={address}&a={email}'
31
37
  const MAX_UNIX_SOCKET_PATH = 100 // sun_path is 104 bytes on macOS, 108 on Linux
32
38
  const DAEMON_READY_TIMEOUT_MS = 20000
@@ -43,6 +49,7 @@ class Anywhere {
43
49
  this.child = null
44
50
  this.api = null
45
51
  this.config = null
52
+ this.saving = null // config writes run one at a time (saveConfig)
46
53
  this.starting = null
47
54
  this.lastStatus = null
48
55
  this.lastStatusAt = 0
@@ -117,27 +124,50 @@ class Anywhere {
117
124
  async loadConfig() {
118
125
  if (this.config) return this.config
119
126
  let config = {}
120
- this.configExists = false
127
+ let exists = false
121
128
  try {
122
- const raw = await fs.promises.readFile(this.configPath(), 'utf8')
123
- config = JSON.parse(raw) || {}
124
- this.configExists = true
129
+ config = JSON.parse(await fs.promises.readFile(this.configPath(), 'utf8')) || {}
130
+ exists = true
125
131
  } catch (e) {
126
132
  if (e.code !== 'ENOENT') throw e
127
- config = {}
128
133
  }
129
- this.config = Object.assign({
130
- enabled: false,
131
- hostname: DEFAULT_HOSTNAME,
132
- }, config)
134
+ // A save or another read may have finished meanwhile; a stale read must not replace it.
135
+ if (this.config) return this.config
136
+ this.configExists = exists
137
+ this.config = Object.assign({ enabled: false }, config)
133
138
  return this.config
134
139
  }
135
- async saveConfig(patch) {
136
- const config = Object.assign({}, await this.loadConfig(), patch || {})
137
- await writeJson(this.configPath(), config)
138
- this.config = config
139
- this.configExists = true
140
- return config
140
+ // The saved Tailscale hostname, or null until enable/start has chosen one.
141
+ async hostname() {
142
+ return (await this.loadConfig()).hostname || null
143
+ }
144
+ // Chooses this install's hostname once and saves it, together with `patch`,
145
+ // before anything is sent to Tailscale. Any saved name is kept, so installs
146
+ // named before this keep `pinokio` and are never renamed. The choice happens
147
+ // inside the write queue, so overlapping enable/start calls agree on one
148
+ // name and the saved name is authoritative only once its atomic write succeeds.
149
+ async ensureHostname(patch) {
150
+ const config = await this.saveConfig((current) => current.hostname
151
+ ? (patch || null)
152
+ : Object.assign({ hostname: randomHostname() }, patch))
153
+ return config.hostname
154
+ }
155
+ // Writes run one at a time so a later save never resurrects what an earlier,
156
+ // slower one read. `patch` is an object, or a function of the current config
157
+ // returning the object to merge (null: nothing to write).
158
+ saveConfig(patch) {
159
+ const run = async () => {
160
+ const current = await this.loadConfig()
161
+ const change = typeof patch === 'function' ? patch(current) : patch
162
+ if (!change) return current
163
+ const config = Object.assign({}, current, change)
164
+ await writeJson(this.configPath(), config)
165
+ this.config = config
166
+ this.configExists = true
167
+ return config
168
+ }
169
+ this.saving = (this.saving || Promise.resolve()).then(run, run)
170
+ return this.saving
141
171
  }
142
172
  // true once config.json exists (the first page visit writes it)
143
173
  async configured() {
@@ -148,10 +178,6 @@ class Anywhere {
148
178
  const config = await this.loadConfig()
149
179
  return !!config.enabled
150
180
  }
151
- async hostname() {
152
- const config = await this.loadConfig()
153
- return String(config.hostname || DEFAULT_HOSTNAME)
154
- }
155
181
  connectUrlTemplate() {
156
182
  const fromEnv = (process.env.PINOKIO_ANYWHERE_CONNECT_URL || '').trim()
157
183
  if (fromEnv) return fromEnv
@@ -218,6 +244,8 @@ class Anywhere {
218
244
  throw new Error('Install the matching Tailscale daemon and CLI through Remote setup.')
219
245
  }
220
246
  if (this.stopping) return false
247
+ const hostname = await this.ensureHostname()
248
+ if (this.stopping) return false
221
249
  this.error = null
222
250
  this.statusError = null
223
251
  this.featureError = null
@@ -283,7 +311,7 @@ class Anywhere {
283
311
  }
284
312
  }
285
313
  if (this.stopping) return false
286
- await this.client().setPrefs(await this.hostname())
314
+ await this.client().setPrefs(hostname)
287
315
  this.lastServe = undefined
288
316
  this.lastServeError = null
289
317
  this.lastStatusAt = 0
@@ -354,6 +382,7 @@ class Anywhere {
354
382
  this.statusQuery = null
355
383
  if (this.api) this.api.cancel()
356
384
  if (this.starting) await this.starting.catch(() => {})
385
+ if (this.saving) await this.saving.catch(() => {}) // a queued write must land in this home
357
386
  if (this.syncing) await this.syncing.catch(() => {})
358
387
  if (this.login) await this.login.promise
359
388
  if (this.featureQuery) await this.featureQuery.catch(() => {})
@@ -388,7 +417,7 @@ class Anywhere {
388
417
  }
389
418
  }
390
419
  async enable() {
391
- await this.saveConfig({ enabled: true })
420
+ await this.ensureHostname({ enabled: true })
392
421
  await this.start()
393
422
  return true
394
423
  }
@@ -399,6 +428,8 @@ class Anywhere {
399
428
  }
400
429
  requestLogin(force = false) {
401
430
  if (!this.config || !this.config.enabled || this.login || this.stopping || this.error) return
431
+ const hostname = this.config.hostname
432
+ if (!hostname) { this.error = 'Remote has no saved hostname. Turn it off and on again.'; return }
402
433
  const login = { url: null, error: null, done: false }
403
434
  this.login = login
404
435
  login.promise = this.assertOwnership().then((owned) => {
@@ -408,7 +439,7 @@ class Anywhere {
408
439
  if (update.AuthURL) login.url = update.AuthURL
409
440
  if (update.Error) { login.url = null; login.error = update.Error; this.error = update.Error }
410
441
  this.lastStatusAt = 0
411
- }, force, this.config.hostname)
442
+ }, force, hostname)
412
443
  }).then(() => {
413
444
  login.done = true
414
445
  if (this.login === login) this.login = null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.0",
3
+ "version": "8.3.1",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -207,6 +207,142 @@ test('Anywhere replacements persist settings and stable ports for a fresh reader
207
207
  assert.deepEqual(fs.readdirSync(anywhere.dir()).sort(), ['config.json', 'ports.json'])
208
208
  })
209
209
 
210
+ const HOSTNAME = /^pinokio-[a-z2-7]{8}$/
211
+
212
+ // A started Remote with a verified owned daemon; records every hostname sent to Tailscale.
213
+ function startable(anywhere) {
214
+ const prefs = []
215
+ anywhere.readPid = () => 123
216
+ anywhere.api = { cancel() {}, ping: async () => true, setPrefs: async (hostname) => { prefs.push(hostname) }, status: async () => runningStatus() }
217
+ return prefs
218
+ }
219
+
220
+ test('a fresh install chooses pinokio-<id> on enable and a fresh instance reads it back', async (t) => {
221
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-name-'))
222
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
223
+ const kernel = fakeKernel(tmp)
224
+ const anywhere = new Anywhere(kernel)
225
+ await anywhere.snapshot()
226
+ assert.equal(await anywhere.hostname(), null)
227
+ assert.equal(await anywhere.configured(), false, 'reading the config must not write it: the first /anywhere visit auto-enables on that')
228
+ assert.equal(fs.existsSync(anywhere.dir()), false)
229
+ const prefs = startable(anywhere)
230
+ await anywhere.enable()
231
+ const name = await anywhere.hostname()
232
+ assert.match(name, HOSTNAME)
233
+ assert.deepEqual(prefs, [name])
234
+ assert.deepEqual(JSON.parse(fs.readFileSync(anywhere.configPath(), 'utf8')), { enabled: true, hostname: name })
235
+ assert.equal(await anywhere.configured(), true)
236
+ assert.equal(await anywhere.start(), true)
237
+ assert.deepEqual(prefs, [name, name], 'later starts reuse the saved name')
238
+ assert.equal(await new Anywhere(kernel).hostname(), name)
239
+ })
240
+
241
+ test('start keeps any saved name, pinokio included, and chooses one only when none is saved', async (t) => {
242
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-name-'))
243
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
244
+ for (const saved of ['pinokio', 'keep-name', null]) {
245
+ const anywhere = new Anywhere(fakeKernel(path.join(tmp, String(saved))))
246
+ await anywhere.saveConfig(saved ? { enabled: true, hostname: saved } : { enabled: true })
247
+ const prefs = startable(anywhere)
248
+ assert.equal(await anywhere.start(), true)
249
+ const name = JSON.parse(fs.readFileSync(anywhere.configPath(), 'utf8')).hostname
250
+ if (saved) assert.equal(name, saved)
251
+ else assert.match(name, HOSTNAME)
252
+ assert.deepEqual(prefs, [name])
253
+ assert.equal(await anywhere.hostname(), name)
254
+ }
255
+ })
256
+
257
+ test('overlapping enable and start calls settle on one name', async (t) => {
258
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-name-'))
259
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
260
+ const anywhere = new Anywhere(fakeKernel(tmp))
261
+ await anywhere.saveConfig({ enabled: true })
262
+ const prefs = startable(anywhere)
263
+ const names = await Promise.all([anywhere.ensureHostname(), anywhere.enable().then(() => anywhere.hostname()), anywhere.start().then(() => anywhere.hostname()), anywhere.ensureHostname()])
264
+ assert.match(names[0], HOSTNAME)
265
+ assert.deepEqual(names, names.map(() => names[0]))
266
+ assert.deepEqual(prefs, prefs.map(() => names[0]))
267
+ assert.equal(JSON.parse(fs.readFileSync(anywhere.configPath(), 'utf8')).hostname, names[0])
268
+ })
269
+
270
+ test('a slower startup name write cannot resurrect On after Remote is switched off', async (t) => {
271
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-name-'))
272
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
273
+ const anywhere = new Anywhere(fakeKernel(tmp))
274
+ await anywhere.saveConfig({ enabled: true })
275
+ const prefs = startable(anywhere)
276
+ anywhere.stop = async () => {}
277
+ const original = fs.promises.writeFile
278
+ let release
279
+ const slow = new Promise((resolve) => { release = resolve })
280
+ t.mock.method(fs.promises, 'writeFile', async function (...args) {
281
+ if (String(args[0]).startsWith(anywhere.configPath()) && JSON.parse(args[1]).enabled) await slow
282
+ return original.apply(this, args)
283
+ })
284
+ const started = anywhere.start()
285
+ await new Promise(setImmediate)
286
+ const disabled = anywhere.disable()
287
+ await new Promise(setImmediate)
288
+ release()
289
+ await Promise.all([started, disabled])
290
+ const config = JSON.parse(fs.readFileSync(anywhere.configPath(), 'utf8'))
291
+ assert.equal(config.enabled, false, 'the slower startup write must not resurrect On')
292
+ assert.match(config.hostname, HOSTNAME)
293
+ assert.equal(await anywhere.enabled(), false)
294
+ })
295
+
296
+ test('a slow first config read cannot overwrite a config saved meanwhile', async (t) => {
297
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-name-'))
298
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
299
+ const anywhere = new Anywhere(fakeKernel(tmp))
300
+ const original = fs.promises.readFile
301
+ let release
302
+ const slow = new Promise((resolve) => { release = resolve })
303
+ const mock = t.mock.method(fs.promises, 'readFile', async function (...args) {
304
+ try { return await original.apply(this, args) }
305
+ finally { if (String(args[0]) === anywhere.configPath()) await slow }
306
+ })
307
+ const stale = anywhere.loadConfig() // a status poll before the file exists
308
+ mock.mock.restore()
309
+ startable(anywhere)
310
+ await anywhere.enable() // the first visit names the install
311
+ const name = await anywhere.hostname()
312
+ assert.match(name, HOSTNAME)
313
+ release()
314
+ assert.equal((await stale).hostname, name, 'the stale read yields the saved config')
315
+ assert.equal(await anywhere.hostname(), name)
316
+ assert.equal(await anywhere.configured(), true, 'the stale read must not forget the file exists')
317
+ assert.equal(await anywhere.ensureHostname(), name, 'the next start reuses the name')
318
+ assert.equal(JSON.parse(fs.readFileSync(anywhere.configPath(), 'utf8')).hostname, name)
319
+ })
320
+
321
+ test('a failed hostname save prevents start and sends Tailscale nothing', async (t) => {
322
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-name-'))
323
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
324
+ // a fresh install names itself on enable; a config without a name on start
325
+ for (const saved of [false, true]) {
326
+ const anywhere = new Anywhere(fakeKernel(path.join(tmp, String(saved))))
327
+ if (saved) await anywhere.saveConfig({ enabled: true })
328
+ const before = saved ? fs.readFileSync(anywhere.configPath(), 'utf8') : null
329
+ const prefs = startable(anywhere)
330
+ const original = fs.promises.writeFile
331
+ const mock = t.mock.method(fs.promises, 'writeFile', async function (...args) {
332
+ if (String(args[0]).startsWith(anywhere.configPath())) throw Object.assign(new Error('disk full'), { code: 'ENOSPC' })
333
+ return original.apply(this, args)
334
+ })
335
+ await assert.rejects(saved ? anywhere.start() : anywhere.enable(), { code: 'ENOSPC' })
336
+ mock.mock.restore()
337
+ assert.deepEqual(prefs, [])
338
+ if (saved) assert.equal(anywhere.error, 'disk full')
339
+ assert.equal(anywhere.child, null)
340
+ if (saved) assert.equal(fs.readFileSync(anywhere.configPath(), 'utf8'), before)
341
+ else assert.equal(fs.existsSync(anywhere.configPath()), false)
342
+ assert.equal(await anywhere.hostname(), null)
343
+ }
344
+ })
345
+
210
346
  test('anywhere snapshot walks setup -> off -> login -> https -> ready', async () => {
211
347
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-'))
212
348
  try {
@@ -217,7 +353,7 @@ test('anywhere snapshot walks setup -> off -> login -> https -> ready', async ()
217
353
  kernel.bin.mod.tailscaled.installed = async () => true
218
354
  assert.equal((await anywhere.snapshot()).phase, 'off')
219
355
 
220
- await anywhere.saveConfig({ enabled: true })
356
+ await anywhere.saveConfig({ enabled: true, hostname: 'pinokio-test' })
221
357
  assert.equal(await anywhere.configured(), true)
222
358
  assert.equal(JSON.parse(fs.readFileSync(path.join(tmp, 'anywhere', 'config.json'), 'utf8')).enabled, true)
223
359
 
@@ -730,7 +866,7 @@ test('Stop drains pending ownership checks without starting login or approval af
730
866
  t.after(() => fs.rmSync(tmp, { recursive: true, force: true }))
731
867
  for (const operation of ['login', 'approval']) {
732
868
  const anywhere = new Anywhere(fakeKernel(path.join(tmp, operation)))
733
- await anywhere.saveConfig({ enabled: true })
869
+ await anywhere.saveConfig({ enabled: true, hostname: 'pinokio-test' })
734
870
  let release, reads = 0, controls = 0, enteredStop
735
871
  const stopping = new Promise(resolve => { enteredStop = resolve })
736
872
  anywhere.readPid = () => ++reads === 1 ? new Promise(resolve => { release = resolve }) : null
@@ -848,7 +984,7 @@ test('logout and rejected links are handled by one CLI flow, with a fresh retry'
848
984
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-anywhere-'))
849
985
  try {
850
986
  const anywhere = new Anywhere(fakeKernel(tmp))
851
- await anywhere.saveConfig({ enabled: true })
987
+ await anywhere.saveConfig({ enabled: true, hostname: 'pinokio-test' })
852
988
  anywhere.readPid = () => 123
853
989
  const calls = []
854
990
  anywhere.api = {
@@ -884,7 +1020,7 @@ test('control failures preserve live-daemon records and logs on every platform',
884
1020
  const kernel = fakeKernel(tmp)
885
1021
  kernel.platform = platform
886
1022
  const anywhere = new Anywhere(kernel)
887
- await anywhere.saveConfig({ enabled: true })
1023
+ await anywhere.saveConfig({ enabled: true, hostname: 'pinokio-test' })
888
1024
  fs.mkdirSync(anywhere.stateDir(), { recursive: true })
889
1025
  const files = [anywhere.pidPath(), anywhere.logPath(), anywhere.portMapPath(), anywhere.stateDir('tailscaled.state')]
890
1026
  for (const file of files) fs.writeFileSync(file, 'preserve me')
@@ -1170,7 +1306,7 @@ test('a completed login allows a later stopped backend to resume', async () => {
1170
1306
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-resume-'))
1171
1307
  try {
1172
1308
  const anywhere = new Anywhere(fakeKernel(tmp))
1173
- await anywhere.saveConfig({ enabled: true })
1309
+ await anywhere.saveConfig({ enabled: true, hostname: 'pinokio-test' })
1174
1310
  anywhere.readPid = () => 123
1175
1311
  let status = runningStatus(), ups = 0
1176
1312
  anywhere.api = {
@@ -1190,7 +1326,7 @@ test('a completed login allows a later stopped backend to resume', async () => {
1190
1326
 
1191
1327
  test('logout while Off does not start another login', async () => {
1192
1328
  const anywhere = new Anywhere(fakeKernel(os.tmpdir()))
1193
- anywhere.config = { enabled: false }
1329
+ anywhere.config = { enabled: false, hostname: 'pinokio-test' }
1194
1330
  anywhere.readPid = () => 123
1195
1331
  let logouts = 0, logins = 0
1196
1332
  anywhere.api = { cancel() {}, logout: async () => { logouts++ }, up: async () => { logins++ } }
@@ -1205,7 +1341,7 @@ test('readiness requires a running backend and confirmed routes after sync', asy
1205
1341
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pk-ready-'))
1206
1342
  try {
1207
1343
  const anywhere = new Anywhere(fakeKernel(tmp))
1208
- await anywhere.saveConfig({ enabled: true })
1344
+ await anywhere.saveConfig({ enabled: true, hostname: 'pinokio-test' })
1209
1345
  anywhere.readPid = () => 123
1210
1346
  let reads = 0
1211
1347
  anywhere.api = { status: async () => {