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,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
+ }
@@ -0,0 +1,96 @@
1
+ import { fromBase64Url } from "../shared/bytes";
2
+ import { MAX_PAYLOAD_BYTES, buildAad, digestHex, seal, type SealedEnvelope } from "../shared/seal";
3
+
4
+ /**
5
+ * What the self-test seals: the largest submission one Paseo call can carry. It proves on this device that the biggest thing
6
+ * a person can send travels the whole way (sealed here, through the daemon's channel, opened there), which a small payload
7
+ * does not: a path with a limit on its messages passes the small one and refuses this.
8
+ */
9
+ export const SELF_TEST_BYTES = MAX_PAYLOAD_BYTES;
10
+
11
+ /**
12
+ * Where the self-test stands. `running` takes the place of an earlier result the moment a run starts, so that the screen
13
+ * never shows the result of the run before as if it were this one's.
14
+ */
15
+ export type SelfTestState =
16
+ | { kind: "idle" }
17
+ | { kind: "running" }
18
+ /** `bytes` is what the plugin says it opened. */
19
+ | { kind: "passed"; bytes: number; ms: number }
20
+ /** The plugin answered, and it had not opened the message or found another digest. */
21
+ | { kind: "mismatch" }
22
+ /** A step failed: sealing in the app, or one of the two calls to the plugin. */
23
+ | { kind: "failed"; stage: "seal" | "plugin" };
24
+
25
+ export const IDLE: SelfTestState = { kind: "idle" };
26
+ export const RUNNING: SelfTestState = { kind: "running" };
27
+
28
+ /** What the sequence needs from outside: the two calls to the plugin, and the clock. */
29
+ export interface SelfTestDeps {
30
+ begin(input: Record<string, never>): Promise<{ probeId: string; publicKey: string }>;
31
+ finish(input: { probeId: string; envelope: SealedEnvelope; digest: string }): Promise<{ ok: boolean; bytes: number }>;
32
+ now(): number;
33
+ }
34
+
35
+ const failed = (stage: "seal" | "plugin"): SelfTestState => ({ kind: "failed", stage });
36
+
37
+ /**
38
+ * Seals a dummy payload in the app and has the plugin open it: the path a real value takes. Decided here and not in
39
+ * the component: which step failed, and what is kept of a failure, which is its stage and nothing of what the error said.
40
+ * It never rejects.
41
+ *
42
+ * The dummy bytes are the largest thing the screen ever holds. They are wiped as a value is, the moment they are sealed
43
+ * and hashed and on every way out, which is before the plugin is asked to open what they became.
44
+ */
45
+ export async function runSelfTest(deps: SelfTestDeps, bytes: number = SELF_TEST_BYTES): Promise<SelfTestState> {
46
+ let startedAt: number;
47
+ let probe: { probeId: string; publicKey: string };
48
+ try {
49
+ startedAt = deps.now();
50
+ probe = await deps.begin({});
51
+ } catch {
52
+ return failed("plugin");
53
+ }
54
+
55
+ let envelope: SealedEnvelope;
56
+ let digest: string;
57
+ let payload: Uint8Array | undefined;
58
+ try {
59
+ payload = new Uint8Array(bytes).fill(0x61);
60
+ envelope = seal(fromBase64Url(probe.publicKey), payload, buildAad(probe.probeId, "selftest"));
61
+ digest = digestHex(payload);
62
+ } catch {
63
+ return failed("seal");
64
+ } finally {
65
+ payload?.fill(0);
66
+ }
67
+
68
+ try {
69
+ const outcome = await deps.finish({ probeId: probe.probeId, envelope, digest });
70
+ return outcome.ok ? { kind: "passed", bytes: outcome.bytes, ms: deps.now() - startedAt } : { kind: "mismatch" };
71
+ } catch {
72
+ return failed("plugin");
73
+ }
74
+ }
75
+
76
+ /** What a screen reader says of the spinner that stands in the place of the result while a run is going. */
77
+ export const SELF_TEST_RUNNING = "Перевірка триває";
78
+
79
+ /**
80
+ * What the settings screen says of a run, next to the button: how long it took, or why it did not pass, in a fixed
81
+ * sentence and never in the words of an error. Before a run and while one is going it says nothing: the screen shows a
82
+ * spinner then (`SELF_TEST_RUNNING`).
83
+ */
84
+ export function selfTestText(state: SelfTestState): string {
85
+ switch (state.kind) {
86
+ case "idle":
87
+ case "running":
88
+ return "";
89
+ case "passed":
90
+ return `✓ ${state.ms} мс`;
91
+ case "mismatch":
92
+ return "✗ дані не збіглися";
93
+ default:
94
+ return state.stage === "seal" ? "✗ не вдалося зашифрувати" : "✗ плагін не відповів";
95
+ }
96
+ }
@@ -0,0 +1,160 @@
1
+ import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
2
+ import { useRpc } from "@getpaseo/plugin/client";
3
+ import { Icon, SettingsAction, SettingsCard, SettingsRow, SettingsSection } from "@getpaseo/plugin/client/ui";
4
+ import { useQuery } from "@tanstack/react-query";
5
+ import { useState, type ReactElement } from "react";
6
+ import { ActivityIndicator, Text, View } from "react-native";
7
+ import { clearDrop, readDiagnostics, selfTestBegin, selfTestFinish, type Diagnostics } from "../shared/contracts";
8
+ import { PASEO_SINCE, PLUGIN_VERSION } from "../shared/limits";
9
+ import { DELETE_ALL, DELETE_FAILED, SETTINGS_BADGE, canDeleteAll, dotColor, statusRows, type StatusRow } from "./diagnostics-rows";
10
+ import { MONO } from "./fields";
11
+ import { IDLE, RUNNING, SELF_TEST_RUNNING, runSelfTest, selfTestText, type SelfTestState } from "./self-test";
12
+ import { tone, type Tone } from "./tone";
13
+
14
+ /** How often the state is read again while the screen is open: a set that arrives or goes shows without leaving the screen. */
15
+ const REFRESH_MS = 5_000;
16
+
17
+ /** The shield, the name, and the version of the plugin with the Paseo it needs. */
18
+ function Header({ colors }: { colors: Tone }) {
19
+ return (
20
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12, paddingVertical: 4 }}>
21
+ <View style={{ width: 36, height: 36, borderRadius: 10, alignItems: "center", justifyContent: "center", backgroundColor: colors.accent }}>
22
+ <Icon name="ShieldCheck" size={20} color={colors.onAccent} />
23
+ </View>
24
+ <View style={{ flexShrink: 1 }}>
25
+ <Text style={{ color: colors.text, fontWeight: "700", fontSize: 16 }}>secure-input</Text>
26
+ <Text style={{ color: colors.muted, fontFamily: MONO, fontSize: 12 }}>{`v${PLUGIN_VERSION} · ${PASEO_SINCE}`}</Text>
27
+ </View>
28
+ </View>
29
+ );
30
+ }
31
+
32
+ /**
33
+ * Seals in the app, opens on the daemon: the same path a real value takes, with a dummy payload of the largest size a
34
+ * submission can have. It runs on the press and not on the render. What a run comes to, and what is said of it, is
35
+ * `self-test.ts`'s to decide; a spinner stands in the place of the result while it runs.
36
+ */
37
+ function Encryption({ colors }: { colors: Tone }) {
38
+ const begin = useRpc(selfTestBegin);
39
+ const finish = useRpc(selfTestFinish);
40
+ const [state, setState] = useState<SelfTestState>(IDLE);
41
+ const running = state.kind === "running";
42
+
43
+ async function run() {
44
+ // At once: the screen says that it is running, not what the run before it found.
45
+ setState(RUNNING);
46
+ setState(await runSelfTest({ begin, finish, now: Date.now }));
47
+ }
48
+
49
+ return (
50
+ <SettingsSection title="Шифрування">
51
+ <SettingsCard>
52
+ <View style={{ paddingHorizontal: 16, paddingVertical: 12, alignItems: "flex-start" }}>
53
+ <View style={{ borderWidth: 1, borderColor: colors.border, borderRadius: 6, paddingHorizontal: 8, paddingVertical: 3 }}>
54
+ <Text style={{ color: colors.accent, fontFamily: MONO, fontSize: 11 }}>{SETTINGS_BADGE}</Text>
55
+ </View>
56
+ </View>
57
+ <SettingsAction label="Цей пристрій" actionLabel="Перевірити" disabled={running} onPress={() => void run()} />
58
+ {state.kind === "idle" ? null : (
59
+ <SettingsRow label="Результат">
60
+ {running ? (
61
+ <ActivityIndicator size="small" color={colors.muted} accessibilityLabel={SELF_TEST_RUNNING} />
62
+ ) : (
63
+ <Text style={{ color: state.kind === "passed" ? colors.success : colors.danger, fontFamily: MONO, fontSize: 12 }}>{selfTestText(state)}</Text>
64
+ )}
65
+ </SettingsRow>
66
+ )}
67
+ </SettingsCard>
68
+ </SettingsSection>
69
+ );
70
+ }
71
+
72
+ /** A coloured dot and the value of a row. The dot is the colour of its state; the words say the same. */
73
+ function StatusValue({ row, colors }: { row: StatusRow; colors: Tone }) {
74
+ return (
75
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8, flexShrink: 1 }}>
76
+ <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: dotColor(row.dot, colors) }} />
77
+ <Text selectable style={{ color: colors.muted, fontFamily: MONO, fontSize: 12, flexShrink: 1 }}>
78
+ {row.value}
79
+ </Text>
80
+ </View>
81
+ );
82
+ }
83
+
84
+ /**
85
+ * The four rows. The explanation is under a red row only (`error` of the row). Read-only: the RPC behind it is open to
86
+ * agents too. A failed reading leaves the last answer in `data`; it is shown, and said to be old, instead of passing for current.
87
+ */
88
+ function Status({ data, failed, colors }: { data: Diagnostics | undefined; failed: boolean; colors: Tone }) {
89
+ const stale = <SettingsRow key="stale" label="Оновлення" error="Не вдалося оновити: показано попередній стан" />;
90
+ const rows: ReactElement[] =
91
+ data === undefined
92
+ ? [<SettingsRow key="reading" label={failed ? "Не вдалося прочитати стан плагіна" : "Завантаження…"} />]
93
+ : [
94
+ ...(failed ? [stale] : []),
95
+ ...statusRows(data).map((row) => (
96
+ <SettingsRow key={row.label} label={row.label} error={row.explanation}>
97
+ <StatusValue row={row} colors={colors} />
98
+ </SettingsRow>
99
+ )),
100
+ ];
101
+ return (
102
+ <SettingsSection title="Стан">
103
+ <SettingsCard>{rows}</SettingsCard>
104
+ </SettingsSection>
105
+ );
106
+ }
107
+
108
+ /**
109
+ * Deletes every set of files at once, and reads the state again. What the plugin could not remove shows in the rows that
110
+ * are read. A deletion that was refused as a whole (the plugin is stopping, `drop/` could not be swept) says so in one
111
+ * fixed line under the button, `DELETE_FAILED`, until a press is not refused: the words of the refusal are not the
112
+ * screen's to show.
113
+ */
114
+ function DeleteAll({ refresh }: { refresh(): Promise<unknown> }) {
115
+ const clear = useRpc(clearDrop);
116
+ const [busy, setBusy] = useState(false);
117
+ const [refused, setRefused] = useState(false);
118
+
119
+ async function run() {
120
+ setBusy(true);
121
+ try {
122
+ await clear({});
123
+ setRefused(false);
124
+ } catch {
125
+ // The rows below, read again, say what is left.
126
+ setRefused(true);
127
+ }
128
+ try {
129
+ await refresh();
130
+ } catch {
131
+ // The reading failed: the rows say so, as old.
132
+ } finally {
133
+ setBusy(false);
134
+ }
135
+ }
136
+
137
+ return (
138
+ <View style={{ marginTop: 12 }}>
139
+ <SettingsCard>
140
+ <SettingsAction label={DELETE_ALL} actionLabel="Видалити" error={refused ? DELETE_FAILED : null} disabled={busy} onPress={() => void run()} />
141
+ </SettingsCard>
142
+ </View>
143
+ );
144
+ }
145
+
146
+ export function SettingsScreen({ theme }: PluginSurfaceProps) {
147
+ const colors = tone(theme.colors);
148
+ const read = useRpc(readDiagnostics);
149
+ const query = useQuery({ queryKey: ["secure-input", "diagnostics"], queryFn: () => read({}), refetchInterval: REFRESH_MS });
150
+ const data = query.data;
151
+
152
+ return (
153
+ <>
154
+ <Header colors={colors} />
155
+ <Encryption colors={colors} />
156
+ <Status data={data} failed={query.isError} colors={colors} />
157
+ {data !== undefined && canDeleteAll(data) ? <DeleteAll refresh={() => query.refetch()} /> : null}
158
+ </>
159
+ );
160
+ }
@@ -0,0 +1,92 @@
1
+ import type { PayloadEntry, SealedEnvelope } from "../shared/seal";
2
+ import type { RequestView } from "../shared/view";
3
+ import { chooseEnvelope, keepAfter, markKnown, markLost, remember, unknownOutcome, type SealedSubmission } from "./envelope-cache";
4
+ import { afterCheckFailed, afterFulfill, afterLostReply, afterMismatch, afterReadClosed, afterSealFailure, type FulfillResult, type Next } from "./outcome";
5
+
6
+ /** What the sequence needs from outside: the daemon's two calls and the sealer. */
7
+ export interface SubmitDeps {
8
+ get(input: { requestId: string }): Promise<RequestView>;
9
+ fulfill(input: { requestId: string; envelope: SealedEnvelope }): Promise<FulfillResult>;
10
+ /** `null` when sealing is not possible. */
11
+ seal(view: Pick<RequestView, "id" | "publicKey" | "requestDigest">, entries: readonly PayloadEntry[]): SealedEnvelope | null;
12
+ }
13
+
14
+ export interface SubmitInput {
15
+ /** The request the human is submitting to: the form was opened for this id. */
16
+ requestId: string;
17
+ /** The view the human is looking at. */
18
+ view: RequestView;
19
+ entries: readonly PayloadEntry[];
20
+ cache: SealedSubmission | null;
21
+ }
22
+
23
+ export interface SubmitOutcome {
24
+ next: Next;
25
+ /** What the form holds now. */
26
+ cache: SealedSubmission | null;
27
+ /** A view the sequence read, to hold instead of the one the human had. */
28
+ view: RequestView | null;
29
+ }
30
+
31
+ const outcome = (next: Next, cache: SealedSubmission | null, view: RequestView | null = null): SubmitOutcome => ({ next, cache, view });
32
+
33
+ /** Seals, or says it cannot; a sealer that throws is the same as one that says no. */
34
+ function sealed(deps: SubmitDeps, view: RequestView, entries: readonly PayloadEntry[]): SealedEnvelope | null {
35
+ try {
36
+ return deps.seal(view, entries);
37
+ } catch {
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /**
43
+ * The whole of a submission, decided here and not in the component: which envelope goes (the kept one for the same
44
+ * entries, a new one otherwise), under which id, what is read first, and what each answer or silence means for the
45
+ * form. The component calls it and does what the outcome says. What goes to the daemon is the request id and the
46
+ * envelope, and nothing else.
47
+ *
48
+ * After a call whose reply never came, a press with changed entries does not send a different submission blindly: if
49
+ * the first one landed, the daemon would answer `request_closed` and flag tampering on the human's own retry. The
50
+ * request is read first. This narrows the gap and does not close it: a view can still say `pending` while the first
51
+ * submission is queued behind other work.
52
+ */
53
+ export async function submitEntries(deps: SubmitDeps, submission: SubmitInput): Promise<SubmitOutcome> {
54
+ const { requestId, view, entries } = submission;
55
+ // A view of another request, under typed values, is the one thing nothing may be sealed or sent for.
56
+ if (view.id !== requestId) return outcome(afterMismatch(), submission.cache);
57
+
58
+ const target = { requestId, publicKey: view.publicKey, requestDigest: view.requestDigest };
59
+ const choice = chooseEnvelope(submission.cache, target, entries);
60
+
61
+ if (!choice.reuse && unknownOutcome(submission.cache, target)) {
62
+ let fresh: RequestView;
63
+ try {
64
+ fresh = await deps.get({ requestId });
65
+ } catch {
66
+ return outcome(afterCheckFailed(), submission.cache);
67
+ }
68
+ if (fresh.id !== requestId) return outcome(afterMismatch(), submission.cache);
69
+ if (fresh.state !== "pending") return outcome(afterReadClosed(), null, fresh);
70
+ }
71
+
72
+ let held: SealedSubmission;
73
+ if (choice.reuse && submission.cache !== null) {
74
+ held = submission.cache;
75
+ } else {
76
+ const envelope = sealed(deps, view, entries);
77
+ if (envelope === null) return outcome(afterSealFailure(), submission.cache);
78
+ held = remember(target, entries, envelope);
79
+ }
80
+
81
+ let result: FulfillResult;
82
+ try {
83
+ result = await deps.fulfill({ requestId, envelope: held.envelope });
84
+ } catch {
85
+ return outcome(afterLostReply(), markLost(held));
86
+ }
87
+
88
+ const next = afterFulfill(result);
89
+ // An answer says what became of the envelope, unless it says that it cannot: then the envelope is kept as after a
90
+ // reply that never came, and a press with other entries reads the request again before it seals them.
91
+ return outcome(next, keepAfter(next.outcomeUnknown ? markLost(held) : markKnown(held), next));
92
+ }
package/client/text.ts ADDED
@@ -0,0 +1,47 @@
1
+ /** Which of three forms a count takes in Ukrainian: 1, 21, 101 take the first; 2-4, 22-24 the second; the rest, and 11-14, the third. */
2
+ function formFor<Form>(count: number, one: Form, few: Form, many: Form): Form {
3
+ const tens = count % 100;
4
+ const units = count % 10;
5
+ if (units === 1 && tens !== 11) return one;
6
+ if (units >= 2 && units <= 4 && (tens < 12 || tens > 14)) return few;
7
+ return many;
8
+ }
9
+
10
+ /** Ukrainian plural: the count and the form of the noun that goes with it. */
11
+ export function plural(count: number, one: string, few: string, many: string): string {
12
+ return `${count} ${formFor(count, one, few, many)}`;
13
+ }
14
+
15
+ /** «1 байт», «2 байти», «5 байтів»: wherever a size is shown, it is said this way. */
16
+ export function bytesText(count: number): string {
17
+ return plural(count, "байт", "байти", "байтів");
18
+ }
19
+
20
+ /** One to ten of something feminine, as it is said: «три спроби», and «після трьох спроб». A number past the list is written in digits. */
21
+ const FEMININE_COUNT: ReadonlyArray<{ nominative: string; genitive: string }> = [
22
+ { nominative: "одна", genitive: "однієї" },
23
+ { nominative: "дві", genitive: "двох" },
24
+ { nominative: "три", genitive: "трьох" },
25
+ { nominative: "чотири", genitive: "чотирьох" },
26
+ { nominative: "п'ять", genitive: "п'яти" },
27
+ { nominative: "шість", genitive: "шести" },
28
+ { nominative: "сім", genitive: "семи" },
29
+ { nominative: "вісім", genitive: "восьми" },
30
+ { nominative: "дев'ять", genitive: "дев'яти" },
31
+ { nominative: "десять", genitive: "десяти" },
32
+ ];
33
+
34
+ /**
35
+ * «Три спроби не вдались»: how many attempts failed, as the start of a sentence. The number is the limit the plugin
36
+ * counts to (`MAX_RETRIES`), so the sentence is built from it and cannot say another number than the plugin means.
37
+ */
38
+ export function attemptsFailed(count: number): string {
39
+ const word = FEMININE_COUNT[count - 1]?.nominative ?? String(count);
40
+ return `${word.charAt(0).toUpperCase()}${word.slice(1)} ${formFor(count, "спроба не вдалась", "спроби не вдались", "спроб не вдалось")}`;
41
+ }
42
+
43
+ /** «Після трьох невдалих спроб»: after how many failed attempts something happens. */
44
+ export function afterFailedAttempts(count: number): string {
45
+ const word = FEMININE_COUNT[count - 1]?.genitive ?? String(count);
46
+ return `Після ${word} ${formFor(count, "невдалої спроби", "невдалих спроб", "невдалих спроб")}`;
47
+ }
package/client/tone.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
2
+
3
+ type Colors = PluginSurfaceProps["theme"]["colors"];
4
+
5
+ /** The colours a component draws with. Every `Text` takes its colour from here, so every colour comes from the theme. */
6
+ export interface Tone {
7
+ surface: string;
8
+ raised: string;
9
+ text: string;
10
+ muted: string;
11
+ accent: string;
12
+ onAccent: string;
13
+ border: string;
14
+ success: string;
15
+ warning: string;
16
+ danger: string;
17
+ }
18
+
19
+ /** Tokens added after SDK 0.8 can be missing on an older app. Fall back instead of rendering `undefined`. */
20
+ export function tone(colors: Colors): Tone {
21
+ const optional = colors as Partial<Colors>;
22
+ return {
23
+ surface: colors.surface0,
24
+ raised: optional.surface1 ?? colors.surface0,
25
+ text: colors.foreground,
26
+ muted: colors.foregroundMuted,
27
+ accent: colors.accent,
28
+ onAccent: colors.accentForeground,
29
+ border: optional.border ?? "rgba(127,127,127,0.28)",
30
+ success: optional.statusSuccess ?? colors.accent,
31
+ // Of the three the muted colour is left: the accent stands for success and the plain text for danger, and the words
32
+ // beside a dot say what it means all the same.
33
+ warning: optional.statusWarning ?? colors.foregroundMuted,
34
+ danger: optional.statusDanger ?? colors.foreground,
35
+ };
36
+ }