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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/OVERVIEW.md +28 -0
  3. package/README.md +105 -2
  4. package/SECURITY.md +84 -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 +178 -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 +150 -0
@@ -0,0 +1,142 @@
1
+ import { toBase64Url, utf8 } from "../shared/bytes";
2
+ import { LIMITS } from "../shared/limits";
3
+ import { sanitizeText } from "../shared/sanitize";
4
+ import { bytesText } from "./text";
5
+
6
+ /**
7
+ * A file the human picked, dropped or pasted: its bytes, as they are, and its name. The name is null for a paste. The
8
+ * bytes are the form's to wipe, when the file leaves its row and when the form closes (`wipeForm`), and they are wiped
9
+ * through `wipeFile` alone. Nothing changes a file but its wipe: what is made of it once (`checkedFile`, `encodedFile`)
10
+ * holds until then.
11
+ */
12
+ export interface FileValue {
13
+ name: string | null;
14
+ bytes: Uint8Array;
15
+ }
16
+
17
+ type Format = "json" | "pem" | "any";
18
+
19
+ /** What the app found of a file, before anything is sealed: it passes, or the one line under its row says why not. */
20
+ export type FileCheck = { ok: true } | { ok: false; message: "Це не JSON" | "Це не PEM" | "Не довше 128 КіБ" };
21
+
22
+ const PASSES: FileCheck = { ok: true };
23
+ /** `LIMITS.fileBytes`, 128 KiB, as the form words it: a literal, so that the type says which line it is. */
24
+ const TOO_LARGE: FileCheck = { ok: false, message: "Не довше 128 КіБ" };
25
+ const NOT_JSON: FileCheck = { ok: false, message: "Це не JSON" };
26
+ const NOT_PEM: FileCheck = { ok: false, message: "Це не PEM" };
27
+
28
+ /** A line of a PEM that opens a block, and one that closes it, ending in CR LF or in LF. */
29
+ const PEM_BEGIN = /^-----BEGIN [^\r\n]+-----\r?$/m;
30
+ const PEM_END = /^-----END [^\r\n]+-----\r?$/m;
31
+
32
+ /**
33
+ * The bytes as text when they are UTF-8, and null when they are not: no character is replaced, and a byte order mark at
34
+ * the start stays the first character. The daemon writes the bytes as they are, BOM and all, and a reader of that file
35
+ * meets the BOM first: a check that dropped it would pass a JSON or a PEM the reader refuses.
36
+ */
37
+ function textOf(bytes: Uint8Array): string | null {
38
+ try {
39
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Whether a file is what its field asks for. The size comes first, for every format: a file over `LIMITS.fileBytes`
47
+ * is refused however it reads. `json` is UTF-8 that parses as JSON; `pem` is UTF-8 with a line that begins a block and
48
+ * one that ends one; `any` is not looked into, so a `.p12` or anything else binary passes. The bytes are only read.
49
+ */
50
+ export function checkFile(file: FileValue, format: Format): FileCheck {
51
+ if (file.bytes.length > LIMITS.fileBytes) return TOO_LARGE;
52
+ if (format === "any") return PASSES;
53
+ const text = textOf(file.bytes);
54
+ if (format === "pem") return text !== null && PEM_BEGIN.test(text) && PEM_END.test(text) ? PASSES : NOT_PEM;
55
+ if (text === null) return NOT_JSON;
56
+ try {
57
+ JSON.parse(text);
58
+ return PASSES;
59
+ } catch {
60
+ return NOT_JSON;
61
+ }
62
+ }
63
+
64
+ /** The most of a file's name that is shown: the longest name a file system gives one. */
65
+ const NAME_MAX = 255;
66
+
67
+ /** «2,1 КіБ»: the size of a file, in bytes below a KiB and in KiB with one decimal above. */
68
+ export function sizeText(bytes: number): string {
69
+ if (bytes < 1024) return bytesText(bytes);
70
+ return `${(bytes / 1024).toFixed(1).replace(".", ",")} КіБ`;
71
+ }
72
+
73
+ /**
74
+ * The line that stands for a file in its row: its name, or «вставлено» for a paste, its size, and for a format that
75
+ * is checked, the check. Never a byte of the file. The name is the human's file system's, and it is shown without what
76
+ * could hide or reorder it, which a name made to deceive could hold.
77
+ */
78
+ export function fileLine(file: FileValue, format: "json" | "pem" | "any", check: FileCheck): string {
79
+ const name = file.name === null ? "вставлено" : sanitizeText(file.name, NAME_MAX);
80
+ const parts = [name, sizeText(file.bytes.length)];
81
+ if (format !== "any") parts.push(`${format} ${check.ok ? "✓" : "✗"}`);
82
+ return parts.filter((part) => part !== "").join(" · ");
83
+ }
84
+
85
+ /** What was pasted into a file row's area, as the file's bytes: nothing pasted is no file, and the row stays empty. */
86
+ export function fromPasted(text: string): FileValue | null {
87
+ return text === "" ? null : { name: null, bytes: utf8.encode(text) };
88
+ }
89
+
90
+ /**
91
+ * What is made of each file the form holds, made once: its check against each format it is held to, and its bytes as
92
+ * base64url, which is how it is sent. Every change of the form checks every row again, so without this every keystroke
93
+ * would read and parse every file anew and make another copy of its content as text. Keyed by the file itself, so that
94
+ * it goes with the file; `wipeFile` lets go of it at once. The text cannot be wiped, as no string can: it is held no
95
+ * longer than the file it was made from, which is no longer than the form.
96
+ */
97
+ const made = new WeakMap<FileValue, { checks: Map<Format, FileCheck>; encoded: string | null }>();
98
+
99
+ function madeOf(file: FileValue): { checks: Map<Format, FileCheck>; encoded: string | null } {
100
+ let entry = made.get(file);
101
+ if (entry === undefined) made.set(file, (entry = { checks: new Map(), encoded: null }));
102
+ return entry;
103
+ }
104
+
105
+ /** `checkFile`, made once for each file and format, and kept until the file is wiped. */
106
+ export function checkedFile(file: FileValue, format: Format): FileCheck {
107
+ const { checks } = madeOf(file);
108
+ let check = checks.get(format);
109
+ if (check === undefined) checks.set(format, (check = checkFile(file, format)));
110
+ return check;
111
+ }
112
+
113
+ /** The bytes of a file as base64url, as a file goes in a submission: made once, and kept until the file is wiped. */
114
+ export function encodedFile(file: FileValue): string {
115
+ const entry = madeOf(file);
116
+ entry.encoded ??= toBase64Url(file.bytes);
117
+ return entry.encoded;
118
+ }
119
+
120
+ /** Wipes a file's bytes, and lets go of what was made of them (`checkedFile`, `encodedFile`): nothing of the file is held after. */
121
+ export function wipeFile(file: FileValue): void {
122
+ file.bytes.fill(0);
123
+ made.delete(file);
124
+ }
125
+
126
+ /**
127
+ * A file the human gave a row, handed to `take` while `open` says the form may take one, and wiped otherwise. What
128
+ * `take` throws on is wiped too, and goes no further: a file that nothing takes leaves nothing behind. The form is open
129
+ * to a file while it is on screen and nothing is under way (the dialog), and a row while it is not locked and still
130
+ * mounted (a file row).
131
+ */
132
+ export function takeFile(file: FileValue, open: boolean, take: (file: FileValue) => void): void {
133
+ if (!open) {
134
+ wipeFile(file);
135
+ return;
136
+ }
137
+ try {
138
+ take(file);
139
+ } catch {
140
+ wipeFile(file);
141
+ }
142
+ }
@@ -0,0 +1,198 @@
1
+ import { utf8Length } from "../shared/bytes";
2
+ import { KEY_PATTERN, LIMITS, RESERVED_KEYS } from "../shared/limits";
3
+ import { MAX_PAYLOAD_BYTES, payloadSize, type PayloadEntry } from "../shared/seal";
4
+ import { hasLoneSurrogate } from "../shared/text";
5
+ import type { RequestView } from "../shared/view";
6
+ import { checkedFile, encodedFile, wipeFile, type FileValue } from "./file-entry";
7
+ import { fieldId } from "./presentation";
8
+
9
+ /** What a row holds: a line of text, or a file, which is null until one is picked, dropped or pasted. */
10
+ export type RowValue = { kind: "text"; text: string } | { kind: "file"; file: FileValue | null };
11
+
12
+ /**
13
+ * One row of the form. A declared row is a field the agent asked for: its key is fixed and it cannot be removed. A row
14
+ * of the human's has the name they type in place of a key. `format` is what a file in the row is checked against; a
15
+ * row of the human's checks none (`any`).
16
+ */
17
+ export interface FormRow {
18
+ id: string;
19
+ key: string;
20
+ declared: boolean;
21
+ optional: boolean;
22
+ format: "json" | "pem" | "any";
23
+ value: RowValue;
24
+ }
25
+
26
+ /** The declared rows first, in the view's order, with ids `fieldId.declared(key)`; then the human's, `fieldId.row(n)`. */
27
+ export interface FormState {
28
+ rows: FormRow[];
29
+ }
30
+
31
+ /** The form for a view: a row for each field the agent asked for, empty. */
32
+ export function formFromView(view: RequestView): FormState {
33
+ return {
34
+ rows: view.fields.map((field) => ({
35
+ id: fieldId.declared(field.key),
36
+ key: field.key,
37
+ declared: true,
38
+ optional: field.optional,
39
+ format: field.format ?? "any",
40
+ value: field.kind === "file" ? { kind: "file", file: null } : { kind: "text", text: "" },
41
+ })),
42
+ };
43
+ }
44
+
45
+ // The lines under a row, as the form words them. A limit a line names is the plugin's own number (`LIMITS`, `MAX_PAYLOAD_BYTES`).
46
+ const INVALID_NAME = "Лише A–Z, 0–9, _";
47
+ const RESERVED_NAME = "Ім'я зарезервоване";
48
+ const TEXT_TOO_LARGE = `Не довше ${LIMITS.valueBytes / 1024} КіБ`;
49
+ const BROKEN_TEXT = "Некоректний символ";
50
+ const TOTAL_TOO_LARGE = `Разом не довше ${MAX_PAYLOAD_BYTES / 1024} КіБ`;
51
+
52
+ /**
53
+ * The key a row's name gives, and the line about it. A declared row's key is the agent's, which the plugin checked. A
54
+ * name of the human's is trimmed, and gives no key while it is empty (and no line), is of another shape than a key, is
55
+ * a name a plain object treats specially, or names a file an earlier row names already, exactly or by letter case: two
56
+ * such keys would be one file on a volume that ignores case. `taken` maps each earlier key, folded, to itself.
57
+ */
58
+ function nameOf(row: FormRow, taken: ReadonlyMap<string, string>): { key: string | null; error: string | null } {
59
+ if (row.declared) return { key: row.key, error: null };
60
+ const key = row.key.trim();
61
+ if (key === "") return { key: null, error: null };
62
+ if (!KEY_PATTERN.test(key)) return { key: null, error: INVALID_NAME };
63
+ if (RESERVED_KEYS.includes(key)) return { key: null, error: RESERVED_NAME };
64
+ const earlier = taken.get(key.toLowerCase());
65
+ return earlier === undefined ? { key, error: null } : { key: null, error: `Вже є ${earlier}` };
66
+ }
67
+
68
+ /**
69
+ * What a row's value comes to: a line, nothing to send (an empty text, no file, a file of no bytes), or an entry, made
70
+ * only when the form is sent. A text is measured without a copy of it being made, and must be whole UTF-8: a surrogate
71
+ * with no partner would be written as another character. A file is checked against its row's format, and encoded, once
72
+ * for as long as the row holds it (`checkedFile`, `encodedFile`).
73
+ */
74
+ function valueOf(row: FormRow): { error: string | null; entry: ((key: string) => PayloadEntry) | null } {
75
+ const { value } = row;
76
+ if (value.kind === "text") {
77
+ const { text } = value;
78
+ if (text === "") return { error: null, entry: null };
79
+ if (utf8Length(text) > LIMITS.valueBytes) return { error: TEXT_TOO_LARGE, entry: null };
80
+ if (hasLoneSurrogate(text)) return { error: BROKEN_TEXT, entry: null };
81
+ return { error: null, entry: (key) => ({ key, value: text }) };
82
+ }
83
+ const { file } = value;
84
+ if (file === null) return { error: null, entry: null };
85
+ const check = checkedFile(file, row.format);
86
+ if (!check.ok) return { error: check.message, entry: null };
87
+ // The plugin gives a key whose file has no bytes no file: such a row is an empty one, here as there.
88
+ if (file.bytes.length === 0) return { error: null, entry: null };
89
+ return { error: null, entry: (key) => ({ key, file: encodedFile(file) }) };
90
+ }
91
+
92
+ /**
93
+ * What the form would send, and what each row and the whole say about it. `entries` is null while «→» is disabled:
94
+ * while a row has a line under it, a field the agent needs is empty, a row of the human's lacks a name or a value, the
95
+ * rows together would not fit one submission (`total`), there are more of them than a request may carry, or nothing
96
+ * would be sent at all. The plugin refuses a submission that writes nothing, and the refusal closes the request.
97
+ *
98
+ * An empty row says nothing: «→» is just disabled. A row has one line, about its name before its value. Messages name
99
+ * keys, never values. Every file goes as `{ key, file }`, its bytes as base64url.
100
+ */
101
+ export function checkForm(form: FormState): { entries: PayloadEntry[] | null; errors: ReadonlyMap<string, string>; total: string | null } {
102
+ const errors = new Map<string, string>();
103
+ const taken = new Map<string, string>();
104
+ const ready: Array<() => PayloadEntry> = [];
105
+ let complete = true;
106
+ for (const row of form.rows) {
107
+ const name = nameOf(row, taken);
108
+ const { key } = name;
109
+ if (key !== null && !taken.has(key.toLowerCase())) taken.set(key.toLowerCase(), key);
110
+ const value = valueOf(row);
111
+ const error = name.error ?? value.error;
112
+ if (error !== null) {
113
+ errors.set(row.id, error);
114
+ complete = false;
115
+ } else if (value.entry === null) {
116
+ // Nothing in the row. A field the agent made optional is left out; every other row is waited for.
117
+ if (!(row.declared && row.optional)) complete = false;
118
+ } else if (key === null) {
119
+ complete = false;
120
+ } else {
121
+ const entry = value.entry;
122
+ ready.push(() => entry(key));
123
+ }
124
+ }
125
+ if (!complete) return { entries: null, errors, total: null };
126
+ const entries = ready.map((make) => make());
127
+ if (payloadSize(entries) > MAX_PAYLOAD_BYTES) return { entries: null, errors, total: TOTAL_TOO_LARGE };
128
+ if (entries.length === 0 || entries.length > LIMITS.fields) return { entries: null, errors, total: null };
129
+ return { entries, errors, total: null };
130
+ }
131
+
132
+ /** Fills every file's bytes the form holds with zeros, and lets go of what was made of them (`wipeFile`). */
133
+ export function wipeForm(form: FormState): void {
134
+ for (const row of form.rows) wipeRow(row);
135
+ }
136
+
137
+ function wipeRow(row: FormRow): void {
138
+ if (row.value.kind === "file" && row.value.file !== null) wipeFile(row.value.file);
139
+ }
140
+
141
+ /** The form with one row changed, or the very form it was given when `change` leaves the row as it was or there is no such row. */
142
+ function changed(form: FormState, id: string, change: (row: FormRow) => FormRow): FormState {
143
+ const index = form.rows.findIndex((row) => row.id === id);
144
+ const row = form.rows[index];
145
+ if (row === undefined) return form;
146
+ const next = change(row);
147
+ if (next === row) return form;
148
+ return { rows: form.rows.map((other, at) => (at === index ? next : other)) };
149
+ }
150
+
151
+ /** What was typed into a text row. A file row has no text. */
152
+ export function setText(form: FormState, id: string, text: string): FormState {
153
+ return changed(form, id, (row) => (row.value.kind === "text" ? { ...row, value: { kind: "text", text } } : row));
154
+ }
155
+
156
+ /** The name of a row of the human's. A field the agent asked for keeps its key. */
157
+ export function setName(form: FormState, id: string, key: string): FormState {
158
+ return changed(form, id, (row) => (row.declared ? row : { ...row, key }));
159
+ }
160
+
161
+ /** «+»: a row of the human's, numbered `n`, a text with no name. None past the most a request may carry, and none under an id that is taken. */
162
+ export function addRow(form: FormState, n: number): FormState {
163
+ const id = fieldId.row(n);
164
+ if (form.rows.length >= LIMITS.fields || form.rows.some((row) => row.id === id)) return form;
165
+ return { rows: [...form.rows, { id, key: "", declared: false, optional: false, format: "any", value: { kind: "text", text: "" } }] };
166
+ }
167
+
168
+ /** «✕» on a row of the human's: it goes, and its file is wiped. A field the agent asked for stays. */
169
+ export function removeRow(form: FormState, id: string): FormState {
170
+ const row = form.rows.find((candidate) => candidate.id === id);
171
+ if (row === undefined || row.declared) return form;
172
+ wipeRow(row);
173
+ return { rows: form.rows.filter((other) => other !== row) };
174
+ }
175
+
176
+ /** The paperclip on a text row of the human's: it becomes an empty file row, whose file no format is checked against. */
177
+ export function toFileRow(form: FormState, id: string): FormState {
178
+ return changed(form, id, (row) => (row.declared || row.value.kind !== "text" ? row : { ...row, format: "any", value: { kind: "file", file: null } }));
179
+ }
180
+
181
+ /**
182
+ * A file picked, dropped or pasted into a row. Only an empty file row takes one: a row that holds a file takes no
183
+ * other until that one is taken out, and a file nothing takes is wiped here, so that no copy of it is left behind.
184
+ */
185
+ export function fillFile(form: FormState, id: string, file: FileValue): FormState {
186
+ const next = changed(form, id, (row) => (row.value.kind === "file" && row.value.file === null ? { ...row, value: { kind: "file", file } } : row));
187
+ if (next === form) wipeFile(file);
188
+ return next;
189
+ }
190
+
191
+ /** «✕» on a file: it is wiped and taken out of its row, which is empty again. */
192
+ export function clearFile(form: FormState, id: string): FormState {
193
+ return changed(form, id, (row) => {
194
+ if (row.value.kind !== "file" || row.value.file === null) return row;
195
+ wipeFile(row.value.file);
196
+ return { ...row, value: { kind: "file", file: null } };
197
+ });
198
+ }
@@ -0,0 +1,19 @@
1
+ // What the plugin needs from the host it runs in, and no promise that every host has it. The client project is checked
2
+ // without Node's types and without the DOM library, so the compiler is told about exactly the three globals that
3
+ // `shared/bytes.ts` uses. Whether they are there depends on the app that loads this code (Hermes on a phone, a browser
4
+ // engine on the desktop and the web): `crypto.getRandomValues` in particular is the host app's to provide.
5
+ //
6
+ // Its absence fails closed. Without it no key pair and no nonce can be drawn, `seal` throws `SealError("sealing failed")`,
7
+ // the form sends nothing and asks for «→» again, and the self-test on the settings screen reports that the app could
8
+ // not seal. There is no fallback to another source of randomness and none to plaintext.
9
+ declare class TextEncoder {
10
+ encode(input?: string): Uint8Array;
11
+ }
12
+
13
+ declare class TextDecoder {
14
+ /** `ignoreBOM`: a byte order mark at the start is kept as the character U+FEFF, and not taken away (`client/file-entry.ts`). */
15
+ constructor(label?: string, options?: { fatal?: boolean; ignoreBOM?: boolean });
16
+ decode(input?: Uint8Array): string;
17
+ }
18
+
19
+ declare var crypto: { getRandomValues<T extends Uint8Array>(array: T): T };
@@ -0,0 +1,96 @@
1
+ import type { ErrorCode } from "../shared/errors";
2
+ import type { RequestState } from "../shared/request";
3
+
4
+ /**
5
+ * What the daemon answers to a submission, as the fulfil contract (`shared/contracts.ts`) declares it. Written out
6
+ * here so that this module needs no SDK: the form hands the RPC's answer in, and the compiler holds the two together.
7
+ */
8
+ export type FulfillResult =
9
+ | { ok: true; state: RequestState }
10
+ | { ok: false; code: ErrorCode; retryable: boolean; detail?: string };
11
+
12
+ /** The line at the top of the form when the plugin did not take what was sent, but the request may still be open. */
13
+ export const UNAVAILABLE = "Плагін зараз недоступний. Натисни «→» ще раз.";
14
+
15
+ /** The line at the top of the form when the request is closed: what was typed stays, and «→» is disabled. */
16
+ export const CLOSED = "Запит уже закрито.";
17
+
18
+ /**
19
+ * A plain description of what the form does next. The component does exactly this and decides nothing. Every flag is
20
+ * false and the line null unless the row says otherwise.
21
+ */
22
+ export interface Next {
23
+ /** The one line at the top of the form, or none. Nothing the plugin said besides its code is ever in it. */
24
+ top: string | null;
25
+ /** The form closes. */
26
+ close: boolean;
27
+ /** The request is closed on the plugin's side: «→» is disabled from now on, and what was typed stays. */
28
+ closed: boolean;
29
+ /** What was typed is thrown away and every file wiped. False means it stays for the next try. */
30
+ clearForm: boolean;
31
+ /** The sealed envelope kept for a resend is thrown away. */
32
+ dropEnvelope: boolean;
33
+ /**
34
+ * An answer came, and it does not say what became of the submission: the plugin may have taken it. The envelope is
35
+ * kept as one whose outcome is not known, exactly as after a call whose reply never came, so that other values are
36
+ * not sealed and sent before the request has been read again.
37
+ */
38
+ outcomeUnknown: boolean;
39
+ }
40
+
41
+ const STAY: Next = { top: null, close: false, closed: false, clearForm: false, dropEnvelope: false, outcomeUnknown: false };
42
+
43
+ const unavailable = (): Next => ({ ...STAY, top: UNAVAILABLE });
44
+
45
+ /** The request is closed: what was typed stays on screen, «→» is disabled, and the envelope is of no use any more. */
46
+ const closedNow = (): Next => ({ ...STAY, top: CLOSED, closed: true, dropEnvelope: true });
47
+
48
+ /**
49
+ * The plugin answered. A submission it took closes the form, which wipes what it held; there is no toast and no
50
+ * screen of success, and the pill turns green. A refusal that closed the request is the closed line, whatever its
51
+ * code; one that left it open is the line that asks for «→» again, and keeps the envelope for that, unless the
52
+ * envelope may be the trouble (`decrypt_failed`, after which the next press seals anew) or what became of it is not
53
+ * known (`service_unavailable`, the handler's fixed answer).
54
+ */
55
+ export function afterFulfill(result: FulfillResult): Next {
56
+ if (result.ok) return { ...STAY, close: true, clearForm: true, dropEnvelope: true };
57
+ if (!result.retryable) return closedNow();
58
+ switch (result.code) {
59
+ case "decrypt_failed":
60
+ return { ...unavailable(), dropEnvelope: true };
61
+ case "service_unavailable":
62
+ return { ...unavailable(), outcomeUnknown: true };
63
+ default:
64
+ return unavailable();
65
+ }
66
+ }
67
+
68
+ /** The call failed or timed out. Whether the plugin got the envelope is not known, so the same envelope is what goes next. */
69
+ export function afterLostReply(): Next {
70
+ return unavailable();
71
+ }
72
+
73
+ /** Sealing failed in the app, before anything was sent. */
74
+ export function afterSealFailure(): Next {
75
+ return unavailable();
76
+ }
77
+
78
+ /** The request had to be read again before new values were sealed, and could not be: none were sent. */
79
+ export function afterCheckFailed(): Next {
80
+ return unavailable();
81
+ }
82
+
83
+ /** A view of another request than the one the form was opened for, held or read. Nothing is sent. */
84
+ export function afterMismatch(): Next {
85
+ return unavailable();
86
+ }
87
+
88
+ /** A reading found the request closed: nothing new goes out, and the envelope is of no use any more. */
89
+ export function afterReadClosed(): Next {
90
+ return closedNow();
91
+ }
92
+
93
+ /** «✕» declined the request, and the form closes; when the decline failed, the form stays and asks to try again. */
94
+ export function afterDecline(succeeded: boolean): Next {
95
+ return succeeded ? { ...STAY, close: true, clearForm: true, dropEnvelope: true } : unavailable();
96
+ }
@@ -0,0 +1,114 @@
1
+ import type { CardData } from "../shared/card";
2
+ import type { RequestView } from "../shared/view";
3
+ import { plural } from "./text";
4
+ import type { Tone } from "./tone";
5
+
6
+ /** What the form says of how the values travel: the cipher `shared/seal.ts` really uses, and nothing else. */
7
+ export const FORM_BADGE = "X25519 · ChaCha20-Poly1305";
8
+
9
+ /** The form's title: one key on screen, or several. */
10
+ export function formTitle(rowsOnScreen: number): string {
11
+ return rowsOnScreen > 1 ? "Секрети для агента" : "Секрет для агента";
12
+ }
13
+
14
+ /** What a screen reader says of each control that has an icon and no words, and of each input that shows no name of its own. */
15
+ export const A11Y: Readonly<
16
+ Record<"enter" | "decline" | "add" | "remove" | "show" | "hide" | "submit" | "pick" | "paste" | "removeFile" | "name" | "pasteArea", string>
17
+ > = {
18
+ enter: "Ввести значення",
19
+ decline: "Відхилити запит",
20
+ add: "Додати ключ",
21
+ remove: "Прибрати ключ",
22
+ show: "Показати значення",
23
+ hide: "Сховати значення",
24
+ submit: "Передати",
25
+ pick: "Вибрати файл",
26
+ paste: "Вставити з буфера",
27
+ removeFile: "Прибрати файл",
28
+ name: "Назва ключа",
29
+ pasteArea: "Вміст файлу",
30
+ };
31
+
32
+ /** What the name input of a row of the human's shows while it is empty: the form a key has. */
33
+ export const KEY_PLACEHOLDER = "KEY_NAME";
34
+
35
+ /** The eye of a text row: what it shows, and what pressing it will do. */
36
+ export function eye(shown: boolean): { icon: "Eye" | "EyeOff"; label: string } {
37
+ return shown ? { icon: "EyeOff", label: A11Y.hide } : { icon: "Eye", label: A11Y.show };
38
+ }
39
+
40
+ /** The pill in the chat. Its look comes from the card's data alone, and nothing in it changes its height. */
41
+ export interface Pill {
42
+ tone: "accent" | "success" | "muted" | "dim" | "danger";
43
+ icon: "Shield" | "ShieldCheck" | "ShieldX" | "ShieldAlert";
44
+ title: string;
45
+ detail: string;
46
+ struck: boolean;
47
+ pressable: boolean;
48
+ }
49
+
50
+ /** The height of the pill, in every state. The chat's list does not take a row whose height changes (getpaseo/paseo#7486). */
51
+ export const PILL_HEIGHT = 36;
52
+
53
+ /** The word for each way a request ends without its values. All of them are drawn the same way: dimmed and struck through. */
54
+ const ENDED_AS: Readonly<Record<"declined" | "cancelled" | "expired" | "rejected", string>> = {
55
+ declined: "Відхилено",
56
+ cancelled: "Скасовано",
57
+ expired: "Час минув",
58
+ rejected: "Не прийнято",
59
+ };
60
+
61
+ /**
62
+ * How a request looks as a pill in each state it can be in. Only a request that waits can be pressed, and not once a
63
+ * second, different submission has come: that one is red in every state. A waiting request names its one key, or counts
64
+ * several; every other state counts them.
65
+ */
66
+ export function pill(data: Pick<CardData, "state" | "tamper" | "keys">): Pill {
67
+ const count = plural(data.keys.length, "ключ", "ключі", "ключів");
68
+ if (data.tamper) return { tone: "danger", icon: "ShieldAlert", title: "Підозріле подання", detail: count, struck: false, pressable: false };
69
+ switch (data.state) {
70
+ case "pending":
71
+ return data.keys.length > 1
72
+ ? { tone: "accent", icon: "Shield", title: "Секрети для агента", detail: count, struck: false, pressable: true }
73
+ : { tone: "accent", icon: "Shield", title: "Секрет для агента", detail: data.keys[0] ?? "", struck: false, pressable: true };
74
+ case "delivered":
75
+ return { tone: "success", icon: "ShieldCheck", title: "Передано", detail: count, struck: false, pressable: false };
76
+ case "released":
77
+ return { tone: "muted", icon: "ShieldCheck", title: "Передано", detail: count, struck: false, pressable: false };
78
+ default:
79
+ return { tone: "dim", icon: "ShieldX", title: ENDED_AS[data.state], detail: count, struck: true, pressable: false };
80
+ }
81
+ }
82
+
83
+ /** The colour a pill is drawn in, from the theme: `dim` is the muted colour, fainter. */
84
+ export function pillColor(tone: Pill["tone"], colors: Tone): { color: string; opacity: number } {
85
+ switch (tone) {
86
+ case "accent":
87
+ return { color: colors.accent, opacity: 1 };
88
+ case "success":
89
+ return { color: colors.success, opacity: 1 };
90
+ case "danger":
91
+ return { color: colors.danger, opacity: 1 };
92
+ case "dim":
93
+ return { color: colors.muted, opacity: 0.6 };
94
+ default:
95
+ return { color: colors.muted, opacity: 1 };
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Which screen the form is on: waiting for its first reading, unable to read the request, or the form. Once a view is
101
+ * held the form stays: a request that no longer waits keeps what was typed, with «→» disabled.
102
+ */
103
+ export type Screen = "loading" | "failed" | "form";
104
+
105
+ export function dialogScreen(state: { view: RequestView | null; loadFailed: boolean }): Screen {
106
+ if (state.view !== null) return "form";
107
+ return state.loadFailed ? "failed" : "loading";
108
+ }
109
+
110
+ /** The id a row of the form goes by: a declared field by its key, a row of the human's by its number. The prefix keeps a key like `constructor` a plain name. */
111
+ export const fieldId = {
112
+ declared: (key: string): string => `field:${key}`,
113
+ row: (n: number): string => `row:${n}`,
114
+ };
@@ -0,0 +1,27 @@
1
+ import { fromBase64Url } from "../shared/bytes";
2
+ import { buildAad, encodeValues, seal, type PayloadEntry, type SealedEnvelope } from "../shared/seal";
3
+ import type { RequestView } from "../shared/view";
4
+
5
+ /**
6
+ * Seals the entries to the request's one-time key, bound to this request and to the digest of what it asked for. This
7
+ * is the last place the values exist outside component state: what leaves is ciphertext. The bytes of the encoded
8
+ * values are wiped as soon as they are sealed, whatever happens (the strings in the form cannot be wiped; they die with
9
+ * the form, and its files' bytes are wiped when it closes). `null` when sealing is not possible, with nothing about
10
+ * why: a library message is not ours to show, and none can hold a value. The encoder is a parameter so that a test can
11
+ * look at the buffer it made.
12
+ */
13
+ export function sealEntries(
14
+ view: Pick<RequestView, "id" | "publicKey" | "requestDigest">,
15
+ entries: readonly PayloadEntry[],
16
+ encode: (entries: readonly PayloadEntry[]) => Uint8Array = encodeValues,
17
+ ): SealedEnvelope | null {
18
+ let plaintext: Uint8Array | undefined;
19
+ try {
20
+ plaintext = encode(entries);
21
+ return seal(fromBase64Url(view.publicKey), plaintext, buildAad(view.id, view.requestDigest));
22
+ } catch {
23
+ return null;
24
+ } finally {
25
+ plaintext?.fill(0);
26
+ }
27
+ }