@shieldfive/cli 0.2.0 → 0.3.0
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/CHANGELOG.md +117 -4
- package/README.md +130 -12
- package/SECURITY.md +9 -5
- package/package.json +1 -1
- package/src/agent/client.mjs +102 -0
- package/src/agent/ledger.mjs +254 -0
- package/src/agent/main.mjs +72 -0
- package/src/agent/paths.mjs +132 -0
- package/src/agent/protocol.mjs +125 -0
- package/src/agent/server.mjs +525 -0
- package/src/auth.mjs +79 -1
- package/src/cli.mjs +365 -36
- package/src/prompt.mjs +79 -0
- package/src/upload.mjs +207 -73
- package/src/uploadCrypto.mjs +62 -5
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// ShieldFive CLI — the upload ledger.
|
|
2
|
+
//
|
|
3
|
+
// One JSON line per upload the agent performed:
|
|
4
|
+
//
|
|
5
|
+
// {"v":1,"path":"/abs/path","size":48211,"mtimeMs":…,"mac":"<hex>",
|
|
6
|
+
// "fileId":"…","uploadedAt":"…","device":"<uuid>","tag":"<hex>"}
|
|
7
|
+
//
|
|
8
|
+
// `mac` is HMAC-SHA256 over exactly the plaintext bytes that were encrypted and
|
|
9
|
+
// uploaded, keyed by a key derived from the vault root key. A plain SHA-256
|
|
10
|
+
// would let anyone who reads this file confirm whether you hold a specific
|
|
11
|
+
// known document; keyed, the entries are unlinkable without the root key.
|
|
12
|
+
//
|
|
13
|
+
// `tag` is HMAC-SHA256 over the record's other fields under the same key. The
|
|
14
|
+
// ledger is an ordinary file the user's processes can write, so without it a
|
|
15
|
+
// forged line naming a missing file's MAC and some real fileId would make that
|
|
16
|
+
// file report as backed up. Records whose tag does not verify are dropped.
|
|
17
|
+
//
|
|
18
|
+
// Nothing here decides that a file is backed up by its name, path or size. A
|
|
19
|
+
// match on the MAC says those exact bytes were uploaded; whether they are still
|
|
20
|
+
// safely stored is a question for the server, asked at the moment it matters
|
|
21
|
+
// (see classify()).
|
|
22
|
+
|
|
23
|
+
import { createHmac, hkdfSync, timingSafeEqual } from 'node:crypto'
|
|
24
|
+
import { createReadStream } from 'node:fs'
|
|
25
|
+
import { mkdir, open, readFile, stat } from 'node:fs/promises'
|
|
26
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
27
|
+
|
|
28
|
+
export const LEDGER_VERSION = 1
|
|
29
|
+
const LEDGER_INFO = 'shieldfive/cli/ledger/v1'
|
|
30
|
+
const TAGGED_FIELDS = ['v', 'path', 'size', 'mtimeMs', 'mac', 'fileId', 'uploadedAt', 'device']
|
|
31
|
+
export const VERIFY_BATCH = 100
|
|
32
|
+
|
|
33
|
+
/** Derive the ledger MAC key from the 32-byte vault root key. */
|
|
34
|
+
export function deriveLedgerKey(rootKey) {
|
|
35
|
+
if (!(rootKey instanceof Uint8Array) || rootKey.length !== 32) {
|
|
36
|
+
throw new Error('deriveLedgerKey needs the 32-byte root key')
|
|
37
|
+
}
|
|
38
|
+
return Buffer.from(hkdfSync('sha256', rootKey, Buffer.alloc(0), LEDGER_INFO, 32))
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** HMAC-SHA256 of a file's bytes, streamed. Returns lowercase hex. */
|
|
42
|
+
export function macFile(path, ledgerKey) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const hmac = createHmac('sha256', ledgerKey)
|
|
45
|
+
const stream = createReadStream(path)
|
|
46
|
+
stream.on('error', reject)
|
|
47
|
+
stream.on('data', (chunk) => hmac.update(chunk))
|
|
48
|
+
stream.on('end', () => resolve(hmac.digest('hex')))
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function tagFor(ledgerKey, record) {
|
|
53
|
+
const fields = TAGGED_FIELDS.map((f) => record[f] ?? null)
|
|
54
|
+
return createHmac('sha256', ledgerKey).update(JSON.stringify(fields)).digest('hex')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function ledgerPath(dir, accountId) {
|
|
58
|
+
// Supabase user ids are UUIDs. Validating the shape keeps an account id from
|
|
59
|
+
// ever being read as a path.
|
|
60
|
+
if (typeof accountId !== 'string' || !/^[0-9a-f-]{36}$/i.test(accountId)) {
|
|
61
|
+
throw new Error(`Refusing ledger for malformed account id ${JSON.stringify(accountId)}`)
|
|
62
|
+
}
|
|
63
|
+
return join(dir, `${accountId.toLowerCase()}.jsonl`)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Tag, append and fsync one record. Creates the file 0600 inside a 0700 dir. */
|
|
67
|
+
export async function appendEntry(file, entry, { ledgerKey } = {}) {
|
|
68
|
+
if (!ledgerKey) throw new Error('appendEntry needs the ledger key to tag the record')
|
|
69
|
+
|
|
70
|
+
// Build and tag the record before the first await. The agent overwrites the
|
|
71
|
+
// key on logout, and a tag computed after that would be a tag under zeros.
|
|
72
|
+
const record = { v: LEDGER_VERSION, ...entry }
|
|
73
|
+
record.tag = tagFor(ledgerKey, record)
|
|
74
|
+
const line = JSON.stringify(record) + '\n'
|
|
75
|
+
|
|
76
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 })
|
|
77
|
+
const handle = await open(file, 'a+', 0o600)
|
|
78
|
+
try {
|
|
79
|
+
// If a previous write was torn and left no trailing newline, start on a new
|
|
80
|
+
// line. Otherwise this record would be glued to the broken one and both
|
|
81
|
+
// would be discarded as malformed.
|
|
82
|
+
const { size } = await handle.stat()
|
|
83
|
+
let prefix = ''
|
|
84
|
+
if (size > 0) {
|
|
85
|
+
const { buffer } = await handle.read(Buffer.alloc(1), 0, 1, size - 1)
|
|
86
|
+
if (buffer[0] !== 0x0a) prefix = '\n'
|
|
87
|
+
}
|
|
88
|
+
await handle.write(prefix + line)
|
|
89
|
+
await handle.sync()
|
|
90
|
+
} finally {
|
|
91
|
+
await handle.close()
|
|
92
|
+
}
|
|
93
|
+
return record
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Every well-formed, correctly tagged record, oldest first.
|
|
98
|
+
*
|
|
99
|
+
* A malformed line or a record whose tag does not verify is counted and
|
|
100
|
+
* skipped rather than failing the read, so one torn write or one forged line
|
|
101
|
+
* does not hide every other upload.
|
|
102
|
+
*/
|
|
103
|
+
export async function readEntries(file, { ledgerKey } = {}) {
|
|
104
|
+
if (!ledgerKey) throw new Error('readEntries needs the ledger key to check record tags')
|
|
105
|
+
|
|
106
|
+
let raw
|
|
107
|
+
try {
|
|
108
|
+
raw = await readFile(file, 'utf8')
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (err.code === 'ENOENT') return { entries: [], malformed: 0, unauthenticated: 0 }
|
|
111
|
+
throw err
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const entries = []
|
|
115
|
+
let malformed = 0
|
|
116
|
+
let unauthenticated = 0
|
|
117
|
+
for (const line of raw.split('\n')) {
|
|
118
|
+
if (!line.trim()) continue
|
|
119
|
+
let rec
|
|
120
|
+
try {
|
|
121
|
+
rec = JSON.parse(line)
|
|
122
|
+
} catch {
|
|
123
|
+
malformed++
|
|
124
|
+
continue
|
|
125
|
+
}
|
|
126
|
+
const wellFormed =
|
|
127
|
+
rec?.v === LEDGER_VERSION &&
|
|
128
|
+
typeof rec.path === 'string' &&
|
|
129
|
+
typeof rec.mac === 'string' &&
|
|
130
|
+
/^[0-9a-f]{64}$/.test(rec.mac) &&
|
|
131
|
+
typeof rec.fileId === 'string' &&
|
|
132
|
+
rec.fileId &&
|
|
133
|
+
typeof rec.tag === 'string' &&
|
|
134
|
+
/^[0-9a-f]{64}$/.test(rec.tag)
|
|
135
|
+
if (!wellFormed) {
|
|
136
|
+
malformed++
|
|
137
|
+
continue
|
|
138
|
+
}
|
|
139
|
+
const expected = Buffer.from(tagFor(ledgerKey, rec), 'hex')
|
|
140
|
+
if (!timingSafeEqual(expected, Buffer.from(rec.tag, 'hex'))) {
|
|
141
|
+
unauthenticated++
|
|
142
|
+
continue
|
|
143
|
+
}
|
|
144
|
+
entries.push(rec)
|
|
145
|
+
}
|
|
146
|
+
return { entries, malformed, unauthenticated }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Where each local path stands.
|
|
151
|
+
*
|
|
152
|
+
* verified the bytes on disk now are bytes that were uploaded,
|
|
153
|
+
* and the server confirms that upload is stored, ready,
|
|
154
|
+
* outside the Bin and intact
|
|
155
|
+
* missing the bytes were uploaded, but the server cannot confirm
|
|
156
|
+
* it is still safely stored
|
|
157
|
+
* changed_since_upload this path was uploaded, but the file has changed since
|
|
158
|
+
* not_in_ledger no record of these bytes being uploaded from here
|
|
159
|
+
* unreadable the local file could not be read
|
|
160
|
+
*
|
|
161
|
+
* `not_in_ledger` is not `missing`. It means this agent never uploaded these
|
|
162
|
+
* bytes; the file may well be in the vault from another device.
|
|
163
|
+
*
|
|
164
|
+
* When `device` is given, only records made on that device count.
|
|
165
|
+
*
|
|
166
|
+
* `verifyFileIds(ids)` must resolve to the ids the server reports verified. It
|
|
167
|
+
* is called in batches of at most VERIFY_BATCH, and an id in an answer only
|
|
168
|
+
* counts if that batch asked about it.
|
|
169
|
+
*/
|
|
170
|
+
export async function classify(paths, { entries, ledgerKey, verifyFileIds, device }) {
|
|
171
|
+
const usable = device ? entries.filter((e) => e.device === device) : entries
|
|
172
|
+
|
|
173
|
+
const byMac = new Map()
|
|
174
|
+
const byPath = new Map()
|
|
175
|
+
for (const e of usable) {
|
|
176
|
+
const macList = byMac.get(e.mac) ?? []
|
|
177
|
+
macList.push(e)
|
|
178
|
+
byMac.set(e.mac, macList)
|
|
179
|
+
byPath.set(e.path, e) // later records win: entries are oldest first
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const pending = []
|
|
183
|
+
const results = []
|
|
184
|
+
|
|
185
|
+
for (const path of paths) {
|
|
186
|
+
if (typeof path !== 'string' || !isAbsolute(path)) {
|
|
187
|
+
results.push({ path, state: 'unreadable', reason: 'not an absolute path' })
|
|
188
|
+
continue
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let st
|
|
192
|
+
try {
|
|
193
|
+
st = await stat(path)
|
|
194
|
+
} catch (err) {
|
|
195
|
+
results.push({ path, state: 'unreadable', reason: err.code ?? 'stat failed' })
|
|
196
|
+
continue
|
|
197
|
+
}
|
|
198
|
+
if (!st.isFile()) {
|
|
199
|
+
results.push({ path, state: 'unreadable', reason: 'not a regular file' })
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
let mac
|
|
204
|
+
try {
|
|
205
|
+
mac = await macFile(path, ledgerKey)
|
|
206
|
+
} catch (err) {
|
|
207
|
+
results.push({ path, state: 'unreadable', reason: err.code ?? 'read failed' })
|
|
208
|
+
continue
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const sameBytes = byMac.get(mac)
|
|
212
|
+
if (sameBytes?.length) {
|
|
213
|
+
// Prefer the record for this exact path; otherwise any upload of the same
|
|
214
|
+
// bytes counts, because identity here is the content, not the location.
|
|
215
|
+
const own = sameBytes.filter((e) => e.path === path)
|
|
216
|
+
const candidates = (own.length ? own : sameBytes).map((e) => e.fileId)
|
|
217
|
+
const result = { path, state: null, size: st.size, fileIds: [...new Set(candidates)] }
|
|
218
|
+
if (!own.length) result.matchedPath = sameBytes[sameBytes.length - 1].path
|
|
219
|
+
results.push(result)
|
|
220
|
+
pending.push(result)
|
|
221
|
+
continue
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (byPath.has(path)) {
|
|
225
|
+
results.push({ path, state: 'changed_since_upload', size: st.size })
|
|
226
|
+
continue
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
results.push({ path, state: 'not_in_ledger', size: st.size })
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const ids = [...new Set(pending.flatMap((r) => r.fileIds))]
|
|
233
|
+
const verified = new Set()
|
|
234
|
+
for (let i = 0; i < ids.length; i += VERIFY_BATCH) {
|
|
235
|
+
const batch = ids.slice(i, i + VERIFY_BATCH)
|
|
236
|
+
const asked = new Set(batch)
|
|
237
|
+
const answer = await verifyFileIds(batch)
|
|
238
|
+
for (const id of answer ?? []) {
|
|
239
|
+
// An id the server volunteered without being asked in this batch is not
|
|
240
|
+
// an answer to this question. On a check that gates deletion, that must
|
|
241
|
+
// fail closed.
|
|
242
|
+
if (asked.has(id)) verified.add(id)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
for (const r of pending) {
|
|
247
|
+
const ok = r.fileIds.find((id) => verified.has(id))
|
|
248
|
+
r.state = ok ? 'verified' : 'missing'
|
|
249
|
+
if (ok) r.fileId = ok
|
|
250
|
+
delete r.fileIds
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return results
|
|
254
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// ShieldFive CLI — agent entry point.
|
|
2
|
+
//
|
|
3
|
+
// `sf login` starts this as a detached child and passes it one JSON handoff on
|
|
4
|
+
// stdin: the session, the root key and the backend config. Stdin is used
|
|
5
|
+
// because it is the one channel between the two processes that does not appear
|
|
6
|
+
// in `ps` output or in /proc/<pid>/environ. This process never sees the
|
|
7
|
+
// password, and it never reads SF_PASSWORD.
|
|
8
|
+
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
|
|
11
|
+
import { uploadFile } from '../upload.mjs'
|
|
12
|
+
import { deviceId, socketPath } from './paths.mjs'
|
|
13
|
+
import { createAgent } from './server.mjs'
|
|
14
|
+
|
|
15
|
+
const MAX_HANDOFF_BYTES = 64_000
|
|
16
|
+
|
|
17
|
+
export async function readHandoff(stream) {
|
|
18
|
+
let raw = ''
|
|
19
|
+
for await (const chunk of stream) {
|
|
20
|
+
raw += chunk
|
|
21
|
+
if (raw.length > MAX_HANDOFF_BYTES) throw new Error('Agent handoff is too large.')
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let h
|
|
25
|
+
try {
|
|
26
|
+
h = JSON.parse(raw)
|
|
27
|
+
} catch {
|
|
28
|
+
throw new Error('Agent handoff is not valid JSON.')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const rootKey = new Uint8Array(Buffer.from(String(h?.rootKey ?? ''), 'base64'))
|
|
32
|
+
if (rootKey.length !== 32) throw new Error('Agent handoff does not carry a 32-byte root key.')
|
|
33
|
+
|
|
34
|
+
for (const field of ['apiBaseUrl', 'supabaseUrl', 'anonKey']) {
|
|
35
|
+
if (typeof h?.config?.[field] !== 'string' || !h.config[field]) {
|
|
36
|
+
throw new Error(`Agent handoff is missing config.${field}.`)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
session: h.session,
|
|
42
|
+
rootKey,
|
|
43
|
+
config: h.config,
|
|
44
|
+
idleMs: Number.isFinite(h.idleMs) && h.idleMs > 0 ? h.idleMs : undefined,
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function runAgent({ stdin = process.stdin, stdout = process.stdout, env = process.env } = {}) {
|
|
49
|
+
stdin.setEncoding('utf8')
|
|
50
|
+
const handoff = await readHandoff(stdin)
|
|
51
|
+
const home = homedir()
|
|
52
|
+
const socket = socketPath({ env })
|
|
53
|
+
|
|
54
|
+
const agent = createAgent({
|
|
55
|
+
...handoff,
|
|
56
|
+
socket,
|
|
57
|
+
home,
|
|
58
|
+
device: await deviceId(home),
|
|
59
|
+
uploadFile,
|
|
60
|
+
// Leave a moment for the reply to a lock or logout request to flush. The
|
|
61
|
+
// timer is unref'd, so if nothing else is pending the process exits sooner.
|
|
62
|
+
onStop: () => setTimeout(() => process.exit(0), 250).unref(),
|
|
63
|
+
})
|
|
64
|
+
handoff.rootKey.fill(0)
|
|
65
|
+
|
|
66
|
+
await agent.start()
|
|
67
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
|
|
68
|
+
process.on(signal, () => agent.stop(`signal ${signal}`))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
stdout.write(JSON.stringify({ ready: true, pid: process.pid, socket }) + '\n')
|
|
72
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// ShieldFive CLI — where the agent keeps its socket, ledger and device id.
|
|
2
|
+
//
|
|
3
|
+
// The socket directory is the agent's only access control. Node exposes no
|
|
4
|
+
// SO_PEERCRED, so the agent cannot see which process connected; what stops
|
|
5
|
+
// another local user is that they cannot enter the directory. That makes the
|
|
6
|
+
// checks here load-bearing, and it is why the agent refuses to start in a
|
|
7
|
+
// directory it does not own or that anyone else can reach, rather than
|
|
8
|
+
// quietly tightening the mode and carrying on.
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
12
|
+
import { homedir } from 'node:os'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
|
|
15
|
+
export const SOCKET_NAME = 'agent.sock'
|
|
16
|
+
|
|
17
|
+
export class UnsafeDirectoryError extends Error {
|
|
18
|
+
constructor(message) {
|
|
19
|
+
super(message)
|
|
20
|
+
this.name = 'UnsafeDirectoryError'
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class UnsupportedPlatformError extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message)
|
|
27
|
+
this.name = 'UnsupportedPlatformError'
|
|
28
|
+
this.code = 'unsupported_platform'
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The directory holding the agent socket: always ~/.shieldfive/run.
|
|
34
|
+
*
|
|
35
|
+
* An earlier version preferred $XDG_RUNTIME_DIR on Linux and $TMPDIR on macOS.
|
|
36
|
+
* Cron jobs and `env -i` shells set neither, so `sf sync` run from cron looked
|
|
37
|
+
* in a different directory from the one `sf login` used, reported that no agent
|
|
38
|
+
* was running, and fell back to asking for a password. Unattended sync is the
|
|
39
|
+
* reason the agent exists, so every process the user runs has to find it in the
|
|
40
|
+
* same place.
|
|
41
|
+
*/
|
|
42
|
+
export function agentDir({ platform = process.platform, home = homedir() } = {}) {
|
|
43
|
+
if (platform === 'win32') {
|
|
44
|
+
throw new UnsupportedPlatformError(
|
|
45
|
+
'sf agent does not run on Windows yet: named pipes have a different ' +
|
|
46
|
+
'permission model and it has not been designed. Use SF_EMAIL and ' +
|
|
47
|
+
'SF_PASSWORD with sf push / sf sync instead.',
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
return join(home, '.shieldfive', 'run')
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function socketPath(options) {
|
|
54
|
+
return join(agentDir(options), SOCKET_NAME)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function shieldfiveHome(home = homedir()) {
|
|
58
|
+
return join(home, '.shieldfive')
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function ledgerDir(home = homedir()) {
|
|
62
|
+
return join(shieldfiveHome(home), 'ledger')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Create `dir` if needed, then refuse unless it is a real directory owned by
|
|
67
|
+
* this user with no group or other permission bits.
|
|
68
|
+
*/
|
|
69
|
+
export async function ensurePrivateDir(dir, { uid = process.getuid?.() } = {}) {
|
|
70
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
71
|
+
return assertPrivateDir(dir, { uid })
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function assertPrivateDir(dir, { uid = process.getuid?.() } = {}) {
|
|
75
|
+
const st = await lstat(dir)
|
|
76
|
+
if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
77
|
+
throw new UnsafeDirectoryError(
|
|
78
|
+
`${dir} is not a real directory. The agent will not follow a link to ` +
|
|
79
|
+
'decide where its socket lives.',
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
if (uid !== undefined && st.uid !== uid) {
|
|
83
|
+
throw new UnsafeDirectoryError(
|
|
84
|
+
`${dir} is owned by uid ${st.uid}, not by you (uid ${uid}). Remove it ` +
|
|
85
|
+
'and run sf login again.',
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
if ((st.mode & 0o077) !== 0) {
|
|
89
|
+
throw new UnsafeDirectoryError(
|
|
90
|
+
`${dir} is accessible to other users (mode ` +
|
|
91
|
+
`${(st.mode & 0o777).toString(8)}). Run: chmod 700 '${dir}'`,
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
return dir
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A random identifier for this installation, created on first use.
|
|
99
|
+
*
|
|
100
|
+
* Not a secret. Every ledger record carries it, and `verify` only counts
|
|
101
|
+
* records made on this device, so a ledger copied from another computer does
|
|
102
|
+
* not vouch for files here.
|
|
103
|
+
*/
|
|
104
|
+
export async function deviceId(home = homedir()) {
|
|
105
|
+
const dir = shieldfiveHome(home)
|
|
106
|
+
await ensurePrivateDir(dir)
|
|
107
|
+
const file = join(dir, 'device.json')
|
|
108
|
+
|
|
109
|
+
const read = async () => {
|
|
110
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'))
|
|
111
|
+
if (typeof parsed?.id !== 'string' || !/^[0-9a-f-]{36}$/i.test(parsed.id)) {
|
|
112
|
+
throw new Error(`${file} does not hold a valid device id`)
|
|
113
|
+
}
|
|
114
|
+
return parsed.id
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
try {
|
|
118
|
+
return await read()
|
|
119
|
+
} catch (err) {
|
|
120
|
+
if (err.code !== 'ENOENT') throw err
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const id = randomUUID()
|
|
124
|
+
try {
|
|
125
|
+
await writeFile(file, JSON.stringify({ id }) + '\n', { mode: 0o600, flag: 'wx' })
|
|
126
|
+
return id
|
|
127
|
+
} catch (err) {
|
|
128
|
+
// Another sf process created it first; theirs wins.
|
|
129
|
+
if (err.code === 'EEXIST') return read()
|
|
130
|
+
throw err
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// ShieldFive CLI — the agent's wire protocol.
|
|
2
|
+
//
|
|
3
|
+
// Newline-delimited JSON over a Unix domain socket: one request line, one
|
|
4
|
+
// response line.
|
|
5
|
+
//
|
|
6
|
+
// The operation list is an allowlist and it is deliberately short. There is no
|
|
7
|
+
// operation that lists vault contents, downloads, decrypts, or returns key
|
|
8
|
+
// material, and adding one would change what a process that can reach the
|
|
9
|
+
// socket is able to do. A test pins the list so that change cannot happen by
|
|
10
|
+
// accident.
|
|
11
|
+
|
|
12
|
+
import { isAbsolute } from 'node:path'
|
|
13
|
+
|
|
14
|
+
export const OPS = Object.freeze(['status', 'upload', 'sync', 'verify', 'lock', 'logout'])
|
|
15
|
+
const OP_SET = new Set(OPS)
|
|
16
|
+
|
|
17
|
+
export const MAX_LINE_BYTES = 1_000_000
|
|
18
|
+
export const MAX_VERIFY_PATHS = 500
|
|
19
|
+
const MAX_PATH_LENGTH = 4096
|
|
20
|
+
|
|
21
|
+
export class ProtocolError extends Error {
|
|
22
|
+
constructor(code, message) {
|
|
23
|
+
super(message)
|
|
24
|
+
this.name = 'ProtocolError'
|
|
25
|
+
this.code = code
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function encode(message) {
|
|
30
|
+
return JSON.stringify(message) + '\n'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function ok(id, result) {
|
|
34
|
+
return { id, ok: true, result }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function fail(id, code, message) {
|
|
38
|
+
return { id, ok: false, error: { code, message } }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Split an incoming UTF-8 text stream into lines.
|
|
43
|
+
*
|
|
44
|
+
* The socket must be set to 'utf8' encoding first so a multi-byte character
|
|
45
|
+
* split across two chunks is reassembled before it gets here. A line longer
|
|
46
|
+
* than MAX_LINE_BYTES is an error rather than an unbounded buffer.
|
|
47
|
+
*/
|
|
48
|
+
export function lineSplitter(onLine, { maxBytes = MAX_LINE_BYTES } = {}) {
|
|
49
|
+
let buffer = ''
|
|
50
|
+
return (chunk) => {
|
|
51
|
+
buffer += chunk
|
|
52
|
+
let newline
|
|
53
|
+
while ((newline = buffer.indexOf('\n')) !== -1) {
|
|
54
|
+
const line = buffer.slice(0, newline)
|
|
55
|
+
buffer = buffer.slice(newline + 1)
|
|
56
|
+
if (line.trim()) onLine(line)
|
|
57
|
+
}
|
|
58
|
+
if (Buffer.byteLength(buffer) > maxBytes) {
|
|
59
|
+
buffer = ''
|
|
60
|
+
throw new ProtocolError('line_too_long', `A request line exceeded ${maxBytes} bytes.`)
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function absolutePath(value, name) {
|
|
66
|
+
if (typeof value !== 'string' || !value || value.length > MAX_PATH_LENGTH) {
|
|
67
|
+
throw new ProtocolError('bad_request', `${name} must be a path of at most ${MAX_PATH_LENGTH} characters.`)
|
|
68
|
+
}
|
|
69
|
+
if (!isAbsolute(value) || value.includes('\0')) {
|
|
70
|
+
throw new ProtocolError('bad_request', `${name} must be an absolute path.`)
|
|
71
|
+
}
|
|
72
|
+
return value
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Parse and validate one request line. Throws ProtocolError. */
|
|
76
|
+
export function parseRequest(line) {
|
|
77
|
+
let message
|
|
78
|
+
try {
|
|
79
|
+
message = JSON.parse(line)
|
|
80
|
+
} catch {
|
|
81
|
+
throw new ProtocolError('bad_json', 'Request is not valid JSON.')
|
|
82
|
+
}
|
|
83
|
+
if (!message || typeof message !== 'object' || Array.isArray(message)) {
|
|
84
|
+
throw new ProtocolError('bad_request', 'Request must be a JSON object.')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const { id, op } = message
|
|
88
|
+
if (!(typeof id === 'string' || Number.isInteger(id)) || String(id).length > 64) {
|
|
89
|
+
throw new ProtocolError('bad_request', 'Request id must be a string or integer.')
|
|
90
|
+
}
|
|
91
|
+
if (typeof op !== 'string' || !OP_SET.has(op)) {
|
|
92
|
+
throw new ProtocolError(
|
|
93
|
+
'unknown_op',
|
|
94
|
+
`Unknown operation ${JSON.stringify(op)}. The agent performs only: ${OPS.join(', ')}.`,
|
|
95
|
+
)
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const args = message.args ?? {}
|
|
99
|
+
if (typeof args !== 'object' || Array.isArray(args)) {
|
|
100
|
+
throw new ProtocolError('bad_request', 'args must be an object.')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
switch (op) {
|
|
104
|
+
case 'upload':
|
|
105
|
+
return { id, op, args: { path: absolutePath(args.path, 'path') } }
|
|
106
|
+
case 'sync':
|
|
107
|
+
return { id, op, args: { folder: absolutePath(args.folder, 'folder') } }
|
|
108
|
+
case 'verify': {
|
|
109
|
+
if (!Array.isArray(args.paths) || args.paths.length === 0) {
|
|
110
|
+
throw new ProtocolError('bad_request', 'paths must be a non-empty array.')
|
|
111
|
+
}
|
|
112
|
+
if (args.paths.length > MAX_VERIFY_PATHS) {
|
|
113
|
+
throw new ProtocolError('bad_request', `At most ${MAX_VERIFY_PATHS} paths per verify.`)
|
|
114
|
+
}
|
|
115
|
+
return { id, op, args: { paths: args.paths.map((p, i) => absolutePath(p, `paths[${i}]`)) } }
|
|
116
|
+
}
|
|
117
|
+
case 'logout':
|
|
118
|
+
// `everywhere` signs out every session on the account, not just this one.
|
|
119
|
+
// It is how a session the agent could not revoke (offline, or already
|
|
120
|
+
// replaced) gets ended from a later login.
|
|
121
|
+
return { id, op, args: { everywhere: args.everywhere === true } }
|
|
122
|
+
default:
|
|
123
|
+
return { id, op, args: {} }
|
|
124
|
+
}
|
|
125
|
+
}
|