@evolustr/client 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # @evolustr/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > ⚠️ **Early alpha: don't use it for data you can't afford to lose.**
4
+ >
5
+ > Evolustr has not had a security audit, and its vault format and APIs may still change without a migration path. It has been tested mainly with simulated signers, relays and passkeys; testing on real devices has only started.
6
+ >
7
+ > Keep your own backup of anything important, save your recovery phrase, and don't use it to protect high-value secrets (keys to funds, bank credentials). See the [project README](https://github.com/saintego/evolustr#readme) and the [open issues](https://github.com/saintego/evolustr/issues).
8
+
9
+ Opens an app's [Evolu](https://www.evolu.dev) database for the signed-in Nostr user, on any device. See the [main README](https://github.com/saintego/evolustr#readme) for the quick start and [SPEC.md](https://github.com/saintego/evolustr/blob/main/SPEC.md) for the design.
10
+
11
+ Every method returns a `Result`: `{ ok: true, value }` or `{ ok: false, error: { type, message } }`.
12
+
13
+ ## Errors worth handling
14
+
15
+ | `error.type` | From | What to do |
16
+ |---|---|---|
17
+ | `signerRefused` | any | The user declined in their signer, or it failed. Let them retry. |
18
+ | `wrongPhrase` | `unlock`, `unlockRoot`, `restoreFromPhrase` | The phrase doesn't open this app's data. |
19
+ | `vaultReplaced` | `unlock` | The unlock proved the vault on the relays isn't the user's. Call `resolveVaultChange("republishCopy")` to restore this device's copy. |
20
+ | `unsafeFollow` | `resolveVaultChange("followRelay")` | This device's data is protected by a root key and the vault on the relays only opens through NIP-44. Restore with a strong method instead. |
21
+ | `backupRequired` | `makeStrict`, `unlock` (setupStrong) | Ask the user to save the recovery phrase or add a second passkey, or pass `acceptDeviceLoss: true` after they agree. |
22
+ | `partialPublish` | `makeStrict`, `downgrade` | Not every relay took the change; it completes on the next `connect()`. |
23
+ | `rootLocked` | `enrollPasskey`, `showRecoveryPhrase`, `downgrade`, `makeStrict` | Call `unlockRoot()` first. If `status.canReplaceRoot` is true (this device can't open the root key of a compatible database), offer `makeStrict({ replaceRoot: true })` instead. |
24
+ | `rootRotated` | `unlock` | The root key was replaced on another device (`rotateRoot()`); the old phrase or passkey no longer works. Unlock with the new method. |
25
+ | `rootKnown` | `makeStrict({ replaceRoot: true })` | The root key is unlocked here; call `makeStrict()` without `replaceRoot`. |
26
+
27
+ ## Going strict with a new recovery phrase
28
+
29
+ `status.canReplaceRoot` is true when the database is compatible and this device can't open its root key: the user lost every passkey, signer and the phrase, or another app that can decrypt added a root key of its own. `makeStrict({ replaceRoot: true })`, from a click, then creates a new root key and a new strong method (the capable signer, else a new passkey), and moves the data to strict. Tell the user first: "Your earlier recovery phrase and passkeys for this app will stop working." Other devices then ask for a strong unlock and get in with the new passkey, the signer or the new phrase; a device that still has the old root key cached reports the vault as replaced.
30
+
31
+ ## Optional dependencies
32
+
33
+ - `hints`: a small non-secret store that survives logout (for example `localStorage`). It keeps the last mode and secret hash per user and app, so after a logout the device still notices a strict database swapped for a weak one. It also holds the facts for the backup check before strict: which of the user's passkeys and signers recover on their own, and whether the recovery phrase was confirmed. They're kept on the device because other apps with decrypt permission can write to a compatible database. Without `hints`, they last for the session only, and the user may be asked to confirm the phrase again after a reload. The mode hint is removed by `logout({ deleteLocalData: true })`.
34
+ - `cache`: `webSecretCache()` on the web. Its entries are bound to their slot; entries written by earlier versions don't decrypt anymore and act as an empty cache (the user unlocks once).
35
+
36
+ ## Replacing the root key
37
+
38
+ `rotateRoot()`, from a click, replaces the root key and the data secret, keeping the mode. Offer it when `status.rootExposed` is true (the user's signer replaced its key because the old one was exposed), or when the user thinks their recovery phrase leaked. One new strong method seals the new key (the capable signer, else a new passkey). Tell the user first: their earlier recovery phrase, and other passkeys and signers for this app, stop working, and data written before stays as readable as it was.
39
+
40
+ ## After a switch to strict elsewhere
41
+
42
+ When a device follows a database that was made strict elsewhere, it copies only the rows the strict database doesn't have yet. Rows it already has are never overwritten, because any app that could decrypt the old secret could have written to the old database. `ready.migration` says what happened: `{ copied, skippedChanged }`. When `skippedChanged > 0`, edits made on this device while it was away were left in the old database, which is kept: tell the user, then call `discardOldDatabase()`. Set `migrateChangedRows: true` to carry those edits over instead, accepting that such an app could then change strict data.
43
+
44
+ ## States from `connect()`
45
+
46
+ - `ready`: use the database.
47
+ - `needsUserAction`: show a button that calls `unlock()`. The action is `passkey`, `signerUnlock`, `recoveryPhrase`, `setupStrong` or `confirmWeak` (first use of a weak vault on this device).
48
+ - `vaultChanged`: show the offered `options` and call `resolveVaultChange(choice)`. When it also has `advice: "useAnotherDevice"`, nothing on this device can restore the real vault (it was logged out, and the vault on the relays was swapped for a weak one). Tell the user to open the app on a device that is still signed in, which restores the vault (`republishCopy`), and then to sign in here again. `restoreFromPhrase()` works once the real vault is back.
@@ -0,0 +1,52 @@
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 } from "@evolustr/core";
6
+ export interface CachedSecrets {
7
+ readonly s: Bytes;
8
+ readonly r?: Bytes;
9
+ }
10
+ export interface SecretCache {
11
+ readonly get: (pubkey: string, appId: string) => Promise<CachedSecrets | null>;
12
+ readonly set: (pubkey: string, appId: string, secrets: CachedSecrets) => Promise<void>;
13
+ readonly remove: (pubkey: string, appId: string) => Promise<void>;
14
+ }
15
+ interface KeyValue {
16
+ readonly getItem: (k: string) => string | null;
17
+ readonly setItem: (k: string, v: string) => void;
18
+ readonly removeItem: (k: string) => void;
19
+ }
20
+ /** A cache over any `localStorage`-like store. Failing storage acts as empty. */
21
+ export declare const keyValueCache: (store: KeyValue) => SecretCache;
22
+ export declare const memoryCache: () => SecretCache;
23
+ /** An async key-value store, e.g. `expo-secure-store` (getItemAsync / setItemAsync / deleteItemAsync). */
24
+ export interface AsyncKeyValue {
25
+ readonly getItemAsync: (key: string) => Promise<string | null>;
26
+ readonly setItemAsync: (key: string, value: string) => Promise<void>;
27
+ readonly deleteItemAsync: (key: string) => Promise<void>;
28
+ }
29
+ /**
30
+ * A cache over an async store. Keys use only letters, digits, "." "-" "_",
31
+ * which secure stores such as `expo-secure-store` require.
32
+ */
33
+ export declare const asyncKeyValueCache: (store: AsyncKeyValue) => SecretCache;
34
+ /** Where an encrypted cache keeps its key: a non-extractable WebCrypto key. */
35
+ export interface CryptoKeyStore {
36
+ readonly get: () => Promise<CryptoKey | null>;
37
+ readonly set: (key: CryptoKey) => Promise<void>;
38
+ }
39
+ /** Keeps the key in IndexedDB, which can store a CryptoKey without exposing its bytes. */
40
+ export declare const indexedDbKeyStore: (dbName?: string) => CryptoKeyStore;
41
+ export declare const memoryKeyStore: () => CryptoKeyStore;
42
+ /**
43
+ * A cache whose entries are encrypted with a non-extractable AES-GCM key (#27).
44
+ * It doesn't stop script running on the app's origin (an XSS can still ask for
45
+ * decryption), but plain reads of storage, backups or the browser profile only
46
+ * get ciphertext. Failures act as an empty cache.
47
+ */
48
+ export declare const encryptedCache: (store: KeyValue, keyStore: CryptoKeyStore, subtle?: SubtleCrypto) => SecretCache;
49
+ /** The recommended web cache: localStorage entries encrypted with a key kept in IndexedDB. */
50
+ export declare const webSecretCache: () => SecretCache;
51
+ export {};
52
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,KAAK,KAAK,EAAyC,MAAM,gBAAgB,CAAC;AAEnF,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,CAAC,EAAE,KAAK,CAAC;IAClB,QAAQ,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC;CACpB;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,O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AG,IAAI,CAAC,CAAC;IAC9C,QAAQ,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,SAAS,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACjD;AAED,0FAA0F;AAC1F,eAAO,MAAM,iBAAiB,uBAA+B,cAoB5D,CAAC;AAEF,eAAO,MAAM,cAAc,QAAO,cAGjC,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,cAAc,UAClB,QAAQ,YACL,cAAc,WAChB,YAAY,KACnB,WAiDF,CAAC;AAEF,8FAA8F;AAC9F,eAAO,MAAM,cAAc,QAAO,WAA2E,CAAC"}
package/dist/cache.js ADDED
@@ -0,0 +1,175 @@
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 { fromBase64Url, sha256Hex, toBase64Url } from "@evolustr/core";
6
+ const cacheKey = (pubkey, appId) => `evolustr:secrets:${sha256Hex(`${pubkey}|${appId}`)}`;
7
+ const encode = (c) => JSON.stringify({ s: toBase64Url(c.s), ...(c.r === undefined ? {} : { r: toBase64Url(c.r) }) });
8
+ const decode = (text) => {
9
+ if (text === null)
10
+ return null;
11
+ try {
12
+ const data = JSON.parse(text);
13
+ const s = typeof data.s === "string" ? fromBase64Url(data.s) : null;
14
+ const r = typeof data.r === "string" ? fromBase64Url(data.r) : null;
15
+ if (s === null)
16
+ return null;
17
+ return r === null ? { s } : { s, r };
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ };
23
+ /** A cache over any `localStorage`-like store. Failing storage acts as empty. */
24
+ export const keyValueCache = (store) => ({
25
+ get: async (pubkey, appId) => {
26
+ try {
27
+ return decode(store.getItem(cacheKey(pubkey, appId)));
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ },
33
+ set: async (pubkey, appId, secrets) => {
34
+ try {
35
+ store.setItem(cacheKey(pubkey, appId), encode(secrets));
36
+ }
37
+ catch {
38
+ /* storage unavailable: the user unlocks again next time */
39
+ }
40
+ },
41
+ remove: async (pubkey, appId) => {
42
+ try {
43
+ store.removeItem(cacheKey(pubkey, appId));
44
+ }
45
+ catch {
46
+ /* ignore */
47
+ }
48
+ },
49
+ });
50
+ export const memoryCache = () => {
51
+ const map = new Map();
52
+ return keyValueCache({
53
+ getItem: (k) => map.get(k) ?? null,
54
+ setItem: (k, v) => void map.set(k, v),
55
+ removeItem: (k) => void map.delete(k),
56
+ });
57
+ };
58
+ /**
59
+ * A cache over an async store. Keys use only letters, digits, "." "-" "_",
60
+ * which secure stores such as `expo-secure-store` require.
61
+ */
62
+ export const asyncKeyValueCache = (store) => {
63
+ const key = (pubkey, appId) => `evolustr_secrets_${sha256Hex(`${pubkey}|${appId}`)}`;
64
+ return {
65
+ get: async (pubkey, appId) => {
66
+ try {
67
+ return decode(await store.getItemAsync(key(pubkey, appId)));
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ },
73
+ set: async (pubkey, appId, secrets) => {
74
+ try {
75
+ await store.setItemAsync(key(pubkey, appId), encode(secrets));
76
+ }
77
+ catch {
78
+ /* unavailable: unlock again next time */
79
+ }
80
+ },
81
+ remove: async (pubkey, appId) => {
82
+ try {
83
+ await store.deleteItemAsync(key(pubkey, appId));
84
+ }
85
+ catch {
86
+ /* ignore */
87
+ }
88
+ },
89
+ };
90
+ };
91
+ /** Keeps the key in IndexedDB, which can store a CryptoKey without exposing its bytes. */
92
+ export const indexedDbKeyStore = (dbName = "evolustr-keys") => {
93
+ const open = () => new Promise((resolve, reject) => {
94
+ const req = indexedDB.open(dbName, 1);
95
+ req.onupgradeneeded = () => req.result.createObjectStore("keys");
96
+ req.onsuccess = () => resolve(req.result);
97
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB unavailable"));
98
+ });
99
+ const tx = async (mode, f) => {
100
+ const db = await open();
101
+ return new Promise((resolve, reject) => {
102
+ const req = f(db.transaction("keys", mode).objectStore("keys"));
103
+ req.onsuccess = () => resolve(req.result);
104
+ req.onerror = () => reject(req.error ?? new Error("IndexedDB error"));
105
+ }).finally(() => db.close());
106
+ };
107
+ return {
108
+ get: async () => (await tx("readonly", (s) => s.get("cache"))) ?? null,
109
+ set: async (key) => void (await tx("readwrite", (s) => s.put(key, "cache"))),
110
+ };
111
+ };
112
+ export const memoryKeyStore = () => {
113
+ let key = null;
114
+ return { get: async () => key, set: async (k) => void (key = k) };
115
+ };
116
+ /**
117
+ * A cache whose entries are encrypted with a non-extractable AES-GCM key (#27).
118
+ * It doesn't stop script running on the app's origin (an XSS can still ask for
119
+ * decryption), but plain reads of storage, backups or the browser profile only
120
+ * get ciphertext. Failures act as an empty cache.
121
+ */
122
+ export const encryptedCache = (store, keyStore, subtle = globalThis.crypto.subtle) => {
123
+ let keyPromise = null;
124
+ const key = () => (keyPromise ??= (async () => {
125
+ const existing = await keyStore.get();
126
+ if (existing !== null)
127
+ return existing;
128
+ const fresh = await subtle.generateKey({ name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
129
+ await keyStore.set(fresh);
130
+ return fresh;
131
+ })());
132
+ const enc = new TextEncoder();
133
+ const dec = new TextDecoder();
134
+ return {
135
+ get: async (pubkey, appId) => {
136
+ try {
137
+ const raw = store.getItem(cacheKey(pubkey, appId));
138
+ if (raw === null)
139
+ return null;
140
+ const { iv, ct } = JSON.parse(raw);
141
+ const ivBytes = fromBase64Url(iv);
142
+ const ctBytes = fromBase64Url(ct);
143
+ if (ivBytes === null || ctBytes === null)
144
+ return null;
145
+ // The slot name is the AAD: an entry copied to another slot doesn't decrypt (#44).
146
+ const plain = await subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(ivBytes), additionalData: enc.encode(cacheKey(pubkey, appId)) }, await key(), new Uint8Array(ctBytes));
147
+ return decode(dec.decode(plain));
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ },
153
+ set: async (pubkey, appId, secrets) => {
154
+ try {
155
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
156
+ const ct = await subtle.encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(cacheKey(pubkey, appId)) }, await key(), enc.encode(encode(secrets)));
157
+ store.setItem(cacheKey(pubkey, appId), JSON.stringify({ iv: toBase64Url(iv), ct: toBase64Url(new Uint8Array(ct)) }));
158
+ }
159
+ catch {
160
+ /* unavailable: unlock again next time */
161
+ }
162
+ },
163
+ remove: async (pubkey, appId) => {
164
+ try {
165
+ store.removeItem(cacheKey(pubkey, appId));
166
+ }
167
+ catch {
168
+ /* ignore */
169
+ }
170
+ },
171
+ };
172
+ };
173
+ /** The recommended web cache: localStorage entries encrypted with a key kept in IndexedDB. */
174
+ export const webSecretCache = () => encryptedCache(globalThis.localStorage, indexedDbKeyStore());
175
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAc,aAAa,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAanF,MAAM,QAAQ,GAAG,CAAC,MAAc,EAAE,KAAa,EAAE,EAAE,CAAC,oBAAoB,SAAS,CAAC,GAAG,MAAM,IAAI,KAAK,EAAE,CAAC,EAAE,CAAC;AAQ1G,MAAM,MAAM,GAAG,CAAC,CAAgB,EAAE,EAAE,CAClC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AAEjG,MAAM,MAAM,GAAG,CAAC,IAAmB,EAAwB,EAAE;IAC3D,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC/B,IAAI,CAAC;QACH,MAAM,IAAI,GA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KAAK,EAAE,EAAE;YAC9B,IAAI,CAAC;gBACH,KAAK,CAAC,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC;YAC5C,CAAC;YAAC,MAAM,CAAC;gBACP,YAAY;YACd,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAEF,8FAA8F;AAC9F,MAAM,CAAC,MAAM,cAAc,GAAG,GAAgB,EAAE,CAAC,cAAc,CAAC,UAAU,CAAC,YAAY,EAAE,iBAAiB,EAAE,CAAC,CAAC"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Talking to an Evolustr-capable signer from the app (SPEC §5.1, §5.4).
3
+ */
4
+ import { type Bytes } from "@evolustr/core";
5
+ export interface SignerCapabilities {
6
+ readonly identity: "verified" | "connection";
7
+ readonly appId: string;
8
+ readonly signerId: string | null;
9
+ readonly ready: boolean;
10
+ readonly signerPasskey: boolean;
11
+ /** M can be recovered on another device (#42). Older signers don't send it: counts as false. */
12
+ readonly recoverable?: boolean;
13
+ /** The signer's key is protected by the nsec, so nsec holders can open strict data (#43). */
14
+ readonly nsecProtected?: boolean;
15
+ /**
16
+ * The nsec could open the signer's key now or did before, e.g. it moved to a
17
+ * passkey without a new key: nsec holders may still open strict data (#52).
18
+ */
19
+ readonly nsecExposed?: boolean;
20
+ /**
21
+ * The signer replaced its key (#52 phase B): this app's signer id under the
22
+ * previous key. Its wrap in the vault still opens R, which may be exposed.
23
+ */
24
+ readonly previousSignerId?: string | null;
25
+ /**
26
+ * Every earlier key's signer id for this app, newest first (#58), when the
27
+ * signer replaced its key more than once. Older signers send only
28
+ * `previousSignerId`.
29
+ */
30
+ readonly previousSignerIds?: ReadonlyArray<string>;
31
+ }
32
+ /** The signer ids of the signer's earlier keys, newest first: the list, or the single id older signers send (#58). */
33
+ export declare const earlierSignerIds: (c: SignerCapabilities) => ReadonlyArray<string>;
34
+ export interface CapableSigner {
35
+ readonly capabilities: () => Promise<SignerCapabilities>;
36
+ /** May wait for the user to click inside the signer; don't use short timeouts. */
37
+ readonly getWrapKey: () => Promise<Bytes>;
38
+ /**
39
+ * The app key under the signer's earlier key whose signer id is `signerId`
40
+ * (#58), else its previous key, after a key rotation (#52 phase B).
41
+ */
42
+ readonly getPreviousWrapKey?: (signerId?: string) => Promise<Bytes>;
43
+ readonly enrollPasskey?: () => Promise<void>;
44
+ }
45
+ /** The NIP-07 namespace `window.nostr.evolustr`, if present. */
46
+ export interface Nip07Evolustr {
47
+ readonly capabilities: () => Promise<SignerCapabilities>;
48
+ readonly getWrapKey: () => Promise<string | Uint8Array>;
49
+ readonly getPreviousWrapKey?: (signerId?: string) => Promise<string | Uint8Array>;
50
+ readonly enrollPasskey?: () => Promise<void>;
51
+ }
52
+ export declare const nip07CapableSigner: (ns: Nip07Evolustr) => CapableSigner;
53
+ /** Detects `window.nostr.evolustr`; undefined for standard signers. */
54
+ export declare const detectCapableSigner: (nostr: unknown) => CapableSigner | undefined;
55
+ /**
56
+ * Forwards calls to an iframe signer with postMessage. Used by bridge scripts
57
+ * to implement `window.nostr.evolustr` (see {@link exposeOnWindowNostr}).
58
+ */
59
+ export declare const iframeCapableSigner: (args: {
60
+ readonly target: {
61
+ postMessage: (message: unknown, targetOrigin: string) => void;
62
+ };
63
+ readonly signerOrigin: string;
64
+ readonly self: Pick<Window, "addEventListener" | "removeEventListener">;
65
+ }) => CapableSigner;
66
+ /** Adds `evolustr` to a `window.nostr` object, for bridge scripts of iframe signers. */
67
+ export declare const exposeOnWindowNostr: (nostr: Record<string, unknown>, signer: CapableSigner) => void;
68
+ /** A NIP-46 client that can send custom requests (nostr-tools `BunkerSigner.sendRequest`). */
69
+ export interface Nip46RequestClient {
70
+ readonly sendRequest: (method: string, params: string[]) => Promise<string>;
71
+ }
72
+ /**
73
+ * An Evolustr-capable NIP-46 bunker (SPEC §5.1). The bunker identifies the app
74
+ * only by its connection (SPEC §5.2). Check `capabilities()` first: a bunker
75
+ * without the API returns an error, and the client falls back.
76
+ */
77
+ export declare const nip46CapableSigner: (bunker: Nip46RequestClient) => CapableSigner;
78
+ //# sourceMappingURL=capable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capable.d.ts","sourceRoot":"","sources":["../src/capable.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,KAAK,EAAqC,MAAM,gBAAgB,CAAC;AAE/E,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,QAAQ,EAAE,UAAU,GAAG,YAAY,CAAC;IAC7C,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,aAAa,EAAE,OAAO,CAAC;IAChC,gGAAgG;IAChG,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B,6FAA6F;IAC7F,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;IACjC;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;IAC/B;;;OAGG;IACH,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,iBAAiB,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACpD;AAED,sHAAsH;AACtH,eAAO,MAAM,gBAAgB,MAAO,kBAAkB,KAAG,aAAa,CAAC,MAAM,CAKjD,CAAC;AAE7B,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,YAAY,EAAE,MAAM,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACzD,kFAAkF;IAClF,QAAQ,CAAC,UAAU,EAAE,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC;IAC1C;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,MAAM,KAAK,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C,MAAM,CAAC,CAAC;CAC7E;AAED;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,WAAY,kBAAkB,KAAG,aAM9D,CAAC"}
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Talking to an Evolustr-capable signer from the app (SPEC §5.1, §5.4).
3
+ */
4
+ import { fromBase64Url, randomBytes, toHex } from "@evolustr/core";
5
+ /** The signer ids of the signer's earlier keys, newest first: the list, or the single id older signers send (#58). */
6
+ export const earlierSignerIds = (c) => c.previousSignerIds !== undefined && c.previousSignerIds.length > 0
7
+ ? c.previousSignerIds
8
+ : c.previousSignerId == null
9
+ ? []
10
+ : [c.previousSignerId];
11
+ const toKey = (v) => {
12
+ if (v instanceof Uint8Array)
13
+ return v;
14
+ if (typeof v === "string") {
15
+ const b = fromBase64Url(v);
16
+ if (b !== null && b.length === 32)
17
+ return b;
18
+ }
19
+ throw new Error("The signer returned an invalid key");
20
+ };
21
+ export const nip07CapableSigner = (ns) => ({
22
+ capabilities: () => ns.capabilities(),
23
+ getWrapKey: async () => toKey(await ns.getWrapKey()),
24
+ ...(ns.getPreviousWrapKey === undefined ? {} : { getPreviousWrapKey: async (signerId) => toKey(await ns.getPreviousWrapKey(signerId)) }),
25
+ ...(ns.enrollPasskey === undefined ? {} : { enrollPasskey: () => ns.enrollPasskey() }),
26
+ });
27
+ /** Detects `window.nostr.evolustr`; undefined for standard signers. */
28
+ export const detectCapableSigner = (nostr) => {
29
+ const ns = nostr?.evolustr;
30
+ return typeof ns?.capabilities === "function" && typeof ns.getWrapKey === "function"
31
+ ? nip07CapableSigner(ns)
32
+ : undefined;
33
+ };
34
+ /**
35
+ * Forwards calls to an iframe signer with postMessage. Used by bridge scripts
36
+ * to implement `window.nostr.evolustr` (see {@link exposeOnWindowNostr}).
37
+ */
38
+ export const iframeCapableSigner = (args) => {
39
+ const call = (method, params = []) => new Promise((resolve, reject) => {
40
+ const id = toHex(randomBytes(8));
41
+ const listener = (e) => {
42
+ const m = e;
43
+ const data = m.data;
44
+ if (m.origin !== args.signerOrigin || data?.type !== "evolustr" || data.id !== id)
45
+ return;
46
+ args.self.removeEventListener("message", listener);
47
+ if (data.error !== undefined)
48
+ reject(new Error(data.error.message ?? "Signer error"));
49
+ else
50
+ resolve(data.result);
51
+ };
52
+ args.self.addEventListener("message", listener);
53
+ args.target.postMessage({ type: "evolustr", id, method, params }, args.signerOrigin);
54
+ });
55
+ return {
56
+ capabilities: async () => (await call("evolustr_capabilities")),
57
+ getWrapKey: async () => toKey(await call("evolustr_get_wrap_key")),
58
+ getPreviousWrapKey: async (signerId) => toKey(await call("evolustr_get_previous_wrap_key", signerId === undefined ? [] : [signerId])),
59
+ enrollPasskey: async () => void (await call("evolustr_enroll_passkey")),
60
+ };
61
+ };
62
+ /** Adds `evolustr` to a `window.nostr` object, for bridge scripts of iframe signers. */
63
+ export const exposeOnWindowNostr = (nostr, signer) => {
64
+ nostr["evolustr"] = {
65
+ capabilities: () => signer.capabilities(),
66
+ getWrapKey: async () => signer.getWrapKey(),
67
+ ...(signer.getPreviousWrapKey === undefined ? {} : { getPreviousWrapKey: (signerId) => signer.getPreviousWrapKey(signerId) }),
68
+ ...(signer.enrollPasskey === undefined ? {} : { enrollPasskey: () => signer.enrollPasskey() }),
69
+ };
70
+ };
71
+ /**
72
+ * An Evolustr-capable NIP-46 bunker (SPEC §5.1). The bunker identifies the app
73
+ * only by its connection (SPEC §5.2). Check `capabilities()` first: a bunker
74
+ * without the API returns an error, and the client falls back.
75
+ */
76
+ export const nip46CapableSigner = (bunker) => ({
77
+ capabilities: async () => JSON.parse(await bunker.sendRequest("evolustr_capabilities", [])),
78
+ getWrapKey: async () => toKey(await bunker.sendRequest("evolustr_get_wrap_key", [])),
79
+ getPreviousWrapKey: async (signerId) => toKey(await bunker.sendRequest("evolustr_get_previous_wrap_key", signerId === undefined ? [] : [signerId])),
80
+ enrollPasskey: async () => void (await bunker.sendRequest("evolustr_enroll_passkey", [])),
81
+ });
82
+ //# sourceMappingURL=capable.js.map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