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,139 @@
1
+ import type { Diagnostics } from "../shared/contracts";
2
+ import { ERROR_CODES, type ErrorCode } from "../shared/errors";
3
+ import { describeCode } from "./codes";
4
+ import type { Tone } from "./tone";
5
+
6
+ /** What the settings screen says of how the values travel: the construction `shared/seal.ts` really uses, and nothing else. */
7
+ export const SETTINGS_BADGE = "X25519 · HKDF-SHA256 · ChaCha20-Poly1305";
8
+
9
+ /**
10
+ * The words of the button that deletes every file. The explanation under a row that is red sends the human to the button
11
+ * by these words, so the button and the sentence cannot name it differently.
12
+ */
13
+ export const DELETE_ALL = "Видалити всі файли секретів зараз";
14
+
15
+ /**
16
+ * The line under that button when the deletion itself was refused (the plugin is stopping, or `drop/` could not be swept):
17
+ * fixed words, and nothing of what the refusal said. What is left shows in the rows, read again after the press.
18
+ */
19
+ export const DELETE_FAILED = "Не вдалося видалити";
20
+
21
+ /**
22
+ * One line of the «Стан» section. The dot is green (`ok`), amber (`warn`: something to see, nothing to fix) or red
23
+ * (`bad`: something to do), and only a red row has an explanation under it.
24
+ */
25
+ export interface StatusRow {
26
+ label: "Плагін" | "Секрети на сервері" | "Запити, що чекають" | "Помилки";
27
+ value: string;
28
+ dot: "ok" | "warn" | "bad";
29
+ explanation: string | null;
30
+ }
31
+
32
+ const NONE = "Немає";
33
+
34
+ const ok = (label: StatusRow["label"], value: string): StatusRow => ({ label, value, dot: "ok", explanation: null });
35
+ const warn = (label: StatusRow["label"], value: string): StatusRow => ({ label, value, dot: "warn", explanation: null });
36
+ const bad = (label: StatusRow["label"], value: string, explanation: string): StatusRow => ({ label, value, dot: "bad", explanation });
37
+
38
+ /** The time of day on the clock of this machine, «09:05»: when the nearest set goes is said as a person reads a clock. */
39
+ export function clockTime(ms: number): string {
40
+ const time = new Date(ms);
41
+ return `${String(time.getHours()).padStart(2, "0")}:${String(time.getMinutes()).padStart(2, "0")}`;
42
+ }
43
+
44
+ /** A set, so that a name from a prototype is no code. */
45
+ const KNOWN_CODES: ReadonlySet<string> = new Set(ERROR_CODES);
46
+
47
+ function isKnownCode(code: string): code is ErrorCode {
48
+ return KNOWN_CODES.has(code);
49
+ }
50
+
51
+ const UNEXPECTED = "Непередбачена помилка. (unexpected)";
52
+
53
+ function pluginRow(data: Diagnostics): StatusRow {
54
+ if (data.startup !== null) {
55
+ const { code, detail } = data.startup;
56
+ const sentence = code === "unexpected" ? UNEXPECTED : describeCode(code);
57
+ return bad("Плагін", "Не запустився", detail === "" ? sentence : `${sentence} — ${detail}`);
58
+ }
59
+ // The daemon's API arrives with the first call, and messages are held back until the start-up has read the requests.
60
+ if (!data.attached || data.messagesHeld) return warn("Плагін", "Запускається");
61
+ return ok("Плагін", "Працює");
62
+ }
63
+
64
+ function filesRow(data: Diagnostics): StatusRow {
65
+ const { delivered, nextDeleteBy } = data.requests;
66
+ if (data.registry.drop === "failing") {
67
+ return bad(
68
+ "Секрети на сервері",
69
+ `${delivered} · не все видалено`,
70
+ `Не вдалося видалити деякі файли. Натисніть «${DELETE_ALL}» або видаліть ${data.dataDir}/drop.`,
71
+ );
72
+ }
73
+ if (delivered === 0) return ok("Секрети на сервері", NONE);
74
+ // The contract allows a deadline of none beside a set; the count is true all the same.
75
+ if (nextDeleteBy === null) return warn("Секрети на сервері", String(delivered));
76
+ return warn("Секрети на сервері", `${delivered} · найближчий зникне о ${clockTime(nextDeleteBy)}`);
77
+ }
78
+
79
+ function waitingRow(data: Diagnostics): StatusRow {
80
+ const { pending } = data.requests;
81
+ return pending > 0 ? warn("Запити, що чекають", String(pending)) : ok("Запити, що чекають", NONE);
82
+ }
83
+
84
+ const HOOK_FAILURE = /^([^:\s][^:]*): ([a-z_]+)$/;
85
+
86
+ /** `<hook>: <code>` with the sentence for a code the plugin knows; anything else is shown as it was kept. */
87
+ function hookFailure(kept: string): string {
88
+ const parts = HOOK_FAILURE.exec(kept);
89
+ const hook = parts?.[1];
90
+ const code = parts?.[2];
91
+ if (hook === undefined || code === undefined) return kept;
92
+ if (code === "unexpected") return `${hook}: ${UNEXPECTED}`;
93
+ return isKnownCode(code) ? `${hook}: ${describeCode(code)}` : kept;
94
+ }
95
+
96
+ /** The first thing that is the matter, in the order of the table, or null. */
97
+ function firstProblem(data: Diagnostics): string | null {
98
+ if (data.registry.persistence === "failing") return "Не вдається зберегти стан запитів.";
99
+ if (data.registry.stored === "unreadable") return "Файл запитів не читається.";
100
+ if (data.outbox.persistence === "failing") return "Не вдається зберегти повідомлення агентам.";
101
+ if (data.cardsOwed > 0) return `Картку не показано в чаті: ${data.cardsOwed}.`;
102
+ if (data.lastHookFailure !== null) return hookFailure(data.lastHookFailure);
103
+ return null;
104
+ }
105
+
106
+ function problemsRow(data: Diagnostics): StatusRow {
107
+ const problem = firstProblem(data);
108
+ return problem === null ? ok("Помилки", NONE) : bad("Помилки", "Є", problem);
109
+ }
110
+
111
+ /**
112
+ * The four lines of the «Стан» section, from what the plugin says of itself. Read-only: nothing here changes anything. Not
113
+ * every number of the contract has a line: the counts of entries left out of the stored requests and of the outbox
114
+ * (`registry.dropped`, `outbox.unsaved`, `outbox.dropped`) are kept in the contract and are not shown.
115
+ */
116
+ export function statusRows(data: Diagnostics): StatusRow[] {
117
+ return [pluginRow(data), filesRow(data), waitingRow(data), problemsRow(data)];
118
+ }
119
+
120
+ /**
121
+ * Whether the button that deletes every file is shown: while the plugin has a delivered set, and while its drop is
122
+ * failing, which can be with none delivered (the sweep of a start, or of an earlier deletion, left an entry it could not
123
+ * remove). The red row of the secrets sends the human to this button by its words, so the two are there together.
124
+ */
125
+ export function canDeleteAll(data: Diagnostics): boolean {
126
+ return data.requests.delivered > 0 || data.registry.drop === "failing";
127
+ }
128
+
129
+ /** The colour of a row's dot, from the theme. */
130
+ export function dotColor(dot: StatusRow["dot"], colors: Tone): string {
131
+ switch (dot) {
132
+ case "ok":
133
+ return colors.success;
134
+ case "warn":
135
+ return colors.warning;
136
+ default:
137
+ return colors.danger;
138
+ }
139
+ }
@@ -0,0 +1,59 @@
1
+ import type { RequestView } from "../shared/view";
2
+ import { UNAVAILABLE, afterReadClosed, type Next } from "./outcome";
3
+ import { dialogScreen } from "./presentation";
4
+
5
+ /**
6
+ * What the form holds about the request itself, apart from what was typed: the view it shows, whether its reading
7
+ * failed, whether the request is closed, and the line at its top. One value, moved on by the functions below and by
8
+ * nothing in the component.
9
+ */
10
+ export interface DialogState {
11
+ view: RequestView | null;
12
+ loadFailed: boolean;
13
+ /** The request is closed: «→» is disabled for as long as the form is open, and what was typed stays. */
14
+ closed: boolean;
15
+ /** The one line at the top of the form, or none. */
16
+ top: string | null;
17
+ }
18
+
19
+ /** A form that has just been opened: nothing read yet. */
20
+ export function openedDialog(): DialogState {
21
+ return { view: null, loadFailed: false, closed: false, top: null };
22
+ }
23
+
24
+ /**
25
+ * The state after a reading of the request: the one the form makes when it opens, or «→» on the failed screen. A view
26
+ * of another request is no view of this one, and a reading that brought none is the failed screen, with the line that
27
+ * asks for «→» again; a view that was held stays under it. A request that no longer waits is shown closed.
28
+ */
29
+ export function applyRead(state: DialogState, requestId: string, loaded: RequestView | null): DialogState {
30
+ if (loaded === null || loaded.id !== requestId) return { ...state, loadFailed: true, top: UNAVAILABLE };
31
+ if (loaded.state !== "pending") return applyOutcome({ ...state, loadFailed: false }, { next: afterReadClosed(), view: loaded });
32
+ return { ...state, view: loaded, loadFailed: false, top: null };
33
+ }
34
+
35
+ /**
36
+ * The state after an answer: of a submission (`submitEntries`) or of a decline. A view the answer brings is held in
37
+ * place of the one before; the line at the top is the answer's, none when it has none; and once the request is closed,
38
+ * it stays closed.
39
+ */
40
+ export function applyOutcome(state: DialogState, outcome: { next: Next; view: RequestView | null }): DialogState {
41
+ return {
42
+ view: outcome.view ?? state.view,
43
+ loadFailed: state.loadFailed,
44
+ closed: state.closed || outcome.next.closed,
45
+ top: outcome.next.top,
46
+ };
47
+ }
48
+
49
+ /** What «→» does now: read the request again on the failed screen, send a form that is ready to a request that is open, or nothing. */
50
+ export function arrowAction(state: DialogState, ready: boolean): "read" | "submit" | null {
51
+ const screen = dialogScreen(state);
52
+ if (screen === "failed") return "read";
53
+ return screen === "form" && ready && !state.closed ? "submit" : null;
54
+ }
55
+
56
+ /** What «✕» does: decline the request, unless it is known to be closed already, when there is nothing to decline and the form only closes. */
57
+ export function declineAction(state: Pick<DialogState, "closed">): "decline" | "close" {
58
+ return state.closed ? "close" : "decline";
59
+ }
@@ -0,0 +1,292 @@
1
+ import type { PluginHostProps } from "@getpaseo/plugin/client";
2
+ import { useRpc } from "@getpaseo/plugin/client";
3
+ import { Icon, Modal } from "@getpaseo/plugin/client/ui";
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+ import { Text, View } from "react-native";
6
+ import { declineRequest, fulfillRequest, getRequest } from "../shared/contracts";
7
+ import { LIMITS } from "../shared/limits";
8
+ import type { RequestView } from "../shared/view";
9
+ import { applyOutcome, applyRead, arrowAction, declineAction, openedDialog, type DialogState } from "./dialog-state";
10
+ import { keepAfter, type SealedSubmission } from "./envelope-cache";
11
+ import { takeFile, wipeFile, type FileValue } from "./file-entry";
12
+ import { ANNOUNCED, FileRow, IconButton, MONO, RowLine, TextRow } from "./fields";
13
+ import { addRow, checkForm, clearFile, fillFile, formFromView, removeRow, setName, setText, toFileRow, wipeForm, type FormState } from "./form-state";
14
+ import { afterDecline, afterLostReply } from "./outcome";
15
+ import { A11Y, FORM_BADGE, dialogScreen, formTitle } from "./presentation";
16
+ import { sealEntries } from "./sealing";
17
+ import { submitEntries, type SubmitDeps, type SubmitOutcome } from "./submit";
18
+ import { tone } from "./tone";
19
+ import { canPickFiles, pickFile, useFileDrop } from "./web";
20
+
21
+ interface DialogProps extends PluginHostProps {
22
+ requestId: string;
23
+ /** A fresh number each time the form opens. The pill keys the form by the request and this, so every opening of every request starts from nothing. */
24
+ session: number;
25
+ onClose(): void;
26
+ }
27
+
28
+ /**
29
+ * A value the component renders as it was last set, and that its handlers read as it is now: a press, a blur and a
30
+ * file that arrives late all act on the latest form, not on the one of the render they were made in.
31
+ */
32
+ function useHeld<T>(initial: () => T): [T, { readonly current: T }, (next: T) => void] {
33
+ const ref = useRef<{ current: T } | null>(null);
34
+ if (ref.current === null) ref.current = { current: initial() };
35
+ const held = ref.current;
36
+ const [value, setValue] = useState<T>(held.current);
37
+ const set = useCallback(
38
+ (next: T) => {
39
+ held.current = next;
40
+ setValue(next);
41
+ },
42
+ [held],
43
+ );
44
+ return [value, held, set];
45
+ }
46
+
47
+ /**
48
+ * The form over the chat. It holds what the human types and the files they give, reads the request once
49
+ * when it opens, and does what `outcome.ts`, `submit.ts` and `dialog-state.ts` decide. However it goes (closed by the
50
+ * human, by an answer, or unmounted with its row by the chat's list), it takes no file's bytes along: they are wiped.
51
+ */
52
+ export function RequestDialog({ requestId, session, onClose, theme, layout }: DialogProps) {
53
+ const colors = tone(theme.colors);
54
+ const get = useRpc(getRequest);
55
+ const fulfill = useRpc(fulfillRequest);
56
+ const decline = useRpc(declineRequest);
57
+ const [state, stateRef, setState] = useHeld<DialogState>(openedDialog);
58
+ const [form, formRef, setForm] = useHeld<FormState>(() => ({ rows: [] }));
59
+ /** What is under way: «→» (a reading or a submission), or «✕». Nothing else is taken meanwhile. */
60
+ const [busy, setBusy] = useState<"arrow" | "decline" | null>(null);
61
+ const working = useRef(false);
62
+ /** The envelope of the last submission with the entries it was sealed from. Component memory only; gone with the form. */
63
+ const sealed = useRef<SealedSubmission | null>(null);
64
+ const mounted = useRef(true);
65
+ /** The number the next row of the human's is given. Never one that was given before, so no row takes another's place. */
66
+ const nextRow = useRef(1);
67
+ const body = useRef<View>(null);
68
+ const latestGet = useRef(get);
69
+ latestGet.current = get;
70
+
71
+ useEffect(() => {
72
+ mounted.current = true;
73
+ return () => {
74
+ mounted.current = false;
75
+ wipeForm(formRef.current);
76
+ sealed.current = null;
77
+ };
78
+ }, [formRef]);
79
+
80
+ /** A change to the form, made on the latest form and once: a change that wipes a file wipes it here. */
81
+ const update = (change: (current: FormState) => FormState) => {
82
+ const next = change(formRef.current);
83
+ if (next !== formRef.current) setForm(next);
84
+ };
85
+
86
+ /** A reading of the request, and the form for its fields when it is the first view the form holds. */
87
+ const land = useCallback(
88
+ (loaded: RequestView | null) => {
89
+ if (!mounted.current) return;
90
+ const before = stateRef.current;
91
+ const after = applyRead(before, requestId, loaded);
92
+ setState(after);
93
+ if (before.view === null && after.view !== null) setForm(formFromView(after.view));
94
+ },
95
+ [requestId, stateRef, setState, setForm],
96
+ );
97
+
98
+ // Read once per opening. There is no interval and no refetch on focus: nothing may change on screen while the human types.
99
+ useEffect(() => {
100
+ let current = true;
101
+ latestGet.current({ requestId }).then(
102
+ (loaded) => {
103
+ if (current) land(loaded);
104
+ },
105
+ () => {
106
+ if (current) land(null);
107
+ },
108
+ );
109
+ return () => {
110
+ current = false;
111
+ };
112
+ }, [requestId, session, land]);
113
+
114
+ function close() {
115
+ wipeForm(formRef.current);
116
+ sealed.current = null;
117
+ onClose();
118
+ }
119
+
120
+ /** Does exactly what the outcome says. */
121
+ function perform(outcome: SubmitOutcome) {
122
+ if (!mounted.current) return;
123
+ sealed.current = outcome.cache;
124
+ setState(applyOutcome(stateRef.current, outcome));
125
+ if (outcome.next.clearForm) {
126
+ wipeForm(formRef.current);
127
+ setForm({ rows: [] });
128
+ }
129
+ if (outcome.next.close) close();
130
+ }
131
+
132
+ /** One thing at a time. A task never rejects; if one fails all the same, the form asks for «→» again and keeps everything. */
133
+ async function run(kind: "arrow" | "decline", task: () => Promise<void>) {
134
+ if (working.current) return;
135
+ working.current = true;
136
+ setBusy(kind);
137
+ try {
138
+ await task();
139
+ } catch {
140
+ if (mounted.current) setState(applyOutcome(stateRef.current, { next: afterLostReply(), view: null }));
141
+ } finally {
142
+ working.current = false;
143
+ if (mounted.current) setBusy(null);
144
+ }
145
+ }
146
+
147
+ const deps: SubmitDeps = { get, fulfill, seal: sealEntries };
148
+
149
+ function pressArrow() {
150
+ const { entries } = checkForm(formRef.current);
151
+ const action = arrowAction(stateRef.current, entries !== null);
152
+ if (action === "read") {
153
+ void run("arrow", async () => {
154
+ let loaded: RequestView | null;
155
+ try {
156
+ loaded = await get({ requestId });
157
+ } catch {
158
+ loaded = null;
159
+ }
160
+ land(loaded);
161
+ });
162
+ } else if (action === "submit") {
163
+ const view = stateRef.current.view;
164
+ if (view === null || entries === null) return;
165
+ void run("arrow", async () => perform(await submitEntries(deps, { requestId, view, entries, cache: sealed.current })));
166
+ }
167
+ }
168
+
169
+ function pressDecline() {
170
+ if (working.current) return;
171
+ if (declineAction(stateRef.current) === "close") return close();
172
+ void run("decline", async () => {
173
+ let succeeded = false;
174
+ try {
175
+ await decline({ requestId });
176
+ succeeded = true;
177
+ } catch {
178
+ // Closed by someone else, or the plugin is unreachable: the form says so with its line, and the pill shows the real state.
179
+ }
180
+ const next = afterDecline(succeeded);
181
+ perform({ next, cache: keepAfter(sealed.current, next), view: null });
182
+ });
183
+ }
184
+
185
+ /** A file for a row: taken only while the form is on screen and nothing is under way, and only into an empty file row; any other is wiped (`takeFile`, `fillFile`). */
186
+ const took = (id: string) => (file: FileValue) => takeFile(file, mounted.current && !working.current, (taken) => update((current) => fillFile(current, id, taken)));
187
+
188
+ /** The paperclip of a text row of the human's: the row becomes a file row, and where the app can pick a file, it is picked now. */
189
+ const toFile = (id: string) => {
190
+ update((current) => toFileRow(current, id));
191
+ if (canPickFiles) {
192
+ void pickFile().then((file) => {
193
+ if (file !== null) took(id)(file);
194
+ });
195
+ }
196
+ };
197
+
198
+ // A file dropped on the form but not on a file row is taken by nothing, and goes nowhere else either.
199
+ useFileDrop(body, wipeFile);
200
+
201
+ const checked = useMemo(() => checkForm(form), [form]);
202
+ const labels = useMemo(() => new Map((state.view?.fields ?? []).map((field) => [field.key, field.label] as const)), [state.view]);
203
+ const screen = dialogScreen(state);
204
+ const locked = busy !== null;
205
+ const arrowReady = busy === null && arrowAction(state, checked.entries !== null) !== null;
206
+
207
+ return (
208
+ <Modal title={formTitle(form.rows.length)} icon={<Icon name="ShieldCheck" size={18} color={colors.accent} />} open onOpenChange={(open) => (open ? undefined : close())}>
209
+ {/* The host's own scrolling body: the sheet on a phone, with its swipe down and its keyboard handling, and on the desktop a box no taller than the form. */}
210
+ <Modal.Content contentContainerStyle={{ padding: layout.compact ? 16 : 20, gap: 0 }}>
211
+ <View ref={body} style={{ gap: 8 }}>
212
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
213
+ <View style={{ borderWidth: 1, borderColor: colors.border, borderRadius: 6, paddingHorizontal: 6, paddingVertical: 2 }}>
214
+ <Text style={{ color: colors.accent, fontFamily: MONO, fontSize: 11 }}>{FORM_BADGE}</Text>
215
+ </View>
216
+ <View style={{ flex: 1 }} />
217
+ <IconButton icon="X" label={A11Y.decline} color={colors.muted} disabled={locked} onPress={pressDecline} />
218
+ </View>
219
+
220
+ {state.top === null ? null : (
221
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
222
+ <Icon name="CircleAlert" size={14} color={colors.danger} />
223
+ <Text {...ANNOUNCED} style={{ color: colors.danger, fontSize: 12, flexShrink: 1 }}>
224
+ {state.top}
225
+ </Text>
226
+ </View>
227
+ )}
228
+
229
+ {screen === "form"
230
+ ? form.rows.map((row) => {
231
+ const error = checked.errors.get(row.id) ?? null;
232
+ const onName = (key: string) => update((current) => setName(current, row.id, key));
233
+ const onRemove = () => update((current) => removeRow(current, row.id));
234
+ return row.value.kind === "text" ? (
235
+ <TextRow
236
+ key={row.id}
237
+ row={row}
238
+ hint={row.declared ? (labels.get(row.key) ?? "") : ""}
239
+ error={error}
240
+ colors={colors}
241
+ locked={locked}
242
+ onText={(text) => update((current) => setText(current, row.id, text))}
243
+ onName={onName}
244
+ onToFile={() => toFile(row.id)}
245
+ onRemove={onRemove}
246
+ />
247
+ ) : (
248
+ <FileRow
249
+ key={row.id}
250
+ row={row}
251
+ hint={row.declared ? (labels.get(row.key) ?? "") : ""}
252
+ error={error}
253
+ colors={colors}
254
+ locked={locked}
255
+ onName={onName}
256
+ onFile={took(row.id)}
257
+ onClearFile={() => update((current) => clearFile(current, row.id))}
258
+ onRemove={onRemove}
259
+ />
260
+ );
261
+ })
262
+ : null}
263
+
264
+ {screen === "loading" ? null : (
265
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8, marginTop: 4 }}>
266
+ {screen === "form" ? (
267
+ <IconButton
268
+ icon="Plus"
269
+ label={A11Y.add}
270
+ color={colors.muted}
271
+ fill={colors.raised}
272
+ disabled={locked || form.rows.length >= LIMITS.fields}
273
+ onPress={() => update((current) => addRow(current, nextRow.current++))}
274
+ />
275
+ ) : null}
276
+ <View style={{ flex: 1, alignItems: "center" }}>{screen === "form" && checked.total !== null ? <RowLine text={checked.total} colors={colors} /> : null}</View>
277
+ <IconButton
278
+ icon="ArrowRight"
279
+ label={A11Y.submit}
280
+ color={colors.onAccent}
281
+ fill={colors.accent}
282
+ busy={busy === "arrow"}
283
+ disabled={!arrowReady}
284
+ onPress={pressArrow}
285
+ />
286
+ </View>
287
+ )}
288
+ </View>
289
+ </Modal.Content>
290
+ </Modal>
291
+ );
292
+ }
@@ -0,0 +1,85 @@
1
+ import type { PayloadEntry, SealedEnvelope } from "../shared/seal";
2
+ import type { Next } from "./outcome";
3
+
4
+ /**
5
+ * What an envelope was sealed to. The ciphertext is bound to the request and to the digest of what it asked for
6
+ * (`buildAad`) and readable only with the request's key, so an envelope is good for exactly this and nothing else.
7
+ */
8
+ export interface SealTarget {
9
+ requestId: string;
10
+ publicKey: string;
11
+ requestDigest: string;
12
+ }
13
+
14
+ /**
15
+ * The envelope of the last submission together with the entries it was sealed from, kept in component memory while the
16
+ * form is open. The daemon recognises a submission by the digest of its ciphertext: the same envelope sent again is
17
+ * answered with the same result, but the same values sealed anew are a second, different submission, and one that
18
+ * arrives after the first was accepted is refused as `request_closed` and flagged as tampering.
19
+ */
20
+ export interface SealedSubmission {
21
+ target: SealTarget;
22
+ entries: readonly PayloadEntry[];
23
+ envelope: SealedEnvelope;
24
+ /** True after a call whose reply never came: the daemon may or may not have taken this envelope. */
25
+ lostReply: boolean;
26
+ }
27
+
28
+ export type EnvelopeChoice = { reuse: true; envelope: SealedEnvelope } | { reuse: false };
29
+
30
+ function sameTarget(a: SealTarget, b: SealTarget): boolean {
31
+ return a.requestId === b.requestId && a.publicKey === b.publicKey && a.requestDigest === b.requestDigest;
32
+ }
33
+
34
+ /** The same key, and the same text or the same file: a text and a file are never the same, whatever characters they have. */
35
+ function sameEntry(a: PayloadEntry, b: PayloadEntry): boolean {
36
+ if (a.key !== b.key) return false;
37
+ if ("file" in a) return "file" in b && a.file === b.file;
38
+ return !("file" in b) && a.value === b.value;
39
+ }
40
+
41
+ /** Same entries, same order. The values are compared where they already are, in memory; nothing derived from one is made. */
42
+ function sameEntries(a: readonly PayloadEntry[], b: readonly PayloadEntry[]): boolean {
43
+ if (a.length !== b.length) return false;
44
+ return a.every((entry, index) => {
45
+ const other = b[index];
46
+ return other !== undefined && sameEntry(entry, other);
47
+ });
48
+ }
49
+
50
+ /** The kept envelope when the entries are the ones it was sealed from, to the same request. Otherwise the caller seals anew. */
51
+ export function chooseEnvelope(cache: SealedSubmission | null, target: SealTarget, entries: readonly PayloadEntry[]): EnvelopeChoice {
52
+ if (cache !== null && sameTarget(cache.target, target) && sameEntries(cache.entries, entries)) {
53
+ return { reuse: true, envelope: cache.envelope };
54
+ }
55
+ return { reuse: false };
56
+ }
57
+
58
+ /**
59
+ * Takes its own copy of the entries, of each its key and its text or its file and nothing else: what the caller does
60
+ * with its list afterwards must not change what the envelope was sealed from.
61
+ */
62
+ export function remember(target: SealTarget, entries: readonly PayloadEntry[], envelope: SealedEnvelope): SealedSubmission {
63
+ const copies = entries.map((entry): PayloadEntry => ("file" in entry ? { key: entry.key, file: entry.file } : { key: entry.key, value: entry.value }));
64
+ return { target: { ...target }, entries: copies, envelope, lostReply: false };
65
+ }
66
+
67
+ /** The call was made and no reply came. */
68
+ export function markLost(cache: SealedSubmission): SealedSubmission {
69
+ return { ...cache, lostReply: true };
70
+ }
71
+
72
+ /** An answer came, even a refusal: whether the daemon took the envelope is known again. */
73
+ export function markKnown(cache: SealedSubmission): SealedSubmission {
74
+ return { ...cache, lostReply: false };
75
+ }
76
+
77
+ /** True when what is kept was sent to this request and nobody knows whether it was taken. */
78
+ export function unknownOutcome(cache: SealedSubmission | null, target: SealTarget): boolean {
79
+ return cache !== null && cache.lostReply && sameTarget(cache.target, target);
80
+ }
81
+
82
+ /** What is kept once the answer is known: the same, unless the answer says the envelope is of no further use. */
83
+ export function keepAfter(cache: SealedSubmission | null, next: Pick<Next, "dropEnvelope">): SealedSubmission | null {
84
+ return next.dropEnvelope ? null : cache;
85
+ }