tryflop 0.0.1 → 0.1.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/README.md +66 -2
- package/bin/flop-mcp.mjs +22 -0
- package/bin/tryflop.mjs +36 -0
- package/e2e/sandbox-smoke.mjs +136 -0
- package/npm-shrinkwrap.json +2648 -0
- package/package.json +52 -5
- package/src/agent-settings.js +76 -0
- package/src/claim.js +516 -0
- package/src/cli.js +428 -0
- package/src/daily.js +363 -0
- package/src/files.js +104 -0
- package/src/flop-core.js +189 -0
- package/src/flop-node.js +346 -0
- package/src/format.js +180 -0
- package/src/gate.js +19 -0
- package/src/guard.js +231 -0
- package/src/home.js +96 -0
- package/src/install.js +110 -0
- package/src/keyfile.js +70 -0
- package/src/layout.js +55 -0
- package/src/miners.js +65 -0
- package/src/moments.js +50 -0
- package/src/outcome.js +128 -0
- package/src/outer.js +969 -0
- package/src/payer.js +834 -0
- package/src/questions.js +47 -0
- package/src/requests.js +178 -0
- package/src/roots.js +48 -0
- package/src/sandbox.js +223 -0
- package/src/scheduler.js +221 -0
- package/src/scoring.js +67 -0
- package/src/secrets.js +41 -0
- package/src/server.js +13 -0
- package/src/shared/config.js +366 -0
- package/src/shared/direct-core.js +226 -0
- package/src/shared/grants-core.js +69 -0
- package/src/shared/units.js +47 -0
- package/src/statusfile.js +70 -0
- package/src/tools.js +107 -0
- package/src/tryflop.js +622 -0
- package/src/wallet.js +123 -0
- package/bin/tryflop.js +0 -5
package/src/questions.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// What the daily run asks (SPEC.md "tryflop daily", SPEND): a short daily brief on a topic the human chose at setup.
|
|
2
|
+
// Real questions a person would read, varied from day to day, and never private: the topic is the only input, it is
|
|
3
|
+
// checked like any prompt (no secrets), and no file or other data of the human's ever goes into a question.
|
|
4
|
+
// Node built-ins only.
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_TOPIC = 'how AI models work';
|
|
7
|
+
const MAX_TOPIC = 80;
|
|
8
|
+
|
|
9
|
+
/** Each day's angles, in turn (the day of the year picks where to start). */
|
|
10
|
+
const ANGLES = Object.freeze([
|
|
11
|
+
(t) => `In plain words, explain one important idea in ${t}, with a short everyday example.`,
|
|
12
|
+
(t) => `What is a common misconception about ${t}, and what is actually true? Answer in a short paragraph.`,
|
|
13
|
+
(t) => `Give three practical tips for someone learning about ${t}, one sentence each.`,
|
|
14
|
+
(t) => `Define five key terms in ${t}, one line each.`,
|
|
15
|
+
(t) => `Write a three-question quiz about ${t}, with the answers at the end.`,
|
|
16
|
+
(t) => `Summarize how ${t} developed, in five short points.`,
|
|
17
|
+
(t) => `What are two open questions or debates in ${t}? Explain each in two sentences.`,
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
/** A second axis, so a whole ON day (up to 32 questions) never asks the same thing twice (review, 27 Nov). */
|
|
21
|
+
const FOCUSES = Object.freeze(['', ' Focus on its history.', ' Focus on how it is used today.', ' Focus on what beginners get wrong.', ' Focus on what experts still debate.']);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The topic as stored: one line of printable text, at most 80 characters; the default when nothing is left.
|
|
25
|
+
* @param {unknown} text @returns {string}
|
|
26
|
+
*/
|
|
27
|
+
export function cleanTopic(text) {
|
|
28
|
+
const topic = String(text ?? '').replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_TOPIC);
|
|
29
|
+
return topic || DEFAULT_TOPIC;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The most different questions one day can have. */
|
|
33
|
+
export const MAX_QUESTIONS = ANGLES.length * FOCUSES.length;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The questions for one day: `count` different questions on the topic (at most MAX_QUESTIONS), starting at the day's
|
|
37
|
+
* own angle; after every angle once, each comes back with another focus, so no two are the same text (the payer would
|
|
38
|
+
* answer a repeat from storage instead of buying it).
|
|
39
|
+
* @param {string} topic @param {number} dayNumber days since 1970 (local), so tomorrow starts one angle later
|
|
40
|
+
* @param {number} count @returns {string[]}
|
|
41
|
+
*/
|
|
42
|
+
export function dailyQuestions(topic, dayNumber, count) {
|
|
43
|
+
const t = cleanTopic(topic);
|
|
44
|
+
const n = Math.min(MAX_QUESTIONS, Math.max(0, Math.floor(count)));
|
|
45
|
+
const start = ((dayNumber % ANGLES.length) + ANGLES.length) % ANGLES.length;
|
|
46
|
+
return Array.from({ length: n }, (_, i) => `${ANGLES[(start + i) % ANGLES.length](t)}${FOCUSES[Math.floor(i / ANGLES.length) % FOCUSES.length]}`);
|
|
47
|
+
}
|
package/src/requests.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
// The request log: one line per change of each ask_flop call, appended to
|
|
2
|
+
// requests.jsonl, which every connector process on this computer shares; the last line of an id wins.
|
|
3
|
+
// The answer lives in its own 0600 file (answers/<id>.txt); the prompt is never stored, only its
|
|
4
|
+
// fingerprint (for "same question again?") and its length. Ids reaching get() come from the AI, so only
|
|
5
|
+
// the exact id shape is ever turned into a file name.
|
|
6
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
7
|
+
import { closeSync, mkdirSync, openSync, readFileSync, writeSync } from 'node:fs';
|
|
8
|
+
import { join } from 'node:path';
|
|
9
|
+
|
|
10
|
+
const ID = /^r_[0-9a-z]{1,12}_[0-9a-f]{8}$/;
|
|
11
|
+
|
|
12
|
+
/** @param {unknown} id @returns {id is string} */
|
|
13
|
+
export const validRequestId = (id) => typeof id === 'string' && ID.test(id);
|
|
14
|
+
|
|
15
|
+
/** @param {number} now @param {string} [randomHex] 8 hex characters */
|
|
16
|
+
export const newRequestId = (now, randomHex = randomBytes(4).toString('hex')) => `r_${now.toString(36)}_${randomHex}`;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* "The same question": same model, system text, answer length and prompt.
|
|
20
|
+
* @param {{ model: string, system?: string, maxTokens: number, prompt: string }} question
|
|
21
|
+
*/
|
|
22
|
+
export function fingerprint({ model, system, maxTokens, prompt }) {
|
|
23
|
+
return createHash('sha256').update(JSON.stringify([model, system ?? '', maxTokens, prompt])).digest('hex');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @typedef {'queued'|'running'|'answered'|'failed'|'refused'|'unknown'} RequestStatus
|
|
28
|
+
* @typedef {{ id: string, at: number, status: RequestStatus, fingerprint?: string, model?: string, promptChars?: number,
|
|
29
|
+
* miner?: string, finishedAt?: number, reason?: string, paidPlanck?: bigint, channel?: string, replayed?: boolean,
|
|
30
|
+
* answer?: string, pid?: number }} RequestView
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** Append one line in one write (O_APPEND keeps concurrent writers' lines whole). @param {string} file @param {object} line */
|
|
34
|
+
function appendLine(file, line) {
|
|
35
|
+
const fd = openSync(file, 'a', 0o600);
|
|
36
|
+
try {
|
|
37
|
+
writeSync(fd, `${JSON.stringify(line)}\n`);
|
|
38
|
+
} finally {
|
|
39
|
+
closeSync(fd);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class RequestLog {
|
|
44
|
+
/** @param {{ file: string, answersDir: string, now: () => number }} options */
|
|
45
|
+
constructor({ file, answersDir, now }) {
|
|
46
|
+
this.file = file;
|
|
47
|
+
this.answersDir = answersDir;
|
|
48
|
+
this.now = now;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {{ id: string, fingerprint: string, model: string, promptChars: number, miner?: string, pid?: number, status?: 'queued'|'running' }} record
|
|
53
|
+
* pid: the process asking (housekeeping marks a request whose process is gone as unknown)
|
|
54
|
+
*/
|
|
55
|
+
start({ id, fingerprint: print, model, promptChars, miner, pid, status = 'running' }) {
|
|
56
|
+
appendLine(this.file, { id, at: this.now(), status, fingerprint: print, model, promptChars, ...(miner ? { miner } : {}), ...(pid !== undefined ? { pid } : {}) });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A non-final change, e.g. queued → running. @param {string} id @param {{ status: 'queued'|'running' }} patch */
|
|
60
|
+
update(id, { status }) {
|
|
61
|
+
appendLine(this.file, { id, status });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* @param {string} id
|
|
66
|
+
* @param {{ status: Exclude<RequestStatus, 'running'|'queued'>, reason?: string, answer?: string, paidPlanck?: bigint, channel?: string, replayed?: boolean, miner?: string }} result
|
|
67
|
+
*/
|
|
68
|
+
finish(id, { status, reason, answer, paidPlanck, channel, replayed, miner }) {
|
|
69
|
+
if (answer !== undefined) {
|
|
70
|
+
mkdirSync(this.answersDir, { recursive: true, mode: 0o700 });
|
|
71
|
+
const fd = openSync(join(this.answersDir, `${id}.txt`), 'w', 0o600);
|
|
72
|
+
try {
|
|
73
|
+
writeSync(fd, answer);
|
|
74
|
+
} finally {
|
|
75
|
+
closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
appendLine(this.file, {
|
|
79
|
+
id, finishedAt: this.now(), status,
|
|
80
|
+
...(reason ? { reason: reason.slice(0, 500) } : {}),
|
|
81
|
+
...(paidPlanck !== undefined ? { paidPlanck: paidPlanck.toString() } : {}),
|
|
82
|
+
...(channel ? { channel } : {}),
|
|
83
|
+
...(replayed !== undefined ? { replayed } : {}),
|
|
84
|
+
...(miner ? { miner } : {}),
|
|
85
|
+
...(answer !== undefined ? { hasAnswer: true } : {}),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Every request, merged per id, in the order first seen. @returns {Map<string, RequestView & { hasAnswer?: boolean }>} */
|
|
90
|
+
all() {
|
|
91
|
+
/** @type {Map<string, any>} */
|
|
92
|
+
const byId = new Map();
|
|
93
|
+
let text = '';
|
|
94
|
+
try {
|
|
95
|
+
text = readFileSync(this.file, 'utf8');
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (/** @type {any} */ (error).code !== 'ENOENT') throw error;
|
|
98
|
+
}
|
|
99
|
+
for (const row of text.split('\n')) {
|
|
100
|
+
if (!row) continue;
|
|
101
|
+
let line;
|
|
102
|
+
try {
|
|
103
|
+
line = JSON.parse(row);
|
|
104
|
+
} catch {
|
|
105
|
+
continue; // a torn or damaged line: this log drives answers to the user, never money
|
|
106
|
+
}
|
|
107
|
+
if (!line || !validRequestId(line.id)) continue;
|
|
108
|
+
byId.set(line.id, { ...(byId.get(line.id) ?? {}), ...line });
|
|
109
|
+
}
|
|
110
|
+
for (const view of byId.values()) {
|
|
111
|
+
if (typeof view.paidPlanck === 'string') view.paidPlanck = BigInt(view.paidPlanck);
|
|
112
|
+
}
|
|
113
|
+
return byId;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @param {unknown} id @returns {RequestView | undefined} */
|
|
117
|
+
get(id) {
|
|
118
|
+
if (!validRequestId(id)) return undefined;
|
|
119
|
+
const view = this.all().get(id);
|
|
120
|
+
if (!view) return undefined;
|
|
121
|
+
const { hasAnswer, ...rest } = view;
|
|
122
|
+
if (hasAnswer) {
|
|
123
|
+
try {
|
|
124
|
+
rest.answer = readFileSync(join(this.answersDir, `${id}.txt`), 'utf8');
|
|
125
|
+
} catch {
|
|
126
|
+
// the answer file was removed; the status stays
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return rest;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The newest request asked with this fingerprint inside the window of its FINISH (or of its queueing, while
|
|
134
|
+
* it is still queued or running). Timing it from the queue instead let a request that waited behind a settle
|
|
135
|
+
* for over 15 minutes drop out of the "same question" guard, so an immediate repeat was paid for again
|
|
136
|
+
* (review of effcd81, 24 Nov); a request still in flight never ages out.
|
|
137
|
+
* @param {string} print @param {number} windowMs
|
|
138
|
+
*/
|
|
139
|
+
recent(print, windowMs) {
|
|
140
|
+
const since = this.now() - windowMs;
|
|
141
|
+
let best;
|
|
142
|
+
for (const view of this.all().values()) {
|
|
143
|
+
if (view.fingerprint !== print) continue;
|
|
144
|
+
const inFlight = view.status === 'queued' || view.status === 'running';
|
|
145
|
+
const when = inFlight ? Number.POSITIVE_INFINITY : (typeof view.finishedAt === 'number' ? view.finishedAt : view.at);
|
|
146
|
+
if (when <= since) continue;
|
|
147
|
+
if (!best || when >= best.when) best = { id: view.id, when };
|
|
148
|
+
}
|
|
149
|
+
return best ? this.get(best.id) : undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The newest request with this fingerprint that ended FAILED after it had already committed money, by its
|
|
154
|
+
* finish time inside the window. The retry cooldown asks this, for two reasons: a request can start long
|
|
155
|
+
* before it ends (a queue behind a settle), so a lookup by `at` misses the failure exactly when it matters;
|
|
156
|
+
* and selecting only the paid failures keeps a later-finishing record of another status from hiding the one
|
|
157
|
+
* that spent (security reviews of 24 Nov).
|
|
158
|
+
* @param {string} print @param {number} windowMs @returns {RequestView | undefined}
|
|
159
|
+
*/
|
|
160
|
+
recentPaidFailure(print, windowMs) {
|
|
161
|
+
const since = this.now() - windowMs;
|
|
162
|
+
let best;
|
|
163
|
+
for (const view of this.all().values()) {
|
|
164
|
+
if (view.fingerprint !== print || view.status !== 'failed' || typeof view.finishedAt !== 'number' || view.finishedAt <= since) continue;
|
|
165
|
+
if (!(typeof view.paidPlanck === 'bigint' && view.paidPlanck > 0n)) continue;
|
|
166
|
+
if (!best || view.finishedAt >= /** @type {number} */ (best.finishedAt)) best = view;
|
|
167
|
+
}
|
|
168
|
+
return best ? this.get(best.id) : undefined;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Requests still queued or running, or ended unknown. @returns {RequestView[]} */
|
|
172
|
+
unresolved() {
|
|
173
|
+
return [...this.all().values()].filter((v) => v.status === 'queued' || v.status === 'running' || v.status === 'unknown').map((v) => {
|
|
174
|
+
const { hasAnswer: _ignored, ...rest } = v;
|
|
175
|
+
return rest;
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
package/src/roots.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Where the connector keeps its data. Node built-ins only: src/sandbox.js and the tryflop outer commands load this
|
|
2
|
+
// before any sandbox exists, so nothing third-party may run here.
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
/** The connector's data root: FLOP_MCP_HOME, or ~/.flop-mcp. @param {NodeJS.ProcessEnv} [env] */
|
|
7
|
+
export const homeRoot = (env = process.env) => resolve(env.FLOP_MCP_HOME || join(homedir(), '.flop-mcp'));
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The SDK's payer-lock root: FLOP_MCP_PAYERS, or ~/.flop/payers (the SDK's defaultPayersRoot()). One lock
|
|
11
|
+
* per (genesis, payer) on this computer, shared with any other Flop tool paying from the same wallet.
|
|
12
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
13
|
+
*/
|
|
14
|
+
export const payersRoot = (env = process.env) => resolve(env.FLOP_MCP_PAYERS || join(homedir(), '.flop', 'payers'));
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The human's own Try Flop folder (status.md, the saved answers): FLOP_MCP_HUMAN_DIR, or ~/TryFlop. The daily run
|
|
18
|
+
* writes here, so the sandbox lets it.
|
|
19
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
20
|
+
*/
|
|
21
|
+
export const humanRoot = (env = process.env) => resolve(env.FLOP_MCP_HUMAN_DIR || join(homedir(), 'TryFlop'));
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Where `tryflop setup` keeps the copy of the code the scheduler and Claude Code start: FLOP_MCP_APP_ROOT, or
|
|
25
|
+
* ~/.tryflop/app. Never inside a folder the sandbox may write: sandboxed code that could rewrite the code started
|
|
26
|
+
* next time (outside the sandbox: the scheduler's outer process) would escape it.
|
|
27
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
28
|
+
*/
|
|
29
|
+
export const appRoot = (env = process.env) => resolve(env.FLOP_MCP_APP_ROOT || join(homedir(), '.tryflop', 'app'));
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Where the scheduler's own output and the Windows task file go: ~/.tryflop/logs (beside the code copy). Never a folder
|
|
33
|
+
* the sandbox may write: the scheduler runs OUTSIDE it and appends to this file, so sandboxed code that could swap the
|
|
34
|
+
* file for a link would make it write anywhere (security review, 27 Nov 2026).
|
|
35
|
+
* @param {NodeJS.ProcessEnv} [env]
|
|
36
|
+
*/
|
|
37
|
+
export const logsRoot = (env = process.env) => join(appRoot(env), '..', 'logs');
|
|
38
|
+
|
|
39
|
+
/** The launcher setup writes (~/.tryflop/bin/tryflop, or tryflop.cmd on Windows): this Node and the copied code. @param {NodeJS.ProcessEnv} [env] */
|
|
40
|
+
export const launcherDir = (env = process.env) => join(appRoot(env), '..', 'bin');
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The command a human or an agent types for tryflop after setup, as printed (the launcher; `~` for the home folder).
|
|
44
|
+
* @param {string} platform
|
|
45
|
+
*/
|
|
46
|
+
// Forward slashes on Windows too: Claude Code runs commands there in Git Bash, which reads `~\.tryflop\bin` as
|
|
47
|
+
// `~.tryflopbin`; PowerShell and cmd accept `/` as well (review of 4ac7d10).
|
|
48
|
+
export const launcherCommand = (platform) => (platform === 'win32' ? '~/.tryflop/bin/tryflop.cmd' : '~/.tryflop/bin/tryflop');
|
package/src/sandbox.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// The sandbox the connector runs in. The Flop SDK has npm signatures but no
|
|
2
|
+
// build-provenance attestation, so it never runs with the user's full rights: every entry point calls
|
|
3
|
+
// ensureSandboxed() first, which re-executes the same command inside macOS's own sandbox (Seatbelt,
|
|
4
|
+
// /usr/bin/sandbox-exec), enforced by the operating system:
|
|
5
|
+
// - every user's files, external drives and the temp folders are unreadable, except the connector's
|
|
6
|
+
// code (with its copies of the agent-app files, src/shared/), the folder npm installed its dependencies
|
|
7
|
+
// into, the node program itself and its data folders;
|
|
8
|
+
// - nothing may be written anywhere except its two data folders (and, for tryflop, the human's ~/TryFlop);
|
|
9
|
+
// - no other program may start; native add-ons are off (node --no-addons, and the OS refuses to map any
|
|
10
|
+
// code but node's and macOS's own, so a Node from Homebrew or MacPorts is refused up front); nothing may
|
|
11
|
+
// listen for connections; the macOS services a
|
|
12
|
+
// native program could use to act outside the sandbox (AppleEvents, app launching, keychain,
|
|
13
|
+
// clipboard), every local socket except DNS's, and this computer's own network services are refused;
|
|
14
|
+
// - only an allow-list of environment variables gets in (tokens in the user's shell stay outside).
|
|
15
|
+
// The network stays open (the connector must reach Flop). Node's own --permission layer is not used:
|
|
16
|
+
// it switches off fsync, which the SDK's FileSpendJournal needs to record a payment safely before it is
|
|
17
|
+
// sent (measured 24 Nov 2026, Node 22.23.5). Node built-ins only here: this runs before the sandbox exists.
|
|
18
|
+
// Windows and Linux have no such sandbox here: `tryflop` runs there natively (its setup says so once);
|
|
19
|
+
// `flop-mcp` keeps refusing them.
|
|
20
|
+
import { lstatSync, mkdirSync, readdirSync, realpathSync } from 'node:fs';
|
|
21
|
+
import { homedir } from 'node:os';
|
|
22
|
+
import { basename, dirname, resolve, sep } from 'node:path';
|
|
23
|
+
import { fileURLToPath } from 'node:url';
|
|
24
|
+
import { homeRoot, humanRoot, payersRoot } from './roots.js';
|
|
25
|
+
|
|
26
|
+
const SEATBELT = '/usr/bin/sandbox-exec';
|
|
27
|
+
const MARKER = 'seatbelt';
|
|
28
|
+
const APP_DIR = resolve(fileURLToPath(new URL('..', import.meta.url)));
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The folder npm put this package's dependencies in, when the package itself was installed by npm (npx, a global
|
|
32
|
+
* install, a project's node_modules): they are its SIBLINGS there, not inside it, so the sandbox must let Node read
|
|
33
|
+
* that folder or nothing third-party loads. Undefined for a checkout (its own node_modules is inside appDir).
|
|
34
|
+
* @param {string} appDir @returns {string | undefined}
|
|
35
|
+
*/
|
|
36
|
+
export function dependencyDir(appDir) {
|
|
37
|
+
const parent = dirname(appDir);
|
|
38
|
+
if (basename(parent) === 'node_modules') return parent;
|
|
39
|
+
if (basename(parent).startsWith('@') && basename(dirname(parent)) === 'node_modules') return dirname(parent);
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Where people keep their own files on a Mac (real paths: /tmp and /var are links into /private). */
|
|
44
|
+
export const DENIED_ROOTS = Object.freeze(['/Users', '/Volumes', '/private/tmp', '/private/var/folders']);
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {{ readDirs: string[], readFiles: string[], readWrite: string[] }} SandboxPaths
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
/** Local services a native program could use to act outside the sandbox. */
|
|
51
|
+
const DENIED_SERVICES = Object.freeze([
|
|
52
|
+
'com.apple.coreservices.launchservicesd', 'com.apple.coreservices.appleevents', 'com.apple.securityd', 'com.apple.SecurityServer', 'com.apple.pasteboard.1',
|
|
53
|
+
]);
|
|
54
|
+
/**
|
|
55
|
+
* Where executable code may be mapped from besides node itself: macOS's own libraries only. Package-manager
|
|
56
|
+
* trees stay closed: they hold globally installed native add-ons that would give code in here native powers.
|
|
57
|
+
*/
|
|
58
|
+
const MAPPABLE_CODE = Object.freeze(['/usr/lib', '/System']);
|
|
59
|
+
/** Node builds that load their libraries from a package manager (Homebrew on Apple silicon or Intel, MacPorts). */
|
|
60
|
+
const PACKAGE_MANAGER_NODE = /^\/(?:opt\/homebrew|usr\/local\/Cellar|opt\/local)\//;
|
|
61
|
+
/** The one local socket the sandbox may use: macOS's DNS resolver. */
|
|
62
|
+
const DNS_SOCKET = '/private/var/run/mDNSResponder';
|
|
63
|
+
/** Environment variables passed into the sandbox; anything else (tokens, NODE_OPTIONS) stays outside. */
|
|
64
|
+
const ENV_ALLOWED = new Set(['HOME', 'USER', 'LOGNAME', 'LANG', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES', 'TZ', 'TMPDIR']);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @param {{ appDir: string, depDir?: string, homeRoot: string, payersRoot: string, humanRoot?: string, nodeBins: string[] }} where
|
|
68
|
+
* depDir: where npm installed the dependencies (dependencyDir), read only; humanRoot: the human's ~/TryFlop (tryflop),
|
|
69
|
+
* writable; nodeBins: the node program (only the file: Node's built-in modules are compiled in)
|
|
70
|
+
* @returns {SandboxPaths}
|
|
71
|
+
*/
|
|
72
|
+
export function sandboxPaths({ appDir, depDir, homeRoot: home, payersRoot: payers, humanRoot: human, nodeBins }) {
|
|
73
|
+
return { readDirs: [appDir, ...(depDir ? [depDir] : [])], readFiles: [...nodeBins], readWrite: [home, payers, ...(human ? [human] : [])] };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A Seatbelt string literal. @param {string} path */
|
|
77
|
+
function quote(path) {
|
|
78
|
+
if (/[\n\r\0]/.test(path)) throw new Error(`a sandbox path holds a newline or NUL: ${JSON.stringify(path)}`);
|
|
79
|
+
return `"${path.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The folders from `path`'s parent up to and including whichever denied root holds it. */
|
|
83
|
+
function foldersOnTheWay(path, deniedRoots) {
|
|
84
|
+
const root = deniedRoots.find((r) => path.startsWith(r + sep));
|
|
85
|
+
if (!root) return [];
|
|
86
|
+
const out = [];
|
|
87
|
+
for (let dir = dirname(path); dir === root || dir.startsWith(root + sep); dir = dirname(dir)) {
|
|
88
|
+
out.push(dir);
|
|
89
|
+
if (dir === root) break;
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The Seatbelt profile. Later rules win, so the denials come first and the connector's own paths are
|
|
96
|
+
* re-allowed after them. The folders on the way to an allowed path get metadata access only (Node looks
|
|
97
|
+
* each one up when it resolves a path); their contents stay hidden.
|
|
98
|
+
* @param {SandboxPaths} paths real paths (Seatbelt sees what the kernel sees)
|
|
99
|
+
* @param {{ deniedRoots: readonly string[], nodeBins: string[] }} options nodeBins: the node binary, the
|
|
100
|
+
* one program sandbox-exec itself starts
|
|
101
|
+
*/
|
|
102
|
+
export function seatbeltProfile(paths, { deniedRoots, nodeBins }) {
|
|
103
|
+
const lines = [
|
|
104
|
+
'(version 1)',
|
|
105
|
+
'(allow default)',
|
|
106
|
+
...deniedRoots.map((root) => `(deny file-read* file-write* (subpath ${quote(root)}))`),
|
|
107
|
+
'(deny file-write*)',
|
|
108
|
+
'(deny process-fork)',
|
|
109
|
+
'(deny process-exec*)',
|
|
110
|
+
...nodeBins.map((bin) => `(allow process-exec (literal ${quote(bin)}))`),
|
|
111
|
+
// Native code: only node and macOS's own libraries may be mapped as executable, so no add-on loads
|
|
112
|
+
// even in a node restarted without --no-addons (the restarted process stays in this sandbox).
|
|
113
|
+
'(deny file-map-executable)',
|
|
114
|
+
...nodeBins.map((bin) => `(allow file-map-executable (literal ${quote(bin)}))`),
|
|
115
|
+
...MAPPABLE_CODE.map((dir) => `(allow file-map-executable (subpath ${quote(dir)}))`),
|
|
116
|
+
// The connector never listens: no server, no debugger port.
|
|
117
|
+
'(deny network-bind)',
|
|
118
|
+
'(deny network-inbound)',
|
|
119
|
+
'(deny appleevent-send)',
|
|
120
|
+
`(deny mach-lookup ${DENIED_SERVICES.map((name) => `(global-name ${quote(name)})`).join(' ')})`,
|
|
121
|
+
'(deny network-outbound (remote unix-socket))',
|
|
122
|
+
`(allow network-outbound (remote unix-socket (path-literal ${quote(DNS_SOCKET)})))`,
|
|
123
|
+
// Nor this computer's own network services (dev servers, local admin APIs): the connector needs none.
|
|
124
|
+
'(deny network-outbound (remote ip "localhost:*"))',
|
|
125
|
+
];
|
|
126
|
+
const folders = new Set();
|
|
127
|
+
for (const path of [...paths.readDirs, ...paths.readFiles, ...paths.readWrite]) {
|
|
128
|
+
for (const folder of foldersOnTheWay(path, deniedRoots)) folders.add(folder);
|
|
129
|
+
}
|
|
130
|
+
for (const folder of [...folders].sort()) lines.push(`(allow file-read-metadata (literal ${quote(folder)}))`);
|
|
131
|
+
for (const dir of paths.readDirs) lines.push(`(allow file-read* (subpath ${quote(dir)}))`);
|
|
132
|
+
for (const file of paths.readFiles) lines.push(`(allow file-read* (literal ${quote(file)}))`);
|
|
133
|
+
for (const dir of paths.readWrite) lines.push(`(allow file-read* file-write* (subpath ${quote(dir)}))`);
|
|
134
|
+
return lines.join('\n');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** @param {string} path */
|
|
138
|
+
function realOrSame(path) {
|
|
139
|
+
try {
|
|
140
|
+
return realpathSync(path);
|
|
141
|
+
} catch {
|
|
142
|
+
return path;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @param {string} dir */
|
|
147
|
+
function refuseSymlink(dir) {
|
|
148
|
+
let stat;
|
|
149
|
+
try {
|
|
150
|
+
stat = lstatSync(dir);
|
|
151
|
+
} catch {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (stat.isSymbolicLink()) {
|
|
155
|
+
throw new Error(`${dir} is a symbolic link; flop-mcp keeps its data only in a real folder (the sandbox would follow the link elsewhere).`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** True when this process cannot list the user's home folder: what the sandbox guarantees. */
|
|
160
|
+
function homeIsHidden() {
|
|
161
|
+
try {
|
|
162
|
+
readdirSync(homedir());
|
|
163
|
+
return false;
|
|
164
|
+
} catch (error) {
|
|
165
|
+
return /** @type {any} */ (error).code === 'EPERM';
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Re-execute this command inside the sandbox, unless it already runs there. Never returns when it execs.
|
|
171
|
+
* @param {string[]} argv the command's own arguments (process.argv.slice(2))
|
|
172
|
+
* @param {{ proc?: any, platform?: string, homeHidden?: () => boolean,
|
|
173
|
+
* execve?: (file: string, args: string[], env: Record<string, string|undefined>) => void,
|
|
174
|
+
* allowUnsandboxed?: boolean, human?: boolean }} [deps]
|
|
175
|
+
* allowUnsandboxed: on Windows and Linux run without a sandbox instead of stopping (tryflop; the owner's decision of
|
|
176
|
+
* 27 Nov 2026) — the caller says so to the human; human: the human's ~/TryFlop is created (0700) and writable
|
|
177
|
+
* @returns {'sandboxed' | 'none'} 'sandboxed' inside macOS's sandbox; 'none' on Windows/Linux with allowUnsandboxed
|
|
178
|
+
*/
|
|
179
|
+
export function ensureSandboxed(argv, {
|
|
180
|
+
proc = process, platform = process.platform, homeHidden = homeIsHidden, execve = (file, args, env) => process.execve(file, args, env),
|
|
181
|
+
allowUnsandboxed = false, human = false,
|
|
182
|
+
} = {}) {
|
|
183
|
+
if (platform !== 'darwin') {
|
|
184
|
+
if (allowUnsandboxed) return 'none';
|
|
185
|
+
throw new Error('flop-mcp v1 runs on macOS only: it locks itself inside macOS\'s own sandbox (sandbox-exec). Other systems need a different sandbox, not built yet.');
|
|
186
|
+
}
|
|
187
|
+
if (proc.permission) {
|
|
188
|
+
throw new Error('flop-mcp was started with node --permission, which switches off fsync: its payment journal could not record a payment safely. Start it with plain "node"; it sandboxes itself.');
|
|
189
|
+
}
|
|
190
|
+
if (proc.env.FLOP_MCP_SANDBOX === MARKER) {
|
|
191
|
+
if (!homeHidden()) {
|
|
192
|
+
throw new Error('FLOP_MCP_SANDBOX is set but this process is not sandboxed (it can read the home folder). Start flop-mcp with plain "node" and without FLOP_MCP_SANDBOX.');
|
|
193
|
+
}
|
|
194
|
+
if (!(proc.execArgv ?? []).includes('--no-addons')) {
|
|
195
|
+
throw new Error('flop-mcp runs with native add-ons switched off (node --no-addons); this sandboxed process has them on. Start flop-mcp with plain "node".');
|
|
196
|
+
}
|
|
197
|
+
return 'sandboxed';
|
|
198
|
+
}
|
|
199
|
+
const home = homeRoot(proc.env);
|
|
200
|
+
const payers = payersRoot(proc.env);
|
|
201
|
+
const humanDir = human ? humanRoot(proc.env) : undefined;
|
|
202
|
+
for (const dir of [home, payers, ...(humanDir ? [humanDir] : [])]) {
|
|
203
|
+
refuseSymlink(dir);
|
|
204
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
205
|
+
}
|
|
206
|
+
const nodeBins = [...new Set([proc.execPath, realOrSame(proc.execPath)])];
|
|
207
|
+
if (nodeBins.some((bin) => PACKAGE_MANAGER_NODE.test(bin))) {
|
|
208
|
+
throw new Error(`this Node (${realOrSame(proc.execPath)}) loads its libraries from a package manager, which the sandbox does not allow. Run flop-mcp with Node 22.15 or newer from nodejs.org or nvm.`);
|
|
209
|
+
}
|
|
210
|
+
const depDir = dependencyDir(APP_DIR);
|
|
211
|
+
const real = sandboxPaths({
|
|
212
|
+
appDir: realOrSame(APP_DIR), depDir: depDir ? realOrSame(depDir) : undefined, homeRoot: realOrSame(home), payersRoot: realOrSame(payers),
|
|
213
|
+
humanRoot: humanDir ? realOrSame(humanDir) : undefined, nodeBins,
|
|
214
|
+
});
|
|
215
|
+
const profile = seatbeltProfile(real, { deniedRoots: DENIED_ROOTS, nodeBins });
|
|
216
|
+
/** @type {Record<string, string>} */
|
|
217
|
+
const env = { FLOP_MCP_SANDBOX: MARKER };
|
|
218
|
+
for (const [name, value] of Object.entries(proc.env)) {
|
|
219
|
+
if (value !== undefined && (ENV_ALLOWED.has(name) || (name.startsWith('FLOP_MCP_') && name !== 'FLOP_MCP_SANDBOX'))) env[name] = value;
|
|
220
|
+
}
|
|
221
|
+
execve(SEATBELT, [SEATBELT, '-p', profile, proc.execPath, '--no-addons', proc.argv[1], ...argv], env);
|
|
222
|
+
return 'sandboxed'; // only reached with a stand-in execve (tests): the real one replaces this process
|
|
223
|
+
}
|