@evolustr/client 0.0.0-stage → 0.1.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.
package/src/cache.ts ADDED
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Device cache for the unlocked secrets of one (pubkey, appId) (SPEC §6.2 rule 6).
3
+ * Evolu needs S on every start; R is optional.
4
+ */
5
+ import { type Bytes, fromBase64Url, sha256Hex, toBase64Url } from "@evolustr/core";
6
+
7
+ export interface CachedSecrets {
8
+ readonly s: Bytes;
9
+ readonly r?: Bytes;
10
+ }
11
+
12
+ export interface SecretCache {
13
+ readonly get: (pubkey: string, appId: string) => Promise<CachedSecrets | null>;
14
+ readonly set: (pubkey: string, appId: string, secrets: CachedSecrets) => Promise<void>;
15
+ readonly remove: (pubkey: string, appId: string) => Promise<void>;
16
+ }
17
+
18
+ const cacheKey = (pubkey: string, appId: string) => `evolustr:secrets:${sha256Hex(`${pubkey}|${appId}`)}`;
19
+
20
+ interface KeyValue {
21
+ readonly getItem: (k: string) => string | null;
22
+ readonly setItem: (k: string, v: string) => void;
23
+ readonly removeItem: (k: string) => void;
24
+ }
25
+
26
+ const encode = (c: CachedSecrets) =>
27
+ JSON.stringify({ s: toBase64Url(c.s), ...(c.r === undefined ? {} : { r: toBase64Url(c.r) }) });
28
+
29
+ const decode = (text: string | null): CachedSecrets | null => {
30
+ if (text === null) return null;
31
+ try {
32
+ const data = JSON.parse(text) as { s?: unknown; r?: unknown };
33
+ const s = typeof data.s === "string" ? fromBase64Url(data.s) : null;
34
+ const r = typeof data.r === "string" ? fromBase64Url(data.r) : null;
35
+ if (s === null) return null;
36
+ return r === null ? { s } : { s, r };
37
+ } catch {
38
+ return null;
39
+ }
40
+ };
41
+
42
+ /** A cache over any `localStorage`-like store. Failing storage acts as empty. */
43
+ export const keyValueCache = (store: KeyValue): SecretCache => ({
44
+ get: async (pubkey, appId) => {
45
+ try {
46
+ return decode(store.getItem(cacheKey(pubkey, appId)));
47
+ } catch {
48
+ return null;
49
+ }
50
+ },
51
+ set: async (pubkey, appId, secrets) => {
52
+ try {
53
+ store.setItem(cacheKey(pubkey, appId), encode(secrets));
54
+ } catch {
55
+ /* storage unavailable: the user unlocks again next time */
56
+ }
57
+ },
58
+ remove: async (pubkey, appId) => {
59
+ try {
60
+ store.removeItem(cacheKey(pubkey, appId));
61
+ } catch {
62
+ /* ignore */
63
+ }
64
+ },
65
+ });
66
+
67
+ export const memoryCache = (): SecretCache => {
68
+ const map = new Map<string, string>();
69
+ return keyValueCache({
70
+ getItem: (k) => map.get(k) ?? null,
71
+ setItem: (k, v) => void map.set(k, v),
72
+ removeItem: (k) => void map.delete(k),
73
+ });
74
+ };
75
+
76
+ /** An async key-value store, e.g. `expo-secure-store` (getItemAsync / setItemAsync / deleteItemAsync). */
77
+ export interface AsyncKeyValue {
78
+ readonly getItemAsync: (key: string) => Promise<string | null>;
79
+ readonly setItemAsync: (key: string, value: string) => Promise<void>;
80
+ readonly deleteItemAsync: (key: string) => Promise<void>;
81
+ }
82
+
83
+ /**
84
+ * A cache over an async store. Keys use only letters, digits, "." "-" "_",
85
+ * which secure stores such as `expo-secure-store` require.
86
+ */
87
+ export const asyncKeyValueCache = (store: AsyncKeyValue): SecretCache => {
88
+ const key = (pubkey: string, appId: string) => `evolustr_secrets_${sha256Hex(`${pubkey}|${appId}`)}`;
89
+ return {
90
+ get: async (pubkey, appId) => {
91
+ try {
92
+ return decode(await store.getItemAsync(key(pubkey, appId)));
93
+ } catch {
94
+ return null;
95
+ }
96
+ },
97
+ set: async (pubkey, appId, secrets) => {
98
+ try {
99
+ await store.setItemAsync(key(pubkey, appId), encode(secrets));
100
+ } catch {
101
+ /* unavailable: unlock again next time */
102
+ }
103
+ },
104
+ remove: async (pubkey, appId) => {
105
+ try {
106
+ await store.deleteItemAsync(key(pubkey, appId));
107
+ } catch {
108
+ /* ignore */
109
+ }
110
+ },
111
+ };
112
+ };
113
+
114
+ /** Where an encrypted cache keeps its key: a non-extractable WebCrypto key. */
115
+ export interface CryptoKeyStore {
116
+ readonly get: () => Promise<CryptoKey | null>;
117
+ readonly set: (key: CryptoKey) => Promise<void>;
118
+ }
119
+
120
+ /** Keeps the key in IndexedDB, which can store a CryptoKey without exposing its bytes. */
121
+ export const indexedDbKeyStore = (dbName = "evolustr-keys"): CryptoKeyStore => {
122
+ const open = () =>
123
+ new Promise<IDBDatabase>((resolve, reject) => {
124
+ const req = indexedDB.open(dbName, 1);
125
+ req.onupgradeneeded = () => req.result.createObjectStore("keys");
126
+ req.onsuccess = () => resolve(req.result);
127
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB unavailable"));
128
+ });
129
+ const tx = async <T>(mode: IDBTransactionMode, f: (s: IDBObjectStore) => IDBRequest<T>) => {
130
+ const db = await open();
131
+ return new Promise<T>((resolve, reject) => {
132
+ const req = f(db.transaction("keys", mode).objectStore("keys"));
133
+ req.onsuccess = () => resolve(req.result);
134
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB error"));
135
+ }).finally(() => db.close());
136
+ };
137
+ return {
138
+ get: async () => ((await tx("readonly", (s) => s.get("cache"))) as CryptoKey | undefined) ?? null,
139
+ set: async (key) => void (await tx("readwrite", (s) => s.put(key, "cache"))),
140
+ };
141
+ };
142
+
143
+ export const memoryKeyStore = (): CryptoKeyStore => {
144
+ let key: CryptoKey | null = null;
145
+ return { get: async () => key, set: async (k) => void (key = k) };
146
+ };
147
+
148
+ /**
149
+ * A cache whose entries are encrypted with a non-extractable AES-GCM key (#27).
150
+ * It doesn't stop script running on the app's origin (an XSS can still ask for
151
+ * decryption), but plain reads of storage, backups or the browser profile only
152
+ * get ciphertext. Failures act as an empty cache.
153
+ */
154
+ export const encryptedCache = (
155
+ store: KeyValue,
156
+ keyStore: CryptoKeyStore,
157
+ subtle: SubtleCrypto = globalThis.crypto.subtle,
158
+ ): SecretCache => {
159
+ let keyPromise: Promise<CryptoKey> | null = null;
160
+ const key = (): Promise<CryptoKey> =>
161
+ (keyPromise ??= (async () => {
162
+ const existing = await keyStore.get();
163
+ if (existing !== null) return existing;
164
+ const fresh = await subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
165
+ await keyStore.set(fresh);
166
+ return fresh;
167
+ })());
168
+ const enc = new TextEncoder();
169
+ const dec = new TextDecoder();
170
+ return {
171
+ get: async (pubkey, appId) => {
172
+ try {
173
+ const raw = store.getItem(cacheKey(pubkey, appId));
174
+ if (raw === null) return null;
175
+ const { iv, ct } = JSON.parse(raw) as { iv: string; ct: string };
176
+ const ivBytes = fromBase64Url(iv);
177
+ const ctBytes = fromBase64Url(ct);
178
+ if (ivBytes === null || ctBytes === null) return null;
179
+ // The slot name is the AAD: an entry copied to another slot doesn't decrypt (#44).
180
+ const plain = await subtle.decrypt(
181
+ { name: "AES-GCM", iv: new Uint8Array(ivBytes), additionalData: enc.encode(cacheKey(pubkey, appId)) },
182
+ await key(),
183
+ new Uint8Array(ctBytes),
184
+ );
185
+ return decode(dec.decode(plain));
186
+ } catch {
187
+ return null;
188
+ }
189
+ },
190
+ set: async (pubkey, appId, secrets) => {
191
+ try {
192
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
193
+ const ct = await subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(cacheKey(pubkey, appId)) }, await key(), enc.encode(encode(secrets)));
194
+ store.setItem(cacheKey(pubkey, appId), JSON.stringify({ iv: toBase64Url(iv), ct: toBase64Url(new Uint8Array(ct)) }));
195
+ } catch {
196
+ /* unavailable: unlock again next time */
197
+ }
198
+ },
199
+ remove: async (pubkey, appId) => {
200
+ try {
201
+ store.removeItem(cacheKey(pubkey, appId));
202
+ } catch {
203
+ /* ignore */
204
+ }
205
+ },
206
+ };
207
+ };
208
+
209
+ /** The recommended web cache: localStorage entries encrypted with a key kept in IndexedDB. */
210
+ export const webSecretCache = (): SecretCache => encryptedCache(globalThis.localStorage, indexedDbKeyStore());
package/src/capable.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Talking to an Evolustr-capable signer from the app (SPEC §5.1, §5.4).
3
+ */
4
+ import { type Bytes, fromBase64Url, randomBytes, toHex } from "@evolustr/core";
5
+
6
+ export interface SignerCapabilities {
7
+ readonly identity: "verified" | "connection";
8
+ readonly appId: string;
9
+ readonly signerId: string | null;
10
+ readonly ready: boolean;
11
+ readonly signerPasskey: boolean;
12
+ /** M can be recovered on another device (#42). Older signers don't send it: counts as false. */
13
+ readonly recoverable?: boolean;
14
+ /** The signer's key is protected by the nsec, so nsec holders can open strict data (#43). */
15
+ readonly nsecProtected?: boolean;
16
+ /**
17
+ * The nsec could open the signer's key now or did before, e.g. it moved to a
18
+ * passkey without a new key: nsec holders may still open strict data (#52).
19
+ */
20
+ readonly nsecExposed?: boolean;
21
+ /**
22
+ * The signer replaced its key (#52 phase B): this app's signer id under the
23
+ * previous key. Its wrap in the vault still opens R, which may be exposed.
24
+ */
25
+ readonly previousSignerId?: string | null;
26
+ /**
27
+ * Every earlier key's signer id for this app, newest first (#58), when the
28
+ * signer replaced its key more than once. Older signers send only
29
+ * `previousSignerId`.
30
+ */
31
+ readonly previousSignerIds?: ReadonlyArray<string>;
32
+ }
33
+
34
+ /** The signer ids of the signer's earlier keys, newest first: the list, or the single id older signers send (#58). */
35
+ export const earlierSignerIds = (c: SignerCapabilities): ReadonlyArray<string> =>
36
+ c.previousSignerIds !== undefined && c.previousSignerIds.length > 0
37
+ ? c.previousSignerIds
38
+ : c.previousSignerId == null
39
+ ? []
40
+ : [c.previousSignerId];
41
+
42
+ export interface CapableSigner {
43
+ readonly capabilities: () => Promise<SignerCapabilities>;
44
+ /** May wait for the user to click inside the signer; don't use short timeouts. */
45
+ readonly getWrapKey: () => Promise<Bytes>;
46
+ /**
47
+ * The app key under the signer's earlier key whose signer id is `signerId`
48
+ * (#58), else its previous key, after a key rotation (#52 phase B).
49
+ */
50
+ readonly getPreviousWrapKey?: (signerId?: string) => Promise<Bytes>;
51
+ readonly enrollPasskey?: () => Promise<void>;
52
+ }
53
+
54
+ const toKey = (v: unknown): Bytes => {
55
+ if (v instanceof Uint8Array) return v;
56
+ if (typeof v === "string") {
57
+ const b = fromBase64Url(v);
58
+ if (b !== null && b.length === 32) return b;
59
+ }
60
+ throw new Error("The signer returned an invalid key");
61
+ };
62
+
63
+ /** The NIP-07 namespace `window.nostr.evolustr`, if present. */
64
+ export interface Nip07Evolustr {
65
+ readonly capabilities: () => Promise<SignerCapabilities>;
66
+ readonly getWrapKey: () => Promise<string | Uint8Array>;
67
+ readonly getPreviousWrapKey?: (signerId?: string) => Promise<string | Uint8Array>;
68
+ readonly enrollPasskey?: () => Promise<void>;
69
+ }
70
+
71
+ export const nip07CapableSigner = (ns: Nip07Evolustr): CapableSigner => ({
72
+ capabilities: () => ns.capabilities(),
73
+ getWrapKey: async () => toKey(await ns.getWrapKey()),
74
+ ...(ns.getPreviousWrapKey === undefined ? {} : { getPreviousWrapKey: async (signerId?: string) => toKey(await ns.getPreviousWrapKey!(signerId)) }),
75
+ ...(ns.enrollPasskey === undefined ? {} : { enrollPasskey: () => ns.enrollPasskey!() }),
76
+ });
77
+
78
+ /** Detects `window.nostr.evolustr`; undefined for standard signers. */
79
+ export const detectCapableSigner = (nostr: unknown): CapableSigner | undefined => {
80
+ const ns = (nostr as { evolustr?: Partial<Nip07Evolustr> } | undefined)?.evolustr;
81
+ return typeof ns?.capabilities === "function" && typeof ns.getWrapKey === "function"
82
+ ? nip07CapableSigner(ns as Nip07Evolustr)
83
+ : undefined;
84
+ };
85
+
86
+ /**
87
+ * Forwards calls to an iframe signer with postMessage. Used by bridge scripts
88
+ * to implement `window.nostr.evolustr` (see {@link exposeOnWindowNostr}).
89
+ */
90
+ export const iframeCapableSigner = (args: {
91
+ readonly target: { postMessage: (message: unknown, targetOrigin: string) => void };
92
+ readonly signerOrigin: string;
93
+ readonly self: Pick<Window, "addEventListener" | "removeEventListener">;
94
+ }): CapableSigner => {
95
+ const call = (method: string, params: ReadonlyArray<unknown> = []): Promise<unknown> =>
96
+ new Promise((resolve, reject) => {
97
+ const id = toHex(randomBytes(8));
98
+ const listener = (e: Event) => {
99
+ const m = e as MessageEvent;
100
+ const data = m.data as { type?: unknown; id?: unknown; result?: unknown; error?: { message?: string } };
101
+ if (m.origin !== args.signerOrigin || data?.type !== "evolustr" || data.id !== id) return;
102
+ args.self.removeEventListener("message", listener);
103
+ if (data.error !== undefined) reject(new Error(data.error.message ?? "Signer error"));
104
+ else resolve(data.result);
105
+ };
106
+ args.self.addEventListener("message", listener);
107
+ args.target.postMessage({ type: "evolustr", id, method, params }, args.signerOrigin);
108
+ });
109
+ return {
110
+ capabilities: async () => (await call("evolustr_capabilities")) as SignerCapabilities,
111
+ getWrapKey: async () => toKey(await call("evolustr_get_wrap_key")),
112
+ getPreviousWrapKey: async (signerId) => toKey(await call("evolustr_get_previous_wrap_key", signerId === undefined ? [] : [signerId])),
113
+ enrollPasskey: async () => void (await call("evolustr_enroll_passkey")),
114
+ };
115
+ };
116
+
117
+ /** Adds `evolustr` to a `window.nostr` object, for bridge scripts of iframe signers. */
118
+ export const exposeOnWindowNostr = (nostr: Record<string, unknown>, signer: CapableSigner): void => {
119
+ nostr["evolustr"] = {
120
+ capabilities: () => signer.capabilities(),
121
+ getWrapKey: async () => signer.getWrapKey(),
122
+ ...(signer.getPreviousWrapKey === undefined ? {} : { getPreviousWrapKey: (signerId?: string) => signer.getPreviousWrapKey!(signerId) }),
123
+ ...(signer.enrollPasskey === undefined ? {} : { enrollPasskey: () => signer.enrollPasskey!() }),
124
+ };
125
+ };
126
+
127
+ /** A NIP-46 client that can send custom requests (nostr-tools `BunkerSigner.sendRequest`). */
128
+ export interface Nip46RequestClient {
129
+ readonly sendRequest: (method: string, params: string[]) => Promise<string>;
130
+ }
131
+
132
+ /**
133
+ * An Evolustr-capable NIP-46 bunker (SPEC §5.1). The bunker identifies the app
134
+ * only by its connection (SPEC §5.2). Check `capabilities()` first: a bunker
135
+ * without the API returns an error, and the client falls back.
136
+ */
137
+ export const nip46CapableSigner = (bunker: Nip46RequestClient): CapableSigner => ({
138
+ capabilities: async () => JSON.parse(await bunker.sendRequest("evolustr_capabilities", [])) as SignerCapabilities,
139
+ getWrapKey: async () => toKey(await bunker.sendRequest("evolustr_get_wrap_key", [])),
140
+ getPreviousWrapKey: async (signerId) =>
141
+ toKey(await bunker.sendRequest("evolustr_get_previous_wrap_key", signerId === undefined ? [] : [signerId])),
142
+ enrollPasskey: async () => void (await bunker.sendRequest("evolustr_enroll_passkey", [])),
143
+ });