paseo-plugin-secure-input 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/OVERVIEW.md +28 -0
- package/README.md +105 -2
- package/SECURITY.md +84 -0
- package/assets/icon.png +0 -0
- package/client/card.tsx +74 -0
- package/client/codes.ts +32 -0
- package/client/diagnostics-rows.ts +139 -0
- package/client/dialog-state.ts +59 -0
- package/client/dialog.tsx +292 -0
- package/client/envelope-cache.ts +85 -0
- package/client/fields.tsx +255 -0
- package/client/file-entry.ts +142 -0
- package/client/form-state.ts +198 -0
- package/client/globals.d.ts +19 -0
- package/client/outcome.ts +96 -0
- package/client/presentation.ts +114 -0
- package/client/sealing.ts +27 -0
- package/client/self-test.ts +96 -0
- package/client/settings.tsx +160 -0
- package/client/submit.ts +92 -0
- package/client/text.ts +47 -0
- package/client/tone.ts +36 -0
- package/client/web.ts +184 -0
- package/index.client.tsx +29 -0
- package/index.server.ts +6 -0
- package/npm-shrinkwrap.json +60 -0
- package/package.json +68 -4
- package/paseo-plugin.json +6 -0
- package/server/core/continuation.ts +151 -0
- package/server/core/entries.ts +89 -0
- package/server/core/outbox.ts +555 -0
- package/server/core/registry-store.ts +185 -0
- package/server/core/registry.ts +1031 -0
- package/server/core/selftest.ts +60 -0
- package/server/core/view.ts +38 -0
- package/server/io/atomic.ts +119 -0
- package/server/io/deadline.ts +28 -0
- package/server/io/descriptor.ts +36 -0
- package/server/io/directory.ts +40 -0
- package/server/io/drop.ts +434 -0
- package/server/io/legacy-shim.ts +108 -0
- package/server/io/ownership.ts +8 -0
- package/server/io/private-file.ts +86 -0
- package/server/paseo/bounded.ts +13 -0
- package/server/paseo/handlers.ts +124 -0
- package/server/paseo/hooks.ts +106 -0
- package/server/paseo/plugin.ts +341 -0
- package/server/paseo/runtime.ts +409 -0
- package/server/paseo/tools.ts +178 -0
- package/shared/bytes.ts +100 -0
- package/shared/canonical.ts +32 -0
- package/shared/card.ts +41 -0
- package/shared/contracts.ts +128 -0
- package/shared/errors.ts +48 -0
- package/shared/limits.ts +118 -0
- package/shared/request-id.ts +9 -0
- package/shared/request.ts +66 -0
- package/shared/sanitize.ts +101 -0
- package/shared/seal.ts +292 -0
- package/shared/shown.ts +12 -0
- package/shared/text.ts +39 -0
- package/shared/view.ts +42 -0
- package/skills/secure-input/SKILL.md +150 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { constants, type BigIntStats } from "node:fs";
|
|
3
|
+
import { chmod, lstat, mkdir, open, readdir, rename, rmdir, unlink } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { SecureInputError } from "../../shared/errors";
|
|
6
|
+
import { DROP_PREFIX, caseCollision, isValidKey } from "../../shared/limits";
|
|
7
|
+
import { REQUEST_ID_PATTERN } from "../../shared/request-id";
|
|
8
|
+
import type { StillWanted } from "./atomic";
|
|
9
|
+
import { errnoToken, withHandle, type OpenFile } from "./descriptor";
|
|
10
|
+
import { holdDirectory } from "./directory";
|
|
11
|
+
import { uid } from "./ownership";
|
|
12
|
+
|
|
13
|
+
// The drop is the one place a delivered value lives on the daemon, and this is the only code that creates or deletes
|
|
14
|
+
// anything under `<data>/drop/`. A request's values are a directory `si-secret-<requestId>` (0700) with a file for each
|
|
15
|
+
// key (0600), each holding the bytes it was given, as they are.
|
|
16
|
+
//
|
|
17
|
+
// Writing: the set is built under a temporary name in the root and renamed to its place, so that nobody ever finds half
|
|
18
|
+
// of it; a failure at any step takes away what was built and says only the errno. What stands at the set's path decides
|
|
19
|
+
// the rename: a link, a file or a directory that holds anything makes the write fail, and an empty directory is replaced.
|
|
20
|
+
// What a failed write cannot take away is named to the caller (`write`), which owes it from then on.
|
|
21
|
+
//
|
|
22
|
+
// Removing: `unlink` and `rmdir` only. Every entry is looked at with `lstat` first, so a link is unlinked as a link and
|
|
23
|
+
// what it points to is not touched. Node has no `unlinkat` or `openat`, so every call goes by path, and a path is only as
|
|
24
|
+
// good as the directories on the way to it. The store therefore looks at a directory again before it works in it, and goes
|
|
25
|
+
// on only if it is still the one it was reading. The root has one guard for every removal (`removeFromRoot`, with
|
|
26
|
+
// `lookAtRoot` before it): it is looked at without following a link, it has to be a real directory of this user, its
|
|
27
|
+
// device and inode are kept, and it is looked at again right before each of its entries is taken away. A root that is a
|
|
28
|
+
// link, a file or another user's is not worked through at all, and one swapped since it was looked at is not worked
|
|
29
|
+
// through from there on. Any other directory is looked at again before each of its entries and before it is taken away
|
|
30
|
+
// itself (`removeChild`, `removeEmptied`). A directory swapped for a link, or for another directory, since it was read is
|
|
31
|
+
// not worked through. What this leaves is a swap by a process of the same user that lands between a look and the call it
|
|
32
|
+
// guards (the entry's own `lstat` and, for a file, its `unlink`): it narrows that swap and does not close it. A write holds
|
|
33
|
+
// the root first and looks at it once more right before the rename that puts the set in place; between the two, its
|
|
34
|
+
// files are made by path in the directory it staged them in.
|
|
35
|
+
//
|
|
36
|
+
// The caller owns the bytes it gives and wipes them. Nothing here copies them, keeps them or puts any of them in an error.
|
|
37
|
+
|
|
38
|
+
/** The mode of the root and of every set in it: a directory only this user can enter, list or change. */
|
|
39
|
+
export const DIRECTORY_MODE = 0o700;
|
|
40
|
+
|
|
41
|
+
/** The mode of every file of a set: a file only this user can read or write. */
|
|
42
|
+
export const FILE_MODE = 0o600;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* How many levels of directories a removal goes down, the set being the first. A set holds files, so this is far more than
|
|
46
|
+
* an honest one has; what is deeper was not put there by this plugin, and is left, and counted as stuck.
|
|
47
|
+
*/
|
|
48
|
+
export const DROP_MAX_DEPTH = 8;
|
|
49
|
+
|
|
50
|
+
/** What became of an entry: taken away; not there (or gone while it was looked at); or still there, whether because it could not be taken away, may not be, or is too deep. */
|
|
51
|
+
export type Removal = "removed" | "absent" | "stuck";
|
|
52
|
+
|
|
53
|
+
export interface SweepResult {
|
|
54
|
+
/** The entries of the root that were taken away. A set counts once, not once for each of its files. */
|
|
55
|
+
removed: number;
|
|
56
|
+
/** The entries of the root that are still there: each that could not be taken away, and the one a sweep that ended early ended at. */
|
|
57
|
+
stuck: number;
|
|
58
|
+
/** The names of the entries that were taken away, as `removed` counts them. */
|
|
59
|
+
took: string[];
|
|
60
|
+
/**
|
|
61
|
+
* The names of the entries that were read and are, as far as the sweep knows, still there: each that could not be
|
|
62
|
+
* taken away, and, when the sweep ended early, every one it did not come to. Not the ones it found gone.
|
|
63
|
+
*/
|
|
64
|
+
left: string[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** One file of a set. The caller owns `bytes` and wipes them; the store neither copies nor keeps them. */
|
|
68
|
+
export interface DropFile {
|
|
69
|
+
key: string;
|
|
70
|
+
bytes: Uint8Array;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A directory as it was seen: a path says where, never which, and a swap changes the one without the other. */
|
|
74
|
+
interface Identity {
|
|
75
|
+
dev: bigint;
|
|
76
|
+
ino: bigint;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The words `holdDirectory` refuses the root with when it is no real directory of this user; a sweep and a write say the same of a root that has become something else since. */
|
|
80
|
+
const ROOT_NOT_PRIVATE = "the drop directory is not a private directory of this user";
|
|
81
|
+
|
|
82
|
+
/** What a sweep says of a root it cannot read, or that is gone by the time it looks again. */
|
|
83
|
+
const ROOT_UNREADABLE = "the drop directory cannot be read";
|
|
84
|
+
|
|
85
|
+
/** `si-secret-<requestId>`, the name of a request's set in the root. Only an id of the shape the registry gives makes a name, so no id can name anything outside the root. */
|
|
86
|
+
export function setName(requestId: string): string {
|
|
87
|
+
// `typeof` first: the pattern's `test` turns anything into text, and an object that reads as an id is not one.
|
|
88
|
+
if (typeof requestId !== "string" || !REQUEST_ID_PATTERN.test(requestId)) {
|
|
89
|
+
throw new SecureInputError("invalid_request", "the request id is not valid");
|
|
90
|
+
}
|
|
91
|
+
return `${DROP_PREFIX}${requestId}`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `<root>/si-secret-<requestId>`: see `setName`. */
|
|
95
|
+
export function setPath(root: string, requestId: string): string {
|
|
96
|
+
return join(root, setName(requestId));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Whether `name` can be one entry of the root as a directory lists it: text, not empty, not `.` or `..`, and with no `/`
|
|
101
|
+
* and no NUL in it. What a sweep or a write names to the caller is always such a name; anything else would be a path.
|
|
102
|
+
*/
|
|
103
|
+
function isEntryName(name: unknown): name is string {
|
|
104
|
+
return typeof name === "string" && name !== "" && name !== "." && name !== ".." && !name.includes("/") && !name.includes(String.fromCodePoint(0));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** `<root>/si-secret-<requestId>/<key>`. A key is a name no path can be made of, and not one an object treats specially: see `isValidKey`. */
|
|
108
|
+
export function filePath(root: string, requestId: string, key: string): string {
|
|
109
|
+
const set = setPath(root, requestId);
|
|
110
|
+
if (!isValidKey(key)) throw new SecureInputError("invalid_request", "a key is not a valid file name");
|
|
111
|
+
return join(set, key);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The one error a write raises for anything that went wrong on disk: the errno name, or nothing. A refusal of our own passes as it is. */
|
|
115
|
+
function failed(error: unknown): SecureInputError {
|
|
116
|
+
return error instanceof SecureInputError ? error : new SecureInputError("write_failed", errnoToken(error));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Of `lstat` and `unlink`: no entry of that name (ENOENT), or a parent that is no directory (ENOTDIR). Either way nothing
|
|
121
|
+
* is there. A file can still appear there later; this is only what was seen.
|
|
122
|
+
*/
|
|
123
|
+
function isAbsent(error: unknown): boolean {
|
|
124
|
+
const code = errnoToken(error);
|
|
125
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Of `readdir` and `rmdir`, which are made on a path that was a directory a moment ago: only ENOENT says it is gone.
|
|
130
|
+
* ENOTDIR says something that is no directory is there now, and that is still there.
|
|
131
|
+
*/
|
|
132
|
+
function isGone(error: unknown): boolean {
|
|
133
|
+
return errnoToken(error) === "ENOENT";
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Whether `path` is, right now, the directory that was seen: a directory (a link to one is not), with that device and inode. Never throws. */
|
|
137
|
+
async function isDirectoryOf(path: string, seen: Identity): Promise<boolean> {
|
|
138
|
+
try {
|
|
139
|
+
const info = await lstat(path, { bigint: true });
|
|
140
|
+
return info.isDirectory() && info.dev === seen.dev && info.ino === seen.ino;
|
|
141
|
+
} catch {
|
|
142
|
+
return false;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* What stands at the root, looked at without following a link: a real directory of this user, by its device and inode;
|
|
148
|
+
* nothing (`absent`); anything else, a link, a file or a directory of another user (`other`); or what cannot be looked at
|
|
149
|
+
* (`unreadable`).
|
|
150
|
+
*/
|
|
151
|
+
type RootLook = { kind: "directory"; seen: Identity } | { kind: "absent" } | { kind: "other" } | { kind: "unreadable" };
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* `unlink` never removes a directory and never follows a link. `stillWanted` is asked first, with nothing awaited between
|
|
155
|
+
* its answer and the call: see `StillWanted`. Never throws, so a clean-up cannot replace the outcome of a write.
|
|
156
|
+
*/
|
|
157
|
+
async function unlinkFile(path: string, stillWanted: StillWanted): Promise<Removal> {
|
|
158
|
+
if (!stillWanted()) return "stuck";
|
|
159
|
+
try {
|
|
160
|
+
await unlink(path);
|
|
161
|
+
return "removed";
|
|
162
|
+
} catch (error) {
|
|
163
|
+
return isAbsent(error) ? "absent" : "stuck";
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** `rmdir` of a directory that was emptied: only if it is still the directory that was emptied, and only if it is still wanted. Never throws. */
|
|
168
|
+
async function removeEmptied(path: string, seen: Identity, stillWanted: StillWanted): Promise<Removal> {
|
|
169
|
+
if (!(await isDirectoryOf(path, seen))) return "stuck";
|
|
170
|
+
if (!stillWanted()) return "stuck";
|
|
171
|
+
try {
|
|
172
|
+
await rmdir(path);
|
|
173
|
+
return "removed";
|
|
174
|
+
} catch (error) {
|
|
175
|
+
return isGone(error) ? "absent" : "stuck";
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** What ended a write short of its end: a failure of the store's own, or whatever the caller's last word threw. `undefined` is "nothing yet". */
|
|
180
|
+
type Ended = { error: unknown } | undefined;
|
|
181
|
+
|
|
182
|
+
/** Asks the caller's last word, and says what it threw, if it did. What the caller threw is not the store's to turn into anything else. */
|
|
183
|
+
function turnedBack(beforeEffect: (() => void) | undefined): Ended {
|
|
184
|
+
try {
|
|
185
|
+
beforeEffect?.();
|
|
186
|
+
return undefined;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return { error };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export class DropStore {
|
|
193
|
+
private readonly openFile: OpenFile;
|
|
194
|
+
|
|
195
|
+
/** `openFile` is how each file of a set is opened; only a test passes one. */
|
|
196
|
+
constructor(
|
|
197
|
+
readonly root: string,
|
|
198
|
+
options: { openFile?: OpenFile } = {},
|
|
199
|
+
) {
|
|
200
|
+
this.openFile = options.openFile ?? open;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** The root is a real directory of this user at 0700, made if it is not there; anything else (a link, a file, another user's) is refused. */
|
|
204
|
+
hold(): Promise<void> {
|
|
205
|
+
return holdDirectory(this.root, "drop");
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The root as it is now (`RootLook`), by `lstat`, which follows no link. Never throws. The first look of the root's guard; a test acts right after it. */
|
|
209
|
+
protected async lookAtRoot(): Promise<RootLook> {
|
|
210
|
+
try {
|
|
211
|
+
const info = await lstat(this.root, { bigint: true });
|
|
212
|
+
if (!info.isDirectory() || info.uid !== BigInt(uid())) return { kind: "other" };
|
|
213
|
+
return { kind: "directory", seen: { dev: info.dev, ino: info.ino } };
|
|
214
|
+
} catch (error) {
|
|
215
|
+
return isAbsent(error) ? { kind: "absent" } : { kind: "unreadable" };
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* The root held for what makes entries in it or sweeps them (`write`, `sweep`): `hold` first, which makes it when it is
|
|
221
|
+
* missing and refuses a link, a file or another user's directory, and then looked at again (`lookAtRoot`), since `hold`
|
|
222
|
+
* looked by path and the root can have been swapped since. Its device and inode are what the guard compares with from
|
|
223
|
+
* then on. Not caught: a swap for another directory in the instant between `hold`'s look and this one, which has no
|
|
224
|
+
* identity of `hold`'s to compare with.
|
|
225
|
+
*/
|
|
226
|
+
private async holdRoot(): Promise<Identity> {
|
|
227
|
+
await this.hold();
|
|
228
|
+
const root = await this.lookAtRoot();
|
|
229
|
+
if (root.kind === "directory") return root.seen;
|
|
230
|
+
if (root.kind === "other") throw new SecureInputError("service_unavailable", ROOT_NOT_PRIVATE);
|
|
231
|
+
throw new SecureInputError("service_unavailable", ROOT_UNREADABLE);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Puts a request's files in place as one set: every file written and flushed under a temporary name, then the
|
|
236
|
+
* directory renamed to `si-secret-<requestId>`. Right before the rename the root is looked at once more, and a root
|
|
237
|
+
* that is no longer the directory that was held fails the write (`the drop directory is not a private directory of this
|
|
238
|
+
* user`): the rename goes by path, and through a root swapped for a link it would put the set where the link leads.
|
|
239
|
+
* Then the caller's last word, `beforeEffect`, is asked once, with every file written and nothing yet at the set's path
|
|
240
|
+
* (the registry says no there once it is shutting down), and nothing is awaited between its answer and the rename; what
|
|
241
|
+
* it throws comes out as it was thrown. After a failure at any step what was staged is taken away, under the root's
|
|
242
|
+
* guard, and what comes out is a refusal of this module's own, or `write_failed` with the errno. What the clean-up could
|
|
243
|
+
* not take away (a staging directory it may not change, a root that is no longer the one that was held) is left where it
|
|
244
|
+
* is, and its name in the root is given to `onLeftover` before the failure comes out: from then on the caller owes it.
|
|
245
|
+
*
|
|
246
|
+
* The rename is what refuses a set's path that is taken: a link or a file there fails it (ENOTDIR), and so does a
|
|
247
|
+
* directory that holds anything (ENOTEMPTY). Only an empty directory is replaced.
|
|
248
|
+
*/
|
|
249
|
+
async write(requestId: string, files: readonly DropFile[], beforeEffect?: () => void, onLeftover?: (name: string) => void): Promise<void> {
|
|
250
|
+
if (files.length === 0) throw new SecureInputError("invalid_request", "nothing to write");
|
|
251
|
+
const set = setPath(this.root, requestId);
|
|
252
|
+
for (const { key } of files) filePath(this.root, requestId, key);
|
|
253
|
+
const collision = caseCollision(files.map(({ key }) => key));
|
|
254
|
+
if (collision !== null) throw new SecureInputError("invalid_request", `${collision[0]} and ${collision[1]} name the same file`);
|
|
255
|
+
|
|
256
|
+
const seen = await this.holdRoot();
|
|
257
|
+
const name = `${setName(requestId)}.${randomBytes(8).toString("hex")}.tmp`;
|
|
258
|
+
const staging = join(this.root, name);
|
|
259
|
+
try {
|
|
260
|
+
await mkdir(staging, { mode: DIRECTORY_MODE });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
// Nothing of ours is at that name, so there is nothing to take away.
|
|
263
|
+
throw failed(error);
|
|
264
|
+
}
|
|
265
|
+
let ended: Ended = undefined;
|
|
266
|
+
try {
|
|
267
|
+
// The umask may have taken bits from the mode the directory was made with.
|
|
268
|
+
await chmod(staging, DIRECTORY_MODE);
|
|
269
|
+
for (const { key, bytes } of files) await this.put(join(staging, key), bytes);
|
|
270
|
+
if (!(await isDirectoryOf(this.root, seen))) throw new SecureInputError("service_unavailable", ROOT_NOT_PRIVATE);
|
|
271
|
+
ended = turnedBack(beforeEffect);
|
|
272
|
+
if (ended === undefined) await rename(staging, set);
|
|
273
|
+
} catch (error) {
|
|
274
|
+
ended = { error: failed(error) };
|
|
275
|
+
}
|
|
276
|
+
if (ended !== undefined) {
|
|
277
|
+
const cleanup = await this.removeFromRoot(seen, name, () => true);
|
|
278
|
+
if (cleanup === "stuck" || cleanup === "moved") {
|
|
279
|
+
try {
|
|
280
|
+
onLeftover?.(name);
|
|
281
|
+
} catch {
|
|
282
|
+
// What the caller does with the name never replaces the outcome of the write.
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
throw ended.error;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** One file: created new and never through a link, 0600 whatever the umask says, written, flushed and closed. */
|
|
290
|
+
private async put(path: string, content: Uint8Array): Promise<void> {
|
|
291
|
+
const handle = await this.openFile(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, FILE_MODE);
|
|
292
|
+
await withHandle(handle, async () => {
|
|
293
|
+
await handle.chmod(FILE_MODE);
|
|
294
|
+
await handle.writeFile(content);
|
|
295
|
+
await handle.sync();
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** False only when the set is known to be gone: one that cannot be looked at is taken to be there. */
|
|
300
|
+
async exists(requestId: string): Promise<boolean> {
|
|
301
|
+
const path = setPath(this.root, requestId);
|
|
302
|
+
try {
|
|
303
|
+
await lstat(path);
|
|
304
|
+
return true;
|
|
305
|
+
} catch (error) {
|
|
306
|
+
return !isAbsent(error);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Takes the set away, whatever it came to hold, links as links, under the root's guard. `absent` when there is none (no
|
|
312
|
+
* root either); `stuck` when anything of it is still there, and when the root is a link, a file or anything but a real
|
|
313
|
+
* directory of this user, or has been swapped since it was looked at: what it points to is not touched.
|
|
314
|
+
*/
|
|
315
|
+
async release(requestId: string): Promise<Removal> {
|
|
316
|
+
return this.removeNamed(setName(requestId));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Takes away one entry of the root by its name, whatever it is, links as links, under the root's guard, as `release`
|
|
321
|
+
* does a set: what a sweep left or a failed write could not take away, which the caller owes and tries again by itself.
|
|
322
|
+
* A name that is not one entry of the root (a path, `..`) is refused before anything is touched.
|
|
323
|
+
*/
|
|
324
|
+
async remove(name: string): Promise<Removal> {
|
|
325
|
+
if (!isEntryName(name)) throw new SecureInputError("invalid_request", "the name is not an entry of the drop directory");
|
|
326
|
+
return this.removeNamed(name);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** One entry of the root, by its name, under the root's guard: see `release`. Made nothing: a missing root is not made. */
|
|
330
|
+
private async removeNamed(name: string): Promise<Removal> {
|
|
331
|
+
const root = await this.lookAtRoot();
|
|
332
|
+
if (root.kind === "absent") return "absent";
|
|
333
|
+
if (root.kind !== "directory") return "stuck";
|
|
334
|
+
const removal = await this.removeFromRoot(root.seen, name, () => true);
|
|
335
|
+
return removal === "moved" ? "stuck" : removal;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* The root's guard, right before one of its entries is taken away: the root is looked at again, and the entry is taken
|
|
340
|
+
* away only while the root is still the directory that was looked at (`seen`). `moved` when it is not: nothing of the
|
|
341
|
+
* entry is touched then, since its path leads somewhere else now.
|
|
342
|
+
*/
|
|
343
|
+
private async removeFromRoot(seen: Identity, name: string, stillWanted: StillWanted): Promise<Removal | "moved"> {
|
|
344
|
+
if (!(await isDirectoryOf(this.root, seen))) return "moved";
|
|
345
|
+
return this.removeEntry(join(this.root, name), 1, stillWanted);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Takes away everything in the root, of every kind (sets, leftovers of a write that was killed, whatever else was put
|
|
350
|
+
* there) and leaves the root. The root is held first (`holdRoot`), which refuses a link or a file, and then guarded as
|
|
351
|
+
* for every removal (`removeFromRoot`): before each entry it is looked at once more, and if it is no longer the
|
|
352
|
+
* directory that was held (swapped for a link, or for another directory) the sweep ends there, with that entry stuck and
|
|
353
|
+
* nothing of it removed. Not caught: a swap that lands between a look and the removal it guards (see the top of the
|
|
354
|
+
* file). A `stillWanted` that says no ends the sweep too: nothing more is removed or tried, and the entry it stopped at
|
|
355
|
+
* is stuck. The answer names what was taken away and what is left: the entries that are stuck, and those a sweep that
|
|
356
|
+
* ended early did not come to.
|
|
357
|
+
*/
|
|
358
|
+
async sweep(stillWanted: StillWanted = () => true): Promise<SweepResult> {
|
|
359
|
+
const seen = await this.holdRoot();
|
|
360
|
+
let names: string[];
|
|
361
|
+
try {
|
|
362
|
+
names = await readdir(this.root);
|
|
363
|
+
} catch {
|
|
364
|
+
throw new SecureInputError("service_unavailable", ROOT_UNREADABLE);
|
|
365
|
+
}
|
|
366
|
+
let wanted = true;
|
|
367
|
+
const ask: StillWanted = () => {
|
|
368
|
+
if (wanted) wanted = stillWanted();
|
|
369
|
+
return wanted;
|
|
370
|
+
};
|
|
371
|
+
const result: SweepResult = { removed: 0, stuck: 0, took: [], left: [] };
|
|
372
|
+
for (const [index, name] of names.entries()) {
|
|
373
|
+
if (!wanted) {
|
|
374
|
+
result.left.push(...names.slice(index));
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
// Right before each entry, not once for the sweep: the root can be swapped at any point of it. A root that is not
|
|
378
|
+
// the directory the sweep began in is left alone, and the sweep ends with this entry stuck.
|
|
379
|
+
const removal = await this.removeFromRoot(seen, name, ask);
|
|
380
|
+
if (removal === "moved") {
|
|
381
|
+
result.stuck += 1;
|
|
382
|
+
result.left.push(...names.slice(index));
|
|
383
|
+
break;
|
|
384
|
+
}
|
|
385
|
+
if (removal === "removed") {
|
|
386
|
+
result.removed += 1;
|
|
387
|
+
result.took.push(name);
|
|
388
|
+
} else if (removal === "stuck") {
|
|
389
|
+
result.stuck += 1;
|
|
390
|
+
result.left.push(name);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
return result;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Takes one entry away, `depth` levels below the root; a link is unlinked as a link, not followed. No failure of the
|
|
398
|
+
* disk makes it throw: what cannot be done is `stuck`. A directory is emptied entry by entry, and the first that is
|
|
399
|
+
* stuck ends it: `rmdir` is not tried on a directory that still holds something, and `stillWanted` is asked right
|
|
400
|
+
* before each `unlink` and each `rmdir`.
|
|
401
|
+
*/
|
|
402
|
+
private async removeEntry(path: string, depth: number, stillWanted: StillWanted): Promise<Removal> {
|
|
403
|
+
let info: BigIntStats;
|
|
404
|
+
try {
|
|
405
|
+
info = await lstat(path, { bigint: true });
|
|
406
|
+
} catch (error) {
|
|
407
|
+
return isAbsent(error) ? "absent" : "stuck";
|
|
408
|
+
}
|
|
409
|
+
if (!info.isDirectory()) return unlinkFile(path, stillWanted);
|
|
410
|
+
if (depth > DROP_MAX_DEPTH) return "stuck";
|
|
411
|
+
const seen: Identity = { dev: info.dev, ino: info.ino };
|
|
412
|
+
let names: string[];
|
|
413
|
+
try {
|
|
414
|
+
names = await readdir(path);
|
|
415
|
+
} catch (error) {
|
|
416
|
+
return isGone(error) ? "absent" : "stuck";
|
|
417
|
+
}
|
|
418
|
+
for (const name of names) {
|
|
419
|
+
if ((await this.removeChild(path, seen, name, depth + 1, stillWanted)) === "stuck") return "stuck";
|
|
420
|
+
}
|
|
421
|
+
return removeEmptied(path, seen, stillWanted);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Takes the entry `name` out of `parent`, which is `depth` levels below the root. First `parent` is looked at again:
|
|
426
|
+
* `unlink` and `rmdir` go by path, and if the directory that was read has been swapped for a link (or for any other
|
|
427
|
+
* directory) since, the path now leads somewhere else: the entry is then stuck, not removed through it. A swap after
|
|
428
|
+
* this look is the gap the top of the file speaks of.
|
|
429
|
+
*/
|
|
430
|
+
protected async removeChild(parent: string, seen: Identity, name: string, depth: number, stillWanted: StillWanted): Promise<Removal> {
|
|
431
|
+
if (!(await isDirectoryOf(parent, seen))) return "stuck";
|
|
432
|
+
return this.removeEntry(join(parent, name), depth, stillWanted);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { lstat } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, join } from "node:path";
|
|
3
|
+
import { SecureInputError } from "../../shared/errors";
|
|
4
|
+
import { writePrivateFileIf, type StillWanted } from "./atomic";
|
|
5
|
+
import { errnoToken } from "./descriptor";
|
|
6
|
+
import { holdDirectory } from "./directory";
|
|
7
|
+
|
|
8
|
+
/** What an agent created under v1 is told when it calls a tool of its old server or runs the old CLI. */
|
|
9
|
+
export const LEGACY_TEXT = "secure-input now gives its tools through Paseo itself. This old server has none. Do not ask for the secret in chat instead.";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* What takes the place of v1's bridge in `<data>/bin/bridge.cjs`. An agent created under v1 keeps, in its stored
|
|
13
|
+
* configuration, an MCP server that runs `<data>/bin/secure-input mcp --binding <id>`, and its shell may run the same shim
|
|
14
|
+
* as a CLI. The shim runs this script with Node, which has nothing installed beside it: CommonJS and Node's built-ins only.
|
|
15
|
+
*
|
|
16
|
+
* As an MCP server (newline-delimited JSON-RPC on stdio) it has no tools: `initialize`, `ping` and `tools/list` are
|
|
17
|
+
* answered, a tool call gets `LEGACY_TEXT` as a tool error, and any other request is a method that is not found. What
|
|
18
|
+
* needs no answer gets none: a notification, an id that cannot be sent back as it came, a message without a method, a
|
|
19
|
+
* line that is not JSON. It ends with its input. In any other mode it prints the refusal and exits 1.
|
|
20
|
+
*/
|
|
21
|
+
export const LEGACY_STUB_SOURCE = `"use strict";
|
|
22
|
+
// Written by the secure-input plugin in place of the bridge of v1. Its tools now come from Paseo itself.
|
|
23
|
+
const TEXT = ${JSON.stringify(LEGACY_TEXT)};
|
|
24
|
+
const PROTOCOLS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
|
|
25
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
26
|
+
const write = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
|
|
27
|
+
|
|
28
|
+
function answer(line) {
|
|
29
|
+
let message;
|
|
30
|
+
try {
|
|
31
|
+
message = JSON.parse(line);
|
|
32
|
+
} catch {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
if (!isRecord(message)) return;
|
|
36
|
+
const id = message.id;
|
|
37
|
+
if (typeof id !== "string" && !(typeof id === "number" && Number.isSafeInteger(id))) return;
|
|
38
|
+
if (typeof message.method !== "string") return;
|
|
39
|
+
const result = (value) => write({ jsonrpc: "2.0", id, result: value });
|
|
40
|
+
switch (message.method) {
|
|
41
|
+
case "initialize": {
|
|
42
|
+
const asked = isRecord(message.params) ? message.params.protocolVersion : undefined;
|
|
43
|
+
return result({
|
|
44
|
+
protocolVersion: PROTOCOLS.includes(asked) ? asked : PROTOCOLS[0],
|
|
45
|
+
capabilities: { tools: {} },
|
|
46
|
+
serverInfo: { name: "secure-input", version: "0.2.0" },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
case "ping":
|
|
50
|
+
return result({});
|
|
51
|
+
case "tools/list":
|
|
52
|
+
return result({ tools: [] });
|
|
53
|
+
case "tools/call":
|
|
54
|
+
return result({ content: [{ type: "text", text: TEXT }], isError: true });
|
|
55
|
+
default:
|
|
56
|
+
return write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found" } });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (process.argv[2] === "mcp") {
|
|
61
|
+
const lines = require("node:readline").createInterface({ input: process.stdin });
|
|
62
|
+
lines.on("line", answer);
|
|
63
|
+
lines.on("close", () => process.stdout.write("", () => process.exit(0)));
|
|
64
|
+
} else {
|
|
65
|
+
process.stdout.write(JSON.stringify({ error: "service_unavailable", message: TEXT }) + "\\n", () => process.exit(1));
|
|
66
|
+
}
|
|
67
|
+
`;
|
|
68
|
+
|
|
69
|
+
function quote(text: string): string {
|
|
70
|
+
return `'${text.replaceAll("'", `'\\''`)}'`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Puts the stub where v1 left its bridge, so that an agent created under v1 meets a server with no tools and no error,
|
|
75
|
+
* and under Node points the shim at the daemon's own Node: the one v1 wrote down may have been upgraded away since. Under
|
|
76
|
+
* Electron the shim stays as v1 wrote it, because Electron's binary runs no script as Node.
|
|
77
|
+
*
|
|
78
|
+
* Only where v1 installed: without `<data>/bin` nothing is made (`absent`). The directory holds code an agent executes,
|
|
79
|
+
* so it gets v1's rule: a real directory of this user, held at 0700, never a link. Both paths that go into the shim must
|
|
80
|
+
* be absolute; a relative one would depend on the working directory of whoever runs it.
|
|
81
|
+
*
|
|
82
|
+
* It is a step of the start-up, and `stillWanted` is that start-up's question, asked for each file before anything of it
|
|
83
|
+
* is written and again right before it is put in place (`writePrivateFileIf`). On "no" that file and the one after it
|
|
84
|
+
* are not written, what was there stays (it may be what the plugin started after this one wrote), and the answer is
|
|
85
|
+
* `not_wanted`.
|
|
86
|
+
*/
|
|
87
|
+
export async function replaceLegacyBridge(
|
|
88
|
+
dataDir: string,
|
|
89
|
+
runtime: { kind: "node" | "electron"; execPath: string },
|
|
90
|
+
stillWanted: StillWanted = () => true,
|
|
91
|
+
): Promise<"replaced" | "absent" | "not_wanted"> {
|
|
92
|
+
const { kind, execPath } = runtime;
|
|
93
|
+
if (!isAbsolute(dataDir)) throw new SecureInputError("service_unavailable", "the data directory must be an absolute path");
|
|
94
|
+
if (kind === "node" && !isAbsolute(execPath)) throw new SecureInputError("service_unavailable", "the node path must be an absolute path");
|
|
95
|
+
const bin = join(dataDir, "bin");
|
|
96
|
+
try {
|
|
97
|
+
await lstat(bin);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (errnoToken(error) === "ENOENT") return "absent";
|
|
100
|
+
// Anything else is said by the hold, in its own words.
|
|
101
|
+
}
|
|
102
|
+
await holdDirectory(bin, "bridge");
|
|
103
|
+
const bridge = join(bin, "bridge.cjs");
|
|
104
|
+
if (!(await writePrivateFileIf(bridge, LEGACY_STUB_SOURCE, 0o700, stillWanted))) return "not_wanted";
|
|
105
|
+
if (kind === "electron") return "replaced";
|
|
106
|
+
const shim = `#!/bin/sh\nexec ${quote(execPath)} ${quote(bridge)} "$@"\n`;
|
|
107
|
+
return (await writePrivateFileIf(join(bin, "secure-input"), shim, 0o700, stillWanted)) ? "replaced" : "not_wanted";
|
|
108
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The user the plugin runs as. The plugin runs on macOS and Linux only (`os` in package.json), where there is one; what
|
|
3
|
+
* a directory or a file has to be owned by is decided where each is checked (a private directory, `holdDirectory`): only
|
|
4
|
+
* the number is shared.
|
|
5
|
+
*/
|
|
6
|
+
export function uid(): number {
|
|
7
|
+
return (process.getuid as () => number)();
|
|
8
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { open, type FileHandle } from "node:fs/promises";
|
|
3
|
+
import { SecureInputError } from "../../shared/errors";
|
|
4
|
+
import { errnoToken } from "./descriptor";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Why `readPrivateFile` refuses a file for what it is, as opposed to a read that failed just now: a link in its place,
|
|
8
|
+
* something that is no regular file (a pipe, a directory, a device), more bytes than the caller allows, bytes that are
|
|
9
|
+
* not UTF-8. A file refused for one of these is not one the plugin wrote; a caller that owns the file may replace it.
|
|
10
|
+
*/
|
|
11
|
+
export const PRIVATE_FILE_REFUSALS = ["link", "not_regular", "too_large", "not_utf8"] as const;
|
|
12
|
+
export type PrivateFileRefusal = (typeof PRIVATE_FILE_REFUSALS)[number];
|
|
13
|
+
|
|
14
|
+
/** The errno a link in place of the file gives under `O_NOFOLLOW`: `ELOOP`, and `EMLINK` where that is the errno. */
|
|
15
|
+
const LINK_ERRNOS: ReadonlySet<string> = new Set(["ELOOP", "EMLINK"]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* What `readPrivateFile` rejects with. `refusal` is the token of the reason when the file itself was refused, and
|
|
19
|
+
* `null` when it could not be read just now (`EACCES`, `EIO`, `EMFILE`, ...), which says nothing about what it holds.
|
|
20
|
+
* The message is the one a `SecureInputError` has: `write_failed`, then an errno name or a fixed phrase.
|
|
21
|
+
*/
|
|
22
|
+
export class PrivateFileError extends SecureInputError {
|
|
23
|
+
constructor(
|
|
24
|
+
detail: string | undefined,
|
|
25
|
+
readonly refusal: PrivateFileRefusal | null,
|
|
26
|
+
) {
|
|
27
|
+
super("write_failed", detail);
|
|
28
|
+
this.name = "PrivateFileError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** The token of the reason `readPrivateFile` refused a file for, or `null` for any other error. */
|
|
33
|
+
export function privateFileRefusal(error: unknown): PrivateFileRefusal | null {
|
|
34
|
+
return error instanceof PrivateFileError ? error.refusal : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function failed(error: unknown): PrivateFileError {
|
|
38
|
+
if (error instanceof PrivateFileError) return error;
|
|
39
|
+
const errno = errnoToken(error);
|
|
40
|
+
return new PrivateFileError(errno, errno !== undefined && LINK_ERRNOS.has(errno) ? "link" : null);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The text of a state file of the plugin's own, which the agent can also write: so it is read as hostile input. One
|
|
45
|
+
* handle, no link followed, no wait on a pipe, a regular file only (the one thing `fstat` is trusted for), no more than
|
|
46
|
+
* `maxBytes` (one byte more is read, so a file that grows meanwhile is still caught) and UTF-8 only. `null` when there
|
|
47
|
+
* is no such file. Everything else rejects with a `PrivateFileError`: `write_failed` and a detail that is an errno name
|
|
48
|
+
* or a fixed phrase, never anything the file held.
|
|
49
|
+
*
|
|
50
|
+
* Scope: this is for files inside the plugin's own 0700 data directory. It does not check who owns the file, how many
|
|
51
|
+
* links it has or whether it is executable, so it is not for files anywhere else. `O_NOFOLLOW` covers the last
|
|
52
|
+
* component of the path only; the directories above it are the caller's. `write_failed` is this codebase's code for
|
|
53
|
+
* "the plugin's own file is unusable", whether it was being read or written. A caller tells the reasons apart by
|
|
54
|
+
* `privateFileRefusal`, not by the text: `link` (`ELOOP`, or `EMLINK` where that is the errno), `not_regular` ("not a
|
|
55
|
+
* regular file"), `too_large` ("larger than N bytes") and `not_utf8` ("not valid UTF-8") mean the file is not what the
|
|
56
|
+
* plugin wrote; `null` goes with any other errno name, or none, and means the file could not be read right now.
|
|
57
|
+
*/
|
|
58
|
+
export async function readPrivateFile(path: string, maxBytes: number): Promise<string | null> {
|
|
59
|
+
let handle: FileHandle;
|
|
60
|
+
try {
|
|
61
|
+
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (errnoToken(error) === "ENOENT") return null;
|
|
64
|
+
throw failed(error);
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
if (!(await handle.stat()).isFile()) throw new PrivateFileError("not a regular file", "not_regular");
|
|
68
|
+
const buffer = Buffer.alloc(maxBytes + 1);
|
|
69
|
+
let length = 0;
|
|
70
|
+
while (length < buffer.length) {
|
|
71
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
|
|
72
|
+
if (bytesRead === 0) break;
|
|
73
|
+
length += bytesRead;
|
|
74
|
+
}
|
|
75
|
+
if (length > maxBytes) throw new PrivateFileError(`larger than ${maxBytes} bytes`, "too_large");
|
|
76
|
+
try {
|
|
77
|
+
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, length));
|
|
78
|
+
} catch {
|
|
79
|
+
throw new PrivateFileError("not valid UTF-8", "not_utf8");
|
|
80
|
+
}
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw failed(error);
|
|
83
|
+
} finally {
|
|
84
|
+
await handle.close().catch(() => undefined);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { raceDeadline } from "../io/deadline";
|
|
2
|
+
|
|
3
|
+
export const TIMED_OUT = Symbol("timed out");
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What `call` gives; `TIMED_OUT` if it takes longer than `milliseconds`; its own error if it fails first. Every call
|
|
7
|
+
* into the daemon API that a request waits for goes through here, so a daemon that stops answering costs a request
|
|
8
|
+
* the bound and not its life. The race keeps a handler on the call, so one that fails after the bound is no
|
|
9
|
+
* unhandled rejection (which would end the plugin's process), and the timer is cleared on every way out.
|
|
10
|
+
*/
|
|
11
|
+
export function within<T>(milliseconds: number, call: () => Promise<T> | T): Promise<T | typeof TIMED_OUT> {
|
|
12
|
+
return raceDeadline(milliseconds, TIMED_OUT, call);
|
|
13
|
+
}
|