| 59 | * proves nothing, and the client treats it as no daemon. |
| 60 | */ |
| 61 | export function daemonKey(file: string = daemonKeyPath()): Buffer | null { |
| 62 | const key = readDaemonKey(file); |
| 63 | if (key) return key; |
| 64 | let replace = false; |
| 65 | try { |
| 66 | const stat = fs.lstatSync(file); |
| 67 | if (!stat.isFile()) return null; |
| 68 | if (process.platform !== 'win32' && stat.uid !== process.getuid?.()) return null; |
| 69 | // This user's, but others can read it, or it is too short to be a key. |
| 70 | replace = true; |
| 71 | } catch (err) { |
| 72 | if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return null; |
| 73 | } |
| 74 | const { randomBytes } = crypto(); |
| 75 | const dir = path.dirname(file); |
| 76 | const tmp = path.join(dir, `.daemon.key.${process.pid}.${randomBytes(6).toString('hex')}`); |
| 77 | try { |
| 78 | fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); |
| 79 | fs.writeFileSync(tmp, randomBytes(KEY_BYTES), { mode: 0o600, flag: 'wx' }); |
| 80 | if (replace) { |
| 81 | fs.renameSync(tmp, file); |
| 82 | } else { |
| 83 | // Publish without overwriting: of two daemons making it at once, the |
| 84 | // first one's key stands, and the other reads it below. |
| 85 | try { |
| 86 | fs.linkSync(tmp, file); |
| 87 | } catch (err) { |
| 88 | if ((err as NodeJS.ErrnoException).code !== 'EEXIST') fs.renameSync(tmp, file); |
| 89 | } |
| 90 | } |
| 91 | } catch { |
| 92 | /* read below: whatever is there now decides */ |
| 93 | } finally { |
| 94 | try { fs.unlinkSync(tmp); } catch { /* renamed away, or never written */ } |
| 95 | } |
| 96 | return readDaemonKey(file); |
| 97 | } |
| 98 | |
| 99 | /** A fresh random challenge for one connection. */ |
| 100 | export function newDaemonChallenge(): string { |