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,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. When the clear call fails (the plugin is stopping, `drop/` could not be swept), earlier removals may have
111
+ * succeeded; one fixed line under the button, `DELETE_FAILED`, says that it failed, until a press succeeds: the words of
112
+ * the failure are not the 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
+ }
package/client/web.ts ADDED
@@ -0,0 +1,184 @@
1
+ import { useEffect, useRef, type RefObject } from "react";
2
+ import { Platform } from "react-native";
3
+ import { LIMITS } from "../shared/limits";
4
+ import { wipeFile, type FileValue } from "./file-entry";
5
+
6
+ // The one module of the app that touches the browser's own objects. The desktop app is the web build of the app in
7
+ // Electron, and the SDK gives a plugin neither a file picker nor a way to take a file that is dropped: this module does
8
+ // both. It reaches the browser through `globalThis`, and describes below the few members it uses, so that no project is
9
+ // checked against the DOM's types. Every export is gated on the web platform and does nothing anywhere else: a phone has
10
+ // no picking and no dropping, only the paste area of a file row.
11
+
12
+ /** A file the browser holds, as far as this module reads it. */
13
+ interface BrowserFile {
14
+ readonly name: string;
15
+ slice(start: number, end: number): { arrayBuffer(): Promise<ArrayBuffer> };
16
+ }
17
+
18
+ interface BrowserFiles {
19
+ item(index: number): BrowserFile | null;
20
+ }
21
+
22
+ interface FileInput {
23
+ type: string;
24
+ value: string;
25
+ readonly files: BrowserFiles | null;
26
+ addEventListener(type: "change" | "cancel", listener: () => void): void;
27
+ click(): void;
28
+ }
29
+
30
+ interface Page {
31
+ createElement(tag: "input"): FileInput;
32
+ }
33
+
34
+ interface DragEventLike {
35
+ preventDefault(): void;
36
+ stopPropagation(): void;
37
+ readonly dataTransfer: { readonly files: BrowserFiles; dropEffect: string } | null;
38
+ }
39
+
40
+ interface DropTarget {
41
+ addEventListener(type: "dragover" | "drop", listener: (event: DragEventLike) => void): void;
42
+ removeEventListener(type: "dragover" | "drop", listener: (event: DragEventLike) => void): void;
43
+ }
44
+
45
+ function isObject(value: unknown): value is Record<string, unknown> {
46
+ return typeof value === "object" && value !== null;
47
+ }
48
+
49
+ /** The page the app is drawn in, when there is one that can make an input. */
50
+ function page(): Page | null {
51
+ const found: unknown = Reflect.get(globalThis, "document");
52
+ return isObject(found) && typeof found.createElement === "function" ? (found as unknown as Page) : null;
53
+ }
54
+
55
+ /** What a row's ref holds on the web: the element it is drawn as, which takes listeners. Anything else is no target. */
56
+ function dropTarget(value: unknown): DropTarget | null {
57
+ return isObject(value) && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function"
58
+ ? (value as unknown as DropTarget)
59
+ : null;
60
+ }
61
+
62
+ /**
63
+ * A file's bytes and name. At most one byte more than a file may have is read: enough for the check to say that it is
64
+ * too large, and nothing more of a large file taken into memory. Null when the browser cannot read it.
65
+ */
66
+ function read(file: BrowserFile): Promise<FileValue | null> {
67
+ try {
68
+ return file
69
+ .slice(0, LIMITS.fileBytes + 1)
70
+ .arrayBuffer()
71
+ .then(
72
+ (buffer) => ({ name: file.name, bytes: new Uint8Array(buffer) }),
73
+ () => null,
74
+ );
75
+ } catch {
76
+ return Promise.resolve(null);
77
+ }
78
+ }
79
+
80
+ /** Whether this app can pick a file: the web build can, through an input of the page; a phone cannot. */
81
+ export const canPickFiles: boolean = Platform.OS === "web";
82
+
83
+ /**
84
+ * Opens the browser's file picker and resolves with the file the human chose, or null when they chose none, the
85
+ * picker could not be opened, or the app is not the web build. It never rejects: every step that touches the page (the
86
+ * input made, its listeners, the click, the choice read) is in one path that settles with null when one of them throws.
87
+ * A file that comes after the answer was given is wiped, and the input lets go of what it was given.
88
+ */
89
+ export function pickFile(): Promise<FileValue | null> {
90
+ if (Platform.OS !== "web") return Promise.resolve(null);
91
+ const found = page();
92
+ if (found === null) return Promise.resolve(null);
93
+ return new Promise((resolve) => {
94
+ let input: FileInput | null = null;
95
+ let settled = false;
96
+ const settle = (file: FileValue | null): void => {
97
+ if (settled) {
98
+ if (file !== null) wipeFile(file);
99
+ return;
100
+ }
101
+ settled = true;
102
+ try {
103
+ if (input !== null) input.value = "";
104
+ } catch {
105
+ // The input goes with this call, and what it was given with it.
106
+ }
107
+ resolve(file);
108
+ };
109
+ try {
110
+ const made = found.createElement("input");
111
+ input = made;
112
+ made.type = "file";
113
+ made.addEventListener("change", () => {
114
+ let chosen: BrowserFile | null;
115
+ try {
116
+ chosen = made.files?.item(0) ?? null;
117
+ } catch {
118
+ chosen = null;
119
+ }
120
+ if (chosen === null) settle(null);
121
+ else void read(chosen).then(settle, () => settle(null));
122
+ });
123
+ made.addEventListener("cancel", () => settle(null));
124
+ made.click();
125
+ } catch {
126
+ settle(null);
127
+ }
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Takes a file dropped on the element `ref` holds: its bytes go to `onFile`, read as `pickFile` reads them. The drop is
133
+ * the row's alone: the browser does not open the file, and nothing around the row is given it. A file that is read after
134
+ * the row is gone is wiped. On a phone it does nothing.
135
+ */
136
+ export function useFileDrop(ref: RefObject<unknown>, onFile: (file: FileValue) => void): void {
137
+ if (Platform.OS !== "web") return;
138
+ // The platform is the same on every render, so these hooks are called on every render of a web app and on none elsewhere.
139
+ const held = useRef({ onFile, mounted: true });
140
+ useEffect(() => {
141
+ held.current.onFile = onFile;
142
+ });
143
+ useEffect(() => {
144
+ const state = held.current;
145
+ state.mounted = true;
146
+ return () => {
147
+ state.mounted = false;
148
+ };
149
+ }, []);
150
+ // After every render: the element the ref holds may be another one.
151
+ useEffect(() => {
152
+ const target = dropTarget(ref.current);
153
+ if (target === null) return undefined;
154
+ const over = (event: DragEventLike): void => {
155
+ event.preventDefault();
156
+ event.stopPropagation();
157
+ if (event.dataTransfer !== null) event.dataTransfer.dropEffect = "copy";
158
+ };
159
+ const drop = (event: DragEventLike): void => {
160
+ event.preventDefault();
161
+ event.stopPropagation();
162
+ const file = event.dataTransfer?.files.item(0) ?? null;
163
+ if (file === null) return;
164
+ void read(file).then((value) => {
165
+ if (value === null) return;
166
+ if (!held.current.mounted) {
167
+ wipeFile(value);
168
+ return;
169
+ }
170
+ try {
171
+ held.current.onFile(value);
172
+ } catch {
173
+ wipeFile(value);
174
+ }
175
+ });
176
+ };
177
+ target.addEventListener("dragover", over);
178
+ target.addEventListener("drop", drop);
179
+ return () => {
180
+ target.removeEventListener("dragover", over);
181
+ target.removeEventListener("drop", drop);
182
+ };
183
+ });
184
+ }
@@ -0,0 +1,29 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { RequestCard } from "./client/card";
3
+ import { SettingsScreen } from "./client/settings";
4
+ import { CARD_KIND, CARD_VERSION, CardDataSchema } from "./shared/card";
5
+ import { readDiagnostics } from "./shared/contracts";
6
+
7
+ export default function contribute(client: PluginClientContext) {
8
+ const removeRenderer = client.addTimelineRenderer({
9
+ kind: CARD_KIND,
10
+ version: CARD_VERSION,
11
+ schema: CardDataSchema,
12
+ Component: RequestCard,
13
+ });
14
+ const removeSettings = client.addSettingsScreen({ id: "main", title: "Secure input", icon: "ShieldCheck", Component: SettingsScreen });
15
+
16
+ // The daemon half only receives its API handle inside a hook or an RPC. One
17
+ // harmless call when the app loads lets it publish cards that were waiting.
18
+ // A call that throws on the spot must not fail the whole contribution.
19
+ try {
20
+ void client.rpc(readDiagnostics, {}).catch(() => undefined);
21
+ } catch {
22
+ // nothing to do: the cards are published the next time the plugin is asked for anything
23
+ }
24
+
25
+ return () => {
26
+ removeRenderer();
27
+ removeSettings();
28
+ };
29
+ }
@@ -0,0 +1,6 @@
1
+ import type { PluginServerContext } from "@getpaseo/plugin/server";
2
+ import { defaultOptions, startPlugin } from "./server/paseo/plugin";
3
+
4
+ export default function contribute(server: PluginServerContext) {
5
+ return startPlugin(server, defaultOptions()).dispose;
6
+ }