@shieldfive/cli 0.2.1 → 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.
@@ -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
+ }