paseo-plugin-secure-input 0.0.0-stage → 0.2.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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/OVERVIEW.md +30 -0
  3. package/README.md +252 -2
  4. package/SECURITY.md +79 -0
  5. package/assets/icon.png +0 -0
  6. package/client/card.tsx +74 -0
  7. package/client/codes.ts +32 -0
  8. package/client/diagnostics-rows.ts +139 -0
  9. package/client/dialog-state.ts +59 -0
  10. package/client/dialog.tsx +292 -0
  11. package/client/envelope-cache.ts +85 -0
  12. package/client/fields.tsx +255 -0
  13. package/client/file-entry.ts +142 -0
  14. package/client/form-state.ts +198 -0
  15. package/client/globals.d.ts +19 -0
  16. package/client/outcome.ts +96 -0
  17. package/client/presentation.ts +114 -0
  18. package/client/sealing.ts +27 -0
  19. package/client/self-test.ts +96 -0
  20. package/client/settings.tsx +160 -0
  21. package/client/submit.ts +92 -0
  22. package/client/text.ts +47 -0
  23. package/client/tone.ts +36 -0
  24. package/client/web.ts +184 -0
  25. package/index.client.tsx +29 -0
  26. package/index.server.ts +6 -0
  27. package/npm-shrinkwrap.json +60 -0
  28. package/package.json +68 -4
  29. package/paseo-plugin.json +6 -0
  30. package/server/core/continuation.ts +151 -0
  31. package/server/core/entries.ts +89 -0
  32. package/server/core/outbox.ts +555 -0
  33. package/server/core/registry-store.ts +185 -0
  34. package/server/core/registry.ts +1031 -0
  35. package/server/core/selftest.ts +60 -0
  36. package/server/core/view.ts +38 -0
  37. package/server/io/atomic.ts +119 -0
  38. package/server/io/deadline.ts +28 -0
  39. package/server/io/descriptor.ts +36 -0
  40. package/server/io/directory.ts +40 -0
  41. package/server/io/drop.ts +434 -0
  42. package/server/io/legacy-shim.ts +108 -0
  43. package/server/io/ownership.ts +8 -0
  44. package/server/io/private-file.ts +86 -0
  45. package/server/paseo/bounded.ts +13 -0
  46. package/server/paseo/handlers.ts +124 -0
  47. package/server/paseo/hooks.ts +106 -0
  48. package/server/paseo/plugin.ts +341 -0
  49. package/server/paseo/runtime.ts +409 -0
  50. package/server/paseo/tools.ts +180 -0
  51. package/shared/bytes.ts +100 -0
  52. package/shared/canonical.ts +32 -0
  53. package/shared/card.ts +41 -0
  54. package/shared/contracts.ts +128 -0
  55. package/shared/errors.ts +48 -0
  56. package/shared/limits.ts +118 -0
  57. package/shared/request-id.ts +9 -0
  58. package/shared/request.ts +66 -0
  59. package/shared/sanitize.ts +101 -0
  60. package/shared/seal.ts +292 -0
  61. package/shared/shown.ts +12 -0
  62. package/shared/text.ts +39 -0
  63. package/shared/view.ts +42 -0
  64. package/skills/secure-input/SKILL.md +148 -0
@@ -0,0 +1,60 @@
1
+ import { randomBytes, toBase64Url, toHex } from "../../shared/bytes";
2
+ import { SecureInputError } from "../../shared/errors";
3
+ import { buildAad, digestHex, generateRequestKeyPair, open, type RequestKeyPair, type SealedEnvelope } from "../../shared/seal";
4
+
5
+ const probes = new Map<string, Uint8Array>();
6
+ const MAX_PROBES = 16;
7
+ /** What a self-test that cannot begin is refused with: the host gave no randomness for the probe's id or its key. Never the platform's own words. */
8
+ const CANNOT_START = "the self-test cannot be started";
9
+
10
+ /**
11
+ * A throwaway key the app seals to. Proves the client bundle can run the same construction as the server.
12
+ *
13
+ * The id is drawn before the key is made, so that randomness which gives out between the two leaves no secret key
14
+ * that nobody holds (a key pair that fails while it is derived wipes its own: `generateRequestKeyPair`), and nothing
15
+ * can fail between making the key and keeping it. A host that gives no randomness is answered with a fixed refusal.
16
+ */
17
+ export function beginSelfTest(): { probeId: string; publicKey: string } {
18
+ let probeId: string;
19
+ let keys: RequestKeyPair;
20
+ try {
21
+ probeId = `p_${toHex(randomBytes(8))}`;
22
+ keys = generateRequestKeyPair();
23
+ } catch {
24
+ throw new SecureInputError("service_unavailable", CANNOT_START);
25
+ }
26
+ probes.set(probeId, keys.secretKey);
27
+ if (probes.size > MAX_PROBES) {
28
+ const oldest = probes.keys().next().value as string;
29
+ probes.get(oldest)?.fill(0);
30
+ probes.delete(oldest);
31
+ }
32
+ return { probeId, publicKey: toBase64Url(keys.publicKey) };
33
+ }
34
+
35
+ /** Wipes and forgets every open probe. Called when the plugin is disposed. */
36
+ export function clearSelfTests(): void {
37
+ for (const secretKey of probes.values()) secretKey.fill(0);
38
+ probes.clear();
39
+ }
40
+
41
+ /**
42
+ * Opens what the app sealed to the probe's key and compares its digest. The payload is dummy data, and it is wiped
43
+ * like a real one all the same, once it has been hashed: the self-test takes the path a value takes, to its end. The
44
+ * opener is a parameter so that a test can look at the buffer it gave back.
45
+ */
46
+ export function finishSelfTest(probeId: string, envelope: SealedEnvelope, digest: string, unseal: typeof open = open): { ok: boolean; bytes: number } {
47
+ const secretKey = probes.get(probeId);
48
+ probes.delete(probeId);
49
+ if (!secretKey) return { ok: false, bytes: 0 };
50
+ let plaintext: Uint8Array | undefined;
51
+ try {
52
+ plaintext = unseal(secretKey, envelope, buildAad(probeId, "selftest"));
53
+ return { ok: digestHex(plaintext) === digest, bytes: plaintext.length };
54
+ } catch {
55
+ return { ok: false, bytes: 0 };
56
+ } finally {
57
+ secretKey.fill(0);
58
+ plaintext?.fill(0);
59
+ }
60
+ }
@@ -0,0 +1,38 @@
1
+ import { SecureInputError } from "../../shared/errors";
2
+ import { LIMITS } from "../../shared/request";
3
+ import { sanitizeText } from "../../shared/sanitize";
4
+ import type { RequestView } from "../../shared/view";
5
+ import type { Registry, RequestRecord } from "./registry";
6
+
7
+ /** Assembles what the form is given of a request. Agent-supplied text is scrubbed here, on the daemon, before it leaves. */
8
+ export function buildView(registry: Pick<Registry, "get">, requestId: string): RequestView {
9
+ const record = registry.get(requestId);
10
+ if (record === undefined) throw new SecureInputError("invalid_request", "unknown request");
11
+ return composeView(record);
12
+ }
13
+
14
+ /**
15
+ * The view of a request, from its record. Pure, so that the registry can build the view of a request it is about to
16
+ * create and refuse the creation if that view is one the form's contract would not take.
17
+ *
18
+ * Of what the agent wrote, only the labels go, scrubbed: a screen reader reads them. A field that names no kind is a
19
+ * text field, and a file field that names no format is checked as `any`.
20
+ */
21
+ export function composeView(record: RequestRecord): RequestView {
22
+ return {
23
+ id: record.id,
24
+ state: record.state,
25
+ tamper: record.tamper,
26
+ errorCode: record.errorCode,
27
+ fields: record.request.fields.map((field) => ({
28
+ key: field.key,
29
+ label: sanitizeText(field.label ?? "", LIMITS.label),
30
+ optional: field.optional === true,
31
+ kind: field.kind ?? "text",
32
+ format: field.kind === "file" ? (field.format ?? "any") : null,
33
+ })),
34
+ publicKey: record.publicKey,
35
+ requestDigest: record.requestDigest,
36
+ createdAt: record.createdAt,
37
+ };
38
+ }
@@ -0,0 +1,119 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { constants, type BigIntStats } from "node:fs";
3
+ import { lstat, mkdir, open, rename, unlink, type FileHandle } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { SecureInputError } from "../../shared/errors";
6
+ import { errnoToken, withHandle } from "./descriptor";
7
+
8
+ /** The one error this module raises for anything that went wrong on disk. The detail is an errno name or nothing. */
9
+ function failed(error: unknown): SecureInputError {
10
+ if (error instanceof SecureInputError) return error;
11
+ return new SecureInputError("write_failed", errnoToken(error));
12
+ }
13
+
14
+ /**
15
+ * The error says no file is at this path: no entry of that name (ENOENT), a
16
+ * parent that is no directory (ENOTDIR), or a name too long to exist on the
17
+ * volume (ENAMETOOLONG). A file can still appear there later; this is only
18
+ * what was seen.
19
+ */
20
+ function isAbsent(error: unknown): boolean {
21
+ const code = errnoToken(error);
22
+ return code === "ENOENT" || code === "ENOTDIR" || code === "ENAMETOOLONG";
23
+ }
24
+
25
+ /** `unlink` never removes a directory and never follows a link. Never throws, so clean-up cannot replace the outcome of a write. */
26
+ async function unlinkFile(path: string): Promise<"removed" | "absent" | "stuck"> {
27
+ try {
28
+ await unlink(path);
29
+ return "removed";
30
+ } catch (error) {
31
+ return isAbsent(error) ? "absent" : "stuck";
32
+ }
33
+ }
34
+
35
+ /**
36
+ * The rule behind every clean-up: a temporary name is ours only while it refers
37
+ * to the file this call created (`dev` and `ino` of the handle it opened).
38
+ * Absent is gone. The same file is unlinked. Another file is a stranger's: it is
39
+ * left alone, whatever the name. A name that cannot be looked at is stuck.
40
+ */
41
+ async function removeIfOurs(path: string, dev: bigint, ino: bigint): Promise<"gone" | "foreign" | "stuck"> {
42
+ let info: BigIntStats;
43
+ try {
44
+ info = await lstat(path, { bigint: true });
45
+ } catch (error) {
46
+ return isAbsent(error) ? "gone" : "stuck";
47
+ }
48
+ if (info.dev !== dev || info.ino !== ino) return "foreign";
49
+ return (await unlinkFile(path)) === "stuck" ? "stuck" : "gone";
50
+ }
51
+
52
+ /** A failure here means this call created nothing, so whatever is at `path` is not ours to remove. */
53
+ function createExclusive(path: string, mode: number): Promise<FileHandle> {
54
+ return open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
55
+ }
56
+
57
+ /**
58
+ * Writes, flushes and closes. Of two failures the first is the one that comes out (a full disk, not what the close
59
+ * said after it), and a close that fails after a write that worked is a failure too: see `withHandle`.
60
+ */
61
+ function fill(handle: FileHandle, content: string): Promise<void> {
62
+ return withHandle(handle, async () => {
63
+ await handle.writeFile(content);
64
+ await handle.sync();
65
+ });
66
+ }
67
+
68
+ /**
69
+ * The question a step of the plugin's start-up asks right before each thing it does to a path the plugin shares with
70
+ * whichever plugin is started after it on the same data directory: what is in `drop/`, the stub and the shim. The
71
+ * answer is no once the plugin the step belongs to is being stopped (for the sweep and the load, which are let finish
72
+ * within the wait of the stop: once that wait is over). By then those paths may be the next plugin's, and the step does
73
+ * not do the thing. It is asked with nothing awaited between the answer and the call that does the thing, so all that is
74
+ * left between the two is that one call.
75
+ */
76
+ export type StillWanted = () => boolean;
77
+
78
+ /** Atomic replace for the plugin's own state files. These never hold a typed value. */
79
+ export async function writePrivateFile(path: string, content: string, mode = 0o600): Promise<void> {
80
+ await writePrivateFileIf(path, content, mode, () => true);
81
+ }
82
+
83
+ /**
84
+ * `writePrivateFile` for a step of the start-up. `stillWanted` is asked twice. First before anything is made: on "no"
85
+ * nothing is written at all, not the directory and not a temporary file. Then when the new content is whole under its
86
+ * temporary name, right before the `rename` that puts it at `path`: on "no" the rename is not made and the temporary
87
+ * file is removed as after a failed write. Either way the answer is `false` and `path` is as it was; `true` when the
88
+ * file was written. A write that fails before its content is staged does not ask the second time.
89
+ */
90
+ export async function writePrivateFileIf(path: string, content: string, mode: number, stillWanted: StillWanted): Promise<boolean> {
91
+ try {
92
+ if (!stillWanted()) return false;
93
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
94
+ const temp = `${path}.${randomBytes(8).toString("hex")}.tmp`;
95
+ const handle = await createExclusive(temp, mode);
96
+ let identity: { dev: bigint; ino: bigint };
97
+ try {
98
+ const { dev, ino } = await handle.stat({ bigint: true });
99
+ identity = { dev, ino };
100
+ } catch (error) {
101
+ await handle.close().catch(() => undefined);
102
+ throw error;
103
+ }
104
+ try {
105
+ await fill(handle, content);
106
+ if (stillWanted()) {
107
+ await rename(temp, path);
108
+ return true;
109
+ }
110
+ } catch (error) {
111
+ await removeIfOurs(temp, identity.dev, identity.ino);
112
+ throw error;
113
+ }
114
+ await removeIfOurs(temp, identity.dev, identity.ino);
115
+ return false;
116
+ } catch (error) {
117
+ throw failed(error);
118
+ }
119
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * What `call` gives, or `expired` if `milliseconds` pass first, or if the caller gives up sooner by the function it is
3
+ * handed through `onAbandon` (a stop, the end of a budget: it settles the race with `expired` as the clock would). If
4
+ * `call` fails first, its own error. A result or an error that comes later is ignored, and it is not an unhandled
5
+ * rejection either: the handlers stay on the call. The timer is cleared on every way out, and nothing here knows of
6
+ * the daemon's API or of any SDK, so the plugin's core can bound its calls with it too.
7
+ *
8
+ * Each caller says what "expired" is in its own value (`TIMED_OUT` in `server/paseo/bounded.ts`, `UNSETTLED` of the
9
+ * outbox) and keeps what a time-out means to it.
10
+ */
11
+ export async function raceDeadline<T, Expired>(
12
+ milliseconds: number,
13
+ expired: Expired,
14
+ call: () => Promise<T> | T,
15
+ onAbandon?: (abandon: () => void) => void,
16
+ ): Promise<T | Expired> {
17
+ let timer: NodeJS.Timeout | undefined;
18
+ try {
19
+ return await new Promise<T | Expired>((resolve, reject) => {
20
+ timer = setTimeout(() => resolve(expired), milliseconds);
21
+ onAbandon?.(() => resolve(expired));
22
+ // A call that throws before it returns a promise is a rejection of the race, as one that fails later is.
23
+ Promise.resolve(call()).then(resolve, reject);
24
+ });
25
+ } finally {
26
+ clearTimeout(timer);
27
+ }
28
+ }
@@ -0,0 +1,36 @@
1
+ import type { FileHandle } from "node:fs/promises";
2
+
3
+ /** How a file is opened. The modules that take one use `open` of `node:fs/promises`; a test hands in one whose handle fails. */
4
+ export type OpenFile = (path: string, flags: number, mode?: number) => Promise<FileHandle>;
5
+
6
+ /** What may stand in an error as the reason: an errno name such as `ENOSPC`, never text a library wrote. */
7
+ const ERRNO_CODE = /^[A-Z][A-Z0-9_]{1,31}$/;
8
+
9
+ /** The errno name of a failure of the disk, or undefined when the error has none that may be shown. */
10
+ export function errnoToken(error: unknown): string | undefined {
11
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
12
+ return typeof code === "string" && ERRNO_CODE.test(code) ? code : undefined;
13
+ }
14
+
15
+ /**
16
+ * The lifetime of one descriptor: `use` works on the handle, and the handle is closed on every way out, with the
17
+ * close waited for.
18
+ *
19
+ * The first failure is the one that is reported. When `use` fails, what the close then says is dropped: it came
20
+ * second, and the reason a write or a read did not work (a full disk, a failing one) is the one worth telling. When
21
+ * `use` succeeds, a close that fails is the failure: for a file that was written, the close is where a filesystem
22
+ * may still say that the bytes did not arrive, and a write is not reported as done over that.
23
+ *
24
+ * Errors come out as they were raised; the caller turns them into the plugin's own.
25
+ */
26
+ export async function withHandle<T>(handle: FileHandle, use: (handle: FileHandle) => Promise<T>): Promise<T> {
27
+ let result: T;
28
+ try {
29
+ result = await use(handle);
30
+ } catch (error) {
31
+ await handle.close().catch(() => undefined);
32
+ throw error;
33
+ }
34
+ await handle.close();
35
+ return result;
36
+ }
@@ -0,0 +1,40 @@
1
+ import { constants } from "node:fs";
2
+ import { mkdir, open, type FileHandle } from "node:fs/promises";
3
+ import { SecureInputError } from "../../shared/errors";
4
+ import { uid } from "./ownership";
5
+
6
+ function unavailable(detail: string): SecureInputError {
7
+ return new SecureInputError("service_unavailable", detail);
8
+ }
9
+
10
+ /**
11
+ * The directory must be a real directory (never a link) of this user, held at
12
+ * 0700. `mkdir` does nothing to one that exists, so this looks at it through a
13
+ * handle opened without following links, and only as a directory: the owner
14
+ * check and the chmod then concern the one inode that was opened. `what` names
15
+ * the directory in the refusal ("data", "drop", "bridge"); it is always one
16
+ * of our own words, never a caller's text.
17
+ */
18
+ export async function holdDirectory(directory: string, what: string): Promise<void> {
19
+ try {
20
+ await mkdir(directory, { recursive: true, mode: 0o700 });
21
+ } catch {
22
+ throw unavailable(`the ${what} directory cannot be created`);
23
+ }
24
+ const unsafe = (): SecureInputError => unavailable(`the ${what} directory is not a private directory of this user`);
25
+ let handle: FileHandle;
26
+ try {
27
+ handle = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
28
+ } catch {
29
+ throw unsafe();
30
+ }
31
+ try {
32
+ const stats = await handle.stat();
33
+ if (stats.uid !== uid()) throw unsafe();
34
+ if ((stats.mode & 0o7777) !== 0o700) await handle.chmod(0o700);
35
+ } catch (error) {
36
+ throw error instanceof SecureInputError ? error : unsafe();
37
+ } finally {
38
+ await handle.close().catch(() => undefined);
39
+ }
40
+ }