mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 12:46:55 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9614256c8 | ||
|
|
5918ff548b |
+10
@@ -84,6 +84,16 @@ For remote access, use the relay connection. It is the supported path for reachi
|
||||
|
||||
Host header validation and CORS origin checks are defense-in-depth controls for localhost exposure. They help block DNS rebinding and browser-based attacks, but they do not replace network isolation.
|
||||
|
||||
## Saved hosts in the app
|
||||
|
||||
The app saves each host that you pair: its address, server ID, daemon public key, and password. With these values, a client can find a daemon and connect to it. The app keeps them in the secret store of the platform:
|
||||
|
||||
- On iOS, in the Keychain. The entries stay on this device, and the app can read them only after the first unlock since the device started. iOS can keep Keychain entries after you uninstall the app, so remove a host in the app to delete its entry.
|
||||
- On Android, in storage encrypted with an Android Keystore key that does not leave the device. The app also turns off Android Auto Backup, so app data is not copied to Google Drive.
|
||||
- On web and desktop, in the localStorage of the browser, which is not encrypted. A browser has no secret store. On desktop, any process that runs as your OS user can read this data, as it can read `$PASEO_HOME`.
|
||||
|
||||
If an older version of the app saved hosts in AsyncStorage, the app moves them to the secret store the first time that it starts, and then deletes the old copy.
|
||||
|
||||
## DNS rebinding protection
|
||||
|
||||
CORS is not a complete security boundary. It controls which browser origins can make requests, but does not prevent a malicious website from resolving its domain to your local machine (DNS rebinding).
|
||||
|
||||
+19
-7
@@ -608,7 +608,7 @@ These small files are not validated as full Zod schemas but are persisted under
|
||||
|
||||
## Client-side stores (App)
|
||||
|
||||
These live in React Native `AsyncStorage` or browser `IndexedDB`, not on the daemon filesystem.
|
||||
These live in React Native `AsyncStorage` or browser `IndexedDB`, not on the daemon filesystem. Saved hosts are the exception: see [Saved hosts](#saved-hosts).
|
||||
|
||||
### Keying convention: directory-backed vs workspace-owned
|
||||
|
||||
@@ -657,13 +657,25 @@ source code, prompts, and tool output; encrypted-at-rest storage is a separate s
|
||||
|
||||
### Saved hosts
|
||||
|
||||
**AsyncStorage key:** `@paseo:daemon-registry`, an array of host profiles.
|
||||
**Key:** `@paseo:daemon-registry` in `credentialStorage` (`packages/app/src/storage/credential-storage`), an array of host profiles.
|
||||
|
||||
Every app build on a device shares this key, including an older build after a downgrade and a newer
|
||||
one that saves a connection kind this build doesn't know. The key holds every saved host and its
|
||||
password, so never remove it. Read each host and connection on its own, skip the ones this build
|
||||
can't read, and write them back on every save. A value that isn't a JSON array is copied to
|
||||
`@paseo:daemon-registry:unreadable` before the next save overwrites it.
|
||||
A saved host holds what a client needs to reach and sign in to a daemon: its address, server ID,
|
||||
daemon public key, and password. So the registry lives in the platform secret store: the Keychain on
|
||||
iOS, Keystore-encrypted storage on Android. Web and Electron have none and use localStorage under the
|
||||
same key. Callers see one key-value store either way; [SECURITY.md](../SECURITY.md#saved-hosts-in-the-app)
|
||||
covers what each platform protects.
|
||||
|
||||
Every app build on a device that reads this key shares it, including an older build after a
|
||||
downgrade and a newer one that saves a connection kind this build doesn't know. The key holds every
|
||||
saved host and its password, so never remove it. Read each host and connection on its own, skip the
|
||||
ones this build can't read, and write them back on every save. A value that isn't a JSON array is
|
||||
copied to `@paseo:daemon-registry:unreadable` before the next save overwrites it.
|
||||
|
||||
Builds before v0.18.3 kept the registry in AsyncStorage on iOS and Android. The first read moves it
|
||||
into the secret store, then deletes the AsyncStorage copy. When both exist, the secret store wins:
|
||||
every write goes there first, so an AsyncStorage copy is either the same value or an older one. An
|
||||
older build installed over a newer one, which TestFlight allows, finds no saved hosts, and the hosts
|
||||
it saves are dropped when the newer build starts again.
|
||||
|
||||
### Draft Store
|
||||
|
||||
|
||||
Generated
+10
@@ -21213,6 +21213,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/expo-secure-store": {
|
||||
"version": "57.0.4",
|
||||
"resolved": "https://registry.npmjs.org/expo-secure-store/-/expo-secure-store-57.0.4.tgz",
|
||||
"integrity": "sha512-7zBA1RThURTXdP4w65kBzZNbcSsfArqVd+p+ETAnPRWXO8J296Qd0YaCVyRpJ0HSwlCnGdvOnqO+NgSreHsOhA==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/expo-server": {
|
||||
"version": "57.0.3",
|
||||
"resolved": "https://registry.npmjs.org/expo-server/-/expo-server-57.0.3.tgz",
|
||||
@@ -37607,6 +37616,7 @@
|
||||
"expo-localization": "~57.0.2",
|
||||
"expo-notifications": "~57.0.23",
|
||||
"expo-router": "~57.0.28",
|
||||
"expo-secure-store": "~57.0.4",
|
||||
"expo-sharing": "~57.0.23",
|
||||
"expo-splash-screen": "~57.0.10",
|
||||
"expo-sqlite": "~57.0.4",
|
||||
|
||||
@@ -129,6 +129,8 @@ export default {
|
||||
},
|
||||
edgeToEdgeEnabled: true,
|
||||
predictiveBackGestureEnabled: false,
|
||||
// Keep app data, such as cached agent timelines, out of the user's Google Drive backup.
|
||||
allowBackup: false,
|
||||
softwareKeyboardLayoutMode: "resize",
|
||||
// Allow HTTP connections for local network hosts (required for release builds)
|
||||
usesCleartextTraffic: true,
|
||||
|
||||
@@ -82,6 +82,12 @@ describe("Android app config", () => {
|
||||
30_000,
|
||||
);
|
||||
|
||||
// Auto Backup would upload app storage, including AsyncStorage, to the user's cloud backup.
|
||||
it("opts out of Android Auto Backup", async () => {
|
||||
const manifest = await resolveAndroidManifest();
|
||||
expect(manifest.application[0].$["android:allowBackup"]).toBe("false");
|
||||
}, 30_000);
|
||||
|
||||
// Without it, a dark device paints AppCompat's #303030 between the splash and the first screen.
|
||||
it("paints the app window in the splash colour", async () => {
|
||||
const appTheme = await resolveAndroidAppThemeItems();
|
||||
|
||||
@@ -103,6 +103,7 @@
|
||||
"expo-localization": "~57.0.2",
|
||||
"expo-notifications": "~57.0.23",
|
||||
"expo-router": "~57.0.28",
|
||||
"expo-secure-store": "~57.0.4",
|
||||
"expo-sharing": "~57.0.23",
|
||||
"expo-splash-screen": "~57.0.10",
|
||||
"expo-sqlite": "~57.0.4",
|
||||
|
||||
@@ -586,7 +586,7 @@ function createPairingStore(
|
||||
});
|
||||
};
|
||||
return new HostRuntimeStore({
|
||||
storage: input.storage ?? createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(input.storage),
|
||||
deps: {
|
||||
createClient: ({ host, connection }) => {
|
||||
recordRelayDial(host, connection);
|
||||
@@ -625,6 +625,14 @@ function createMemoryHostRuntimeStorage(entries: Record<string, string> = {}): H
|
||||
};
|
||||
}
|
||||
|
||||
/** Plain and credential storage over one map, for tests that don't tell the two apart. */
|
||||
function oneStorage(storage: HostRuntimeStorage = createMemoryHostRuntimeStorage()): {
|
||||
storage: HostRuntimeStorage;
|
||||
credentialStorage: HostRuntimeStorage;
|
||||
} {
|
||||
return { storage, credentialStorage: storage };
|
||||
}
|
||||
|
||||
function createMemoryReplicaRowStore(): ReplicaRowStore {
|
||||
const rows = new Map<string, ReplicaRow>();
|
||||
const keyOf = (row: Pick<ReplicaRow, "serverId" | "kind" | "id">) =>
|
||||
@@ -671,7 +679,7 @@ function createMemoryReplicaRowStore(): ReplicaRowStore {
|
||||
|
||||
function createAppearanceStore(storage: HostRuntimeStorage): HostRuntimeStore {
|
||||
return new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
deps: {
|
||||
createClient: () => {
|
||||
throw new Error("createClient should not be called");
|
||||
@@ -2295,7 +2303,7 @@ describe("HostRuntimeController", () => {
|
||||
[relayAlternate.id]: 320,
|
||||
};
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: makeDeps(latencies, clients),
|
||||
});
|
||||
const queryKey = checkoutStatusQueryKey(host.serverId, "/repo");
|
||||
@@ -2807,13 +2815,13 @@ const storedWithUnreadableEntries = [
|
||||
async function bootWithRegistry(registry: string): Promise<{
|
||||
store: HostRuntimeStore;
|
||||
storage: HostRuntimeStorage;
|
||||
plainStorage: HostRuntimeStorage;
|
||||
}> {
|
||||
const storage = createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: registry,
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const plainStorage = createMemoryHostRuntimeStorage({ "@paseo:e2e": "1" });
|
||||
const storage = createMemoryHostRuntimeStorage({ [REGISTRY_KEY]: registry });
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
storage: plainStorage,
|
||||
credentialStorage: storage,
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => ({
|
||||
@@ -2826,7 +2834,7 @@ async function bootWithRegistry(registry: string): Promise<{
|
||||
revokePushNotifications: async () => undefined,
|
||||
});
|
||||
await store.boot();
|
||||
return { store, storage };
|
||||
return { store, storage, plainStorage };
|
||||
}
|
||||
|
||||
async function readRegistry(storage: HostRuntimeStorage): Promise<unknown> {
|
||||
@@ -2895,10 +2903,12 @@ describe("HostRuntimeStore", () => {
|
||||
}),
|
||||
];
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage({
|
||||
"@paseo:e2e": "1",
|
||||
"@paseo:daemon-registry": JSON.stringify(hosts),
|
||||
}),
|
||||
...oneStorage(
|
||||
createMemoryHostRuntimeStorage({
|
||||
"@paseo:e2e": "1",
|
||||
"@paseo:daemon-registry": JSON.stringify(hosts),
|
||||
}),
|
||||
),
|
||||
deps: {
|
||||
getClientId: async () => "gateway-recovery",
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
@@ -2984,7 +2994,7 @@ describe("HostRuntimeStore", () => {
|
||||
origin.connectedHosts = true;
|
||||
origin.hostDirectory = directory.promise;
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: ({ host }) =>
|
||||
(host.serverId === "srv_a"
|
||||
@@ -3098,7 +3108,7 @@ describe("HostRuntimeStore", () => {
|
||||
clientA.setConnectionState({ status: "connected" });
|
||||
clientB.setConnectionState({ status: "connected" });
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => {
|
||||
throw new Error("initial clients are supplied");
|
||||
@@ -3178,7 +3188,7 @@ describe("HostRuntimeStore", () => {
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
deps: makeDeps({}, []),
|
||||
revokePushNotifications: async ({ serverId }) => {
|
||||
expect(serverId).toBe(host.serverId);
|
||||
@@ -3204,7 +3214,7 @@ describe("HostRuntimeStore", () => {
|
||||
"@paseo:e2e": "1",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
deps: makeDeps({}, []),
|
||||
revokePushNotifications: async ({ serverId }) => {
|
||||
revokedServerIds.push(serverId);
|
||||
@@ -3235,7 +3245,7 @@ describe("HostRuntimeStore", () => {
|
||||
const session = useSessionStore.getState();
|
||||
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
replicaRowStore,
|
||||
deps: {
|
||||
createClient: () => {
|
||||
@@ -3279,7 +3289,7 @@ describe("HostRuntimeStore", () => {
|
||||
},
|
||||
};
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
replicaRowStore,
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
@@ -3313,10 +3323,12 @@ describe("HostRuntimeStore", () => {
|
||||
const fakeClient = new FakeDaemonClient();
|
||||
fakeClient.setConnectionState({ status: "connected" });
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: JSON.stringify([host]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
...oneStorage(
|
||||
createMemoryHostRuntimeStorage({
|
||||
[REGISTRY_KEY]: JSON.stringify([host]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
),
|
||||
deps: {
|
||||
createClient: () => fakeClient as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: hostProfile }) => ({
|
||||
@@ -3415,6 +3427,33 @@ describe("HostRuntimeStore", () => {
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("keeps saved hosts, passwords and daemon keys in credential storage only", async () => {
|
||||
const relay: HostConnection = {
|
||||
id: "relay:relay.paseo.sh:443",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
daemonPublicKeyB64: "pk_saved_daemon",
|
||||
};
|
||||
const { store, storage, plainStorage } = await bootWithRegistry(
|
||||
JSON.stringify([makeHost({ serverId: "srv_relay", connections: [relay] })]),
|
||||
);
|
||||
expect(store.getHosts().map((host) => host.serverId)).toEqual(["srv_relay"]);
|
||||
|
||||
await store.setHostPassword("srv_relay", "relay-secret");
|
||||
|
||||
expect(await readRegistry(storage)).toMatchObject([
|
||||
{
|
||||
serverId: "srv_relay",
|
||||
password: "relay-secret",
|
||||
connections: [{ daemonPublicKeyB64: "pk_saved_daemon" }],
|
||||
},
|
||||
]);
|
||||
expect(await plainStorage.getItem(REGISTRY_KEY)).toBeNull();
|
||||
expect(await plainStorage.getItem(`${REGISTRY_KEY}:unreadable`)).toBeNull();
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("forgets an entry it can't read once that host is paired again and removed", async () => {
|
||||
const { store, storage } = await bootWithRegistry(
|
||||
JSON.stringify([{ serverId: "srv_future", connections: [futureConnection] }]),
|
||||
@@ -4689,7 +4728,7 @@ describe("HostRuntimeStore", () => {
|
||||
}),
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
},
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -5344,10 +5383,12 @@ describe("HostRuntimeStore", () => {
|
||||
],
|
||||
});
|
||||
const store = createPairingStore({
|
||||
storage: createMemoryHostRuntimeStorage({
|
||||
"@paseo:daemon-registry": JSON.stringify([savedHost]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
...oneStorage(
|
||||
createMemoryHostRuntimeStorage({
|
||||
"@paseo:daemon-registry": JSON.stringify([savedHost]),
|
||||
"@paseo:e2e": "1",
|
||||
}),
|
||||
),
|
||||
});
|
||||
const requests = answerHostConfirmations(store, true);
|
||||
|
||||
@@ -5494,7 +5535,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
finishDesktopStart = resolve;
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
@@ -5536,7 +5577,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await storage.setItem("@paseo:daemon-registry", JSON.stringify([host]));
|
||||
const credentialRequests: string[] = [];
|
||||
const store = new HostRuntimeStore({
|
||||
storage,
|
||||
...oneStorage(storage),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: probeHost, connection }) => {
|
||||
@@ -5574,7 +5615,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
connections: [{ id: "direct:lan:6767", type: "directTcp", endpoint: "lan:6767" }],
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => client as unknown as DaemonClient,
|
||||
connectToDaemon: async () => ({
|
||||
@@ -5628,7 +5669,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
});
|
||||
const probeAttempts: string[] = [];
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ connection }) => {
|
||||
@@ -5679,7 +5720,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
it("keeps five rejected hosts red with independent password errors", async () => {
|
||||
let probeAttempts = 0;
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
@@ -5710,7 +5751,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
});
|
||||
it("imports a deep link without waiting for admission, then leaves a rejected saved host red", async () => {
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
@@ -5739,7 +5780,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
const firstProbe = createDeferred<void>();
|
||||
let connectCalls = 0;
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => {
|
||||
@@ -5768,7 +5809,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
|
||||
it("saves and reconnects a rejected saved host after changing its password", async () => {
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host }) => {
|
||||
@@ -5820,7 +5861,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
useTls: true,
|
||||
}),
|
||||
},
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
});
|
||||
|
||||
const hostAdded = onceHostListMatches(store, () => store.getHosts().length > 0);
|
||||
@@ -5855,7 +5896,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
getClientId: async () => "cid_test_runtime",
|
||||
readInitialConnectionHint: () => null,
|
||||
},
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
...oneStorage(createMemoryHostRuntimeStorage()),
|
||||
});
|
||||
|
||||
(globalThis as { window?: unknown }).window = {
|
||||
|
||||
@@ -50,6 +50,7 @@ import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { credentialStorage } from "@/storage/credential-storage";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
import {
|
||||
selectBestConnection,
|
||||
@@ -1925,17 +1926,21 @@ export class HostRuntimeStore {
|
||||
private registryLoad: Promise<void> | null = null;
|
||||
private readonly hostConfirmations = new HostConfirmations();
|
||||
private storage: HostRuntimeStorage;
|
||||
// Saved hosts carry passwords and daemon keys, so the registry never goes to plain storage.
|
||||
private credentialStorage: HostRuntimeStorage;
|
||||
private replicaCache: ReplicaCache;
|
||||
private readonly revokePushNotifications: typeof revokePushNotifications;
|
||||
|
||||
constructor(input?: {
|
||||
deps?: HostRuntimeControllerDeps;
|
||||
storage?: HostRuntimeStorage;
|
||||
credentialStorage?: HostRuntimeStorage;
|
||||
replicaRowStore?: ReplicaRowStore;
|
||||
revokePushNotifications?: typeof revokePushNotifications;
|
||||
}) {
|
||||
this.deps = input?.deps ?? createDefaultDeps((serverId) => this.getClient(serverId));
|
||||
this.storage = input?.storage ?? AsyncStorage;
|
||||
this.credentialStorage = input?.credentialStorage ?? credentialStorage;
|
||||
this.replicaCache = new ReplicaCache(input?.replicaRowStore ?? createReplicaRowStore());
|
||||
this.revokePushNotifications = input?.revokePushNotifications ?? revokePushNotifications;
|
||||
}
|
||||
@@ -2635,7 +2640,7 @@ export class HostRuntimeStore {
|
||||
}
|
||||
|
||||
private async persistHosts(hosts = this.hosts): Promise<void> {
|
||||
await this.storage.setItem(
|
||||
await this.credentialStorage.setItem(
|
||||
REGISTRY_STORAGE_KEY,
|
||||
JSON.stringify(writeHostRegistry(hosts, this.unreadableHosts)),
|
||||
);
|
||||
@@ -2646,7 +2651,7 @@ export class HostRuntimeStore {
|
||||
* `<key>:unreadable` first, because the next save overwrites the key.
|
||||
*/
|
||||
private async readStoredRegistry(): Promise<unknown[] | null> {
|
||||
const raw = await this.storage.getItem(REGISTRY_STORAGE_KEY);
|
||||
const raw = await this.credentialStorage.getItem(REGISTRY_STORAGE_KEY);
|
||||
if (raw === null) return null;
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
@@ -2654,7 +2659,7 @@ export class HostRuntimeStore {
|
||||
} catch {
|
||||
// Not JSON: copied aside below.
|
||||
}
|
||||
await this.storage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
|
||||
await this.credentialStorage.setItem(`${REGISTRY_STORAGE_KEY}:unreadable`, raw);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createCredentialStorage } from "./internal/credential-storage";
|
||||
|
||||
class MemoryStore {
|
||||
readonly values: Map<string, string>;
|
||||
refuseReads = false;
|
||||
refuseWrites = false;
|
||||
|
||||
constructor(entries: Record<string, string> = {}) {
|
||||
this.values = new Map(Object.entries(entries));
|
||||
}
|
||||
|
||||
async getItem(key: string): Promise<string | null> {
|
||||
if (this.refuseReads) throw new Error("vault unavailable");
|
||||
return this.values.get(key) ?? null;
|
||||
}
|
||||
|
||||
async setItem(key: string, value: string): Promise<void> {
|
||||
if (this.refuseWrites) throw new Error("vault unavailable");
|
||||
this.values.set(key, value);
|
||||
}
|
||||
|
||||
async removeItem(key: string): Promise<void> {
|
||||
this.values.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
const KEY = "@paseo:daemon-registry";
|
||||
|
||||
function setup(input: { vault?: Record<string, string>; plain?: Record<string, string> } = {}) {
|
||||
const vault = new MemoryStore(input.vault);
|
||||
const plainStorage = new MemoryStore(input.plain);
|
||||
const storage = createCredentialStorage({ vault, plainStorage });
|
||||
return { vault, plainStorage, storage };
|
||||
}
|
||||
|
||||
describe("credential storage", () => {
|
||||
it("writes values to the vault and never to plain storage", async () => {
|
||||
const { vault, plainStorage, storage } = setup();
|
||||
|
||||
await storage.setItem(KEY, "secret");
|
||||
|
||||
expect(await storage.getItem(KEY)).toBe("secret");
|
||||
expect(vault.values.get(KEY)).toBe("secret");
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
|
||||
it("moves a value an older build left in plain storage into the vault", async () => {
|
||||
const { vault, plainStorage, storage } = setup({ plain: { [KEY]: "legacy" } });
|
||||
|
||||
expect(await storage.getItem(KEY)).toBe("legacy");
|
||||
|
||||
expect(vault.values.get(KEY)).toBe("legacy");
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
|
||||
it("finishes a move that stopped after the vault write", async () => {
|
||||
const { vault, plainStorage, storage } = setup({
|
||||
vault: { [KEY]: "legacy" },
|
||||
plain: { [KEY]: "legacy" },
|
||||
});
|
||||
|
||||
expect(await storage.getItem(KEY)).toBe("legacy");
|
||||
|
||||
expect(vault.values.get(KEY)).toBe("legacy");
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the vault value over a plain copy a write did not get to remove", async () => {
|
||||
const { plainStorage, storage } = setup({
|
||||
vault: { [KEY]: "newer" },
|
||||
plain: { [KEY]: "older" },
|
||||
});
|
||||
|
||||
expect(await storage.getItem(KEY)).toBe("newer");
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a plain value readable while the vault refuses it, and moves it once the vault works", async () => {
|
||||
const vault = new MemoryStore();
|
||||
const plainStorage = new MemoryStore({ [KEY]: "legacy" });
|
||||
vault.refuseWrites = true;
|
||||
|
||||
const firstLaunch = createCredentialStorage({ vault, plainStorage });
|
||||
expect(await firstLaunch.getItem(KEY)).toBe("legacy");
|
||||
expect(plainStorage.values.get(KEY)).toBe("legacy");
|
||||
|
||||
vault.refuseWrites = false;
|
||||
const nextLaunch = createCredentialStorage({ vault, plainStorage });
|
||||
expect(await nextLaunch.getItem(KEY)).toBe("legacy");
|
||||
expect(vault.values.get(KEY)).toBe("legacy");
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a plain value readable while the vault cannot be read", async () => {
|
||||
const { vault, plainStorage, storage } = setup({ plain: { [KEY]: "legacy" } });
|
||||
vault.refuseReads = true;
|
||||
|
||||
expect(await storage.getItem(KEY)).toBe("legacy");
|
||||
expect(plainStorage.values.get(KEY)).toBe("legacy");
|
||||
});
|
||||
|
||||
it("fails a read the vault refuses when plain storage has no value", async () => {
|
||||
const { vault, storage } = setup();
|
||||
vault.refuseReads = true;
|
||||
|
||||
await expect(storage.getItem(KEY)).rejects.toThrow("vault unavailable");
|
||||
});
|
||||
|
||||
it("fails a write the vault refuses instead of writing to plain storage", async () => {
|
||||
const { vault, plainStorage, storage } = setup();
|
||||
vault.refuseWrites = true;
|
||||
|
||||
await expect(storage.setItem(KEY, "secret")).rejects.toThrow("vault unavailable");
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not let a first read overwrite a write that started meanwhile", async () => {
|
||||
const { vault, storage } = setup({ plain: { [KEY]: "legacy" } });
|
||||
|
||||
await Promise.all([storage.getItem(KEY), storage.setItem(KEY, "fresh")]);
|
||||
|
||||
expect(await storage.getItem(KEY)).toBe("fresh");
|
||||
expect(vault.values.get(KEY)).toBe("fresh");
|
||||
});
|
||||
|
||||
it("removes a value from the vault and from plain storage", async () => {
|
||||
const { vault, plainStorage, storage } = setup({
|
||||
vault: { [KEY]: "secret" },
|
||||
plain: { [KEY]: "legacy" },
|
||||
});
|
||||
|
||||
await storage.removeItem(KEY);
|
||||
|
||||
expect(await storage.getItem(KEY)).toBeNull();
|
||||
expect(vault.values.has(KEY)).toBe(false);
|
||||
expect(plainStorage.values.has(KEY)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { type CredentialStorage, createCredentialStorage } from "./internal/credential-storage";
|
||||
import { secureStoreVault } from "./internal/secure-store-vault";
|
||||
|
||||
export type { CredentialStorage };
|
||||
|
||||
/**
|
||||
* Key-value storage for secrets: the iOS Keychain or the Android Keystore. A value an older build
|
||||
* wrote to AsyncStorage under the same key moves in on its first read.
|
||||
*/
|
||||
// COMPAT(plainCredentialStorage): added in v0.18.3, remove after 2027-06-01; then export the vault.
|
||||
export const credentialStorage: CredentialStorage = createCredentialStorage({
|
||||
vault: secureStoreVault,
|
||||
plainStorage: AsyncStorage,
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import type { CredentialStorage } from "./internal/credential-storage";
|
||||
|
||||
export type { CredentialStorage };
|
||||
|
||||
/**
|
||||
* Key-value storage for secrets. A browser, and the Electron renderer, has no secret store, so
|
||||
* values live in localStorage under the same key as before. SECURITY.md covers why.
|
||||
*/
|
||||
export const credentialStorage: CredentialStorage = AsyncStorage;
|
||||
@@ -0,0 +1,72 @@
|
||||
export interface CredentialStorage {
|
||||
getItem(key: string): Promise<string | null>;
|
||||
setItem(key: string, value: string): Promise<void>;
|
||||
removeItem(key: string): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores values in `vault` and moves in any value an older build left in `plainStorage`.
|
||||
*
|
||||
* The vault copy wins whenever both exist: this build writes the vault first and removes the
|
||||
* plain copy second, so a plain copy next to a vault copy is either the same value (a move that
|
||||
* stopped before its scrub) or an older one (a write that stopped before its scrub). A plain copy
|
||||
* stays put until the vault holds the value, so no step of a move can lose it, and it stays
|
||||
* readable while the vault cannot be read.
|
||||
*/
|
||||
export function createCredentialStorage(input: {
|
||||
vault: CredentialStorage;
|
||||
plainStorage: CredentialStorage;
|
||||
}): CredentialStorage {
|
||||
const { vault, plainStorage } = input;
|
||||
let tail: Promise<unknown> = Promise.resolve();
|
||||
|
||||
// A read that moves a plain value writes the vault, so operations run one at a time.
|
||||
function inOrder<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const result = tail.then(operation);
|
||||
tail = result.catch(() => undefined);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function moveIntoVault(key: string, value: string): Promise<void> {
|
||||
try {
|
||||
await vault.setItem(key, value);
|
||||
} catch (error) {
|
||||
// The plain copy stays readable and the next launch tries again.
|
||||
console.warn("[CredentialStorage] Failed to move a stored value into the vault", error);
|
||||
return;
|
||||
}
|
||||
await plainStorage.removeItem(key);
|
||||
}
|
||||
|
||||
return {
|
||||
getItem: (key) =>
|
||||
inOrder(async () => {
|
||||
const plain = await plainStorage.getItem(key);
|
||||
let stored: string | null;
|
||||
try {
|
||||
stored = await vault.getItem(key);
|
||||
} catch (error) {
|
||||
if (plain === null) throw error;
|
||||
// The plain copy has not moved yet, so it stays readable while the vault is unavailable.
|
||||
console.warn("[CredentialStorage] Failed to read the vault", error);
|
||||
return plain;
|
||||
}
|
||||
if (stored !== null) {
|
||||
if (plain !== null) await plainStorage.removeItem(key);
|
||||
return stored;
|
||||
}
|
||||
if (plain !== null) await moveIntoVault(key, plain);
|
||||
return plain;
|
||||
}),
|
||||
setItem: (key, value) =>
|
||||
inOrder(async () => {
|
||||
await vault.setItem(key, value);
|
||||
await plainStorage.removeItem(key);
|
||||
}),
|
||||
removeItem: (key) =>
|
||||
inOrder(async () => {
|
||||
await vault.removeItem(key);
|
||||
await plainStorage.removeItem(key);
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
import type { CredentialStorage } from "./credential-storage";
|
||||
|
||||
// Readable after the first unlock so background work can reconnect; never restored to another device.
|
||||
const OPTIONS: SecureStore.SecureStoreOptions = {
|
||||
keychainAccessible: SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
|
||||
};
|
||||
|
||||
/**
|
||||
* SecureStore accepts only `[A-Za-z0-9._-]` in keys. Every other character, and `_` itself,
|
||||
* becomes `_` plus four hex digits, so distinct keys stay distinct.
|
||||
*/
|
||||
export function toVaultKey(key: string): string {
|
||||
return key.replace(
|
||||
/[^A-Za-z0-9.-]/g,
|
||||
(char) => `_${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** The iOS Keychain or the Android Keystore, through expo-secure-store. */
|
||||
export const secureStoreVault: CredentialStorage = {
|
||||
getItem: (key) => SecureStore.getItemAsync(toVaultKey(key), OPTIONS),
|
||||
setItem: (key, value) => SecureStore.setItemAsync(toVaultKey(key), value, OPTIONS),
|
||||
removeItem: (key) => SecureStore.deleteItemAsync(toVaultKey(key), OPTIONS),
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { toVaultKey } from "./internal/secure-store-vault";
|
||||
|
||||
describe("secure store vault keys", () => {
|
||||
it("turns any storage key into a key SecureStore accepts", () => {
|
||||
expect(toVaultKey("@paseo:daemon-registry")).toMatch(/^[\w.-]+$/);
|
||||
expect(toVaultKey("@paseo:daemon-registry:unreadable")).toMatch(/^[\w.-]+$/);
|
||||
});
|
||||
|
||||
it("keeps distinct storage keys distinct", () => {
|
||||
const keys = ["a:b", "a_b", "a_003ab", "a.b", "a-b", "ab"];
|
||||
expect(new Set(keys.map(toVaultKey)).size).toBe(keys.length);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user