@ghostlytools/cli 1.10.0 → 1.10.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 +9 -9
- package/SKILL.md +2 -2
- package/dist/assets/api-BOWLZYXM.js +3 -0
- package/dist/assets/{api-BF_KwecF.js → api-Bi6hCcwG.js} +27 -20
- package/dist/assets/api-Bi6hCcwG.js.map +1 -0
- package/dist/assets/{apiKit-Du1u2l4x.js → apiKit-DzXHZojD.js} +20 -3
- package/dist/assets/apiKit-DzXHZojD.js.map +1 -0
- package/dist/assets/{apps-Bti9fDoW.js → apps-0Ks6KjqS.js} +1 -1
- package/dist/assets/{apps-DwPfp54I.js → apps-DIQbzG08.js} +31 -10
- package/dist/assets/apps-DIQbzG08.js.map +1 -0
- package/dist/assets/{arkade-DOWpA2Kr.js → arkade-zozCldAE.js} +2 -2
- package/dist/assets/{arkade-DOWpA2Kr.js.map → arkade-zozCldAE.js.map} +1 -1
- package/dist/assets/{backup-DZ_Q1eSu.js → backup-BL49Kt-T.js} +6 -5
- package/dist/assets/{backup-DZ_Q1eSu.js.map → backup-BL49Kt-T.js.map} +1 -1
- package/dist/assets/{backup-CeRckyl2.js → backup-BvIFcZM7.js} +1 -1
- package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
- package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
- package/dist/assets/{buttons-BxIThdg9.js → buttons-CAW5v5EE.js} +3 -3
- package/dist/assets/{buttons-BxIThdg9.js.map → buttons-CAW5v5EE.js.map} +1 -1
- package/dist/assets/buttons-oJI5mHSL.js +2 -0
- package/dist/assets/childEnv-BVOQK9EA.js +21 -0
- package/dist/assets/childEnv-BVOQK9EA.js.map +1 -0
- package/dist/assets/{client-D5E1RQYB.js → client-CyApKBEw.js} +2 -2
- package/dist/assets/{client-D5E1RQYB.js.map → client-CyApKBEw.js.map} +1 -1
- package/dist/assets/codec-DqFxxB_q.js +13 -0
- package/dist/assets/codec-DqFxxB_q.js.map +1 -0
- package/dist/assets/{envelope-CugS9qwQ.js → envelope-CMUgz31I.js} +3 -12
- package/dist/assets/envelope-CMUgz31I.js.map +1 -0
- package/dist/assets/{fixedHosts-B4E4VrYE.js → fixedHosts-C2hdCfzK.js} +4 -4
- package/dist/assets/{fixedHosts-B4E4VrYE.js.map → fixedHosts-C2hdCfzK.js.map} +1 -1
- package/dist/assets/{groupFiles-NonOYBKN.js → groupFiles-BAQIt_bJ.js} +68 -144
- package/dist/assets/groupFiles-BAQIt_bJ.js.map +1 -0
- package/dist/assets/{host-DvcVt5YI.js → host-CaRlDMTd.js} +143 -42
- package/dist/assets/host-CaRlDMTd.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-Ce42sR8x.js → hyperdhtRelay-BxADl3SG.js} +2 -2
- package/dist/assets/{hyperdhtRelay-Ce42sR8x.js.map → hyperdhtRelay-BxADl3SG.js.map} +1 -1
- package/dist/assets/{irohWeb-C9ChbD-c.js → irohWeb-D2sh6EWp.js} +10 -6
- package/dist/assets/irohWeb-D2sh6EWp.js.map +1 -0
- package/dist/assets/{main-4qE381KM.js → main-Bc4Ow56Z.js} +46 -30
- package/dist/assets/main-Bc4Ow56Z.js.map +1 -0
- package/dist/assets/{mainline-DOwZDHVy.js → mainline-DWh4Ccri.js} +2 -2
- package/dist/assets/{mainline-DOwZDHVy.js.map → mainline-DWh4Ccri.js.map} +1 -1
- package/dist/assets/networkReason-DT_D_Wpc.js +474 -0
- package/dist/assets/networkReason-DT_D_Wpc.js.map +1 -0
- package/dist/assets/{nwc-CHLWFV1R.js → nwc-DoSEhUKb.js} +3 -3
- package/dist/assets/{nwc-CHLWFV1R.js.map → nwc-DoSEhUKb.js.map} +1 -1
- package/dist/assets/{nwcProvider-BlkPOJen.js → nwcProvider-CGWqUjpB.js} +2 -2
- package/dist/assets/{nwcProvider-BlkPOJen.js.map → nwcProvider-CGWqUjpB.js.map} +1 -1
- package/dist/assets/{ownDid-yXtY_1B5.js → ownDid-CbGjRLBn.js} +2 -2
- package/dist/assets/{ownDid-yXtY_1B5.js.map → ownDid-CbGjRLBn.js.map} +1 -1
- package/dist/assets/{profiles-vbXHs0Mq.js → profiles-DgIfvBeN.js} +10 -4
- package/dist/assets/profiles-DgIfvBeN.js.map +1 -0
- package/dist/assets/{registry-chCD0KWS.js → registry-BSyxGjN6.js} +11 -9
- package/dist/assets/registry-BSyxGjN6.js.map +1 -0
- package/dist/assets/{registry-BN9r2pR4.js → registry-C5cn80Rw.js} +1 -1
- package/dist/assets/{resolve-Dtzogt2W.js → resolve-D-9YRFhl.js} +2 -2
- package/dist/assets/{resolve-Dtzogt2W.js.map → resolve-D-9YRFhl.js.map} +1 -1
- package/dist/assets/{server-BZnsm5X5.js → server-BufntkX8.js} +240 -289
- package/dist/assets/server-BufntkX8.js.map +1 -0
- package/dist/assets/{src-DZagapGt.js → src-CCt5s4DK.js} +3162 -2825
- package/dist/assets/src-CCt5s4DK.js.map +1 -0
- package/dist/assets/{sshForges-BkTgy5rx.js → sshForges-D8CPaIbR.js} +2 -2
- package/dist/assets/{sshForges-BkTgy5rx.js.map → sshForges-D8CPaIbR.js.map} +1 -1
- package/dist/assets/{translate-B9SMd6uf.js → translate-Cb-6hMhD.js} +11 -7
- package/dist/assets/{translate-B9SMd6uf.js.map → translate-Cb-6hMhD.js.map} +1 -1
- package/dist/assets/{usdt-BU4ezonh.js → usdt-ds461mzA.js} +3 -3
- package/dist/assets/{usdt-BU4ezonh.js.map → usdt-ds461mzA.js.map} +1 -1
- package/dist/assets/{words-jYy7lTcb.js → words-B1ylON2h.js} +2 -2
- package/dist/assets/{words-jYy7lTcb.js.map → words-B1ylON2h.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-BF_KwecF.js.map +0 -1
- package/dist/assets/api-DdrA86Ur.js +0 -3
- package/dist/assets/apiKit-Du1u2l4x.js.map +0 -1
- package/dist/assets/apps-DwPfp54I.js.map +0 -1
- package/dist/assets/buttons-D9QBHS9Y.js +0 -2
- package/dist/assets/envelope-CugS9qwQ.js.map +0 -1
- package/dist/assets/groupFiles-NonOYBKN.js.map +0 -1
- package/dist/assets/host-DvcVt5YI.js.map +0 -1
- package/dist/assets/irohWeb-C9ChbD-c.js.map +0 -1
- package/dist/assets/main-4qE381KM.js.map +0 -1
- package/dist/assets/networkReason-MInk1Y63.js +0 -154
- package/dist/assets/networkReason-MInk1Y63.js.map +0 -1
- package/dist/assets/profiles-vbXHs0Mq.js.map +0 -1
- package/dist/assets/registry-chCD0KWS.js.map +0 -1
- package/dist/assets/server-BZnsm5X5.js.map +0 -1
- package/dist/assets/src-DZagapGt.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"networkReason-DT_D_Wpc.js","names":[],"sources":["../../../browser/src/shared/profileKey.ts","../../../browser/src/engine/dataKey.ts","../../../browser/src/engine/sealedRows.ts","../../../browser/src/engine/paymentAdapters/persistence.ts","../../../browser/src/engine/paymentAdapters/networkReason.ts"],"sourcesContent":["import { fromBase64Url, toBase64Url } from \"../backup/codec\";\n\n/**\n * The encrypted profile's keys (WISP 04, Encrypted profile): a random data key (DK) per profile seals each secret\n * field, and is stored only wrapped under a key derived from the passphrase (KEK). The passphrase never encrypts\n * data directly, so changing it rewraps 32 bytes and rewrites nothing else.\n */\nexport interface ProfileKeyRecord {\n format: \"ghostly-profile-key\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n /** The profile id, empty for the default: the record opens only in its own profile's slot. */\n profile: string;\n ciphertext: string;\n}\n/** A field sealed under DK. Version 1 is the `{version:1,salt,iv,ciphertext}` seed sealed with a device key. */\nexport interface SealedField { v: 2; iv: string; ct: string }\n/**\n * Where a sealed field lives: a ciphertext moved to another database, store, record or field fails to open instead\n * of being read as that one. `db` is `local` for local storage.\n */\nexport interface FieldBinding { db: string; store: string; key: string; field: string }\n\nconst ITERATIONS = 600_000;\nconst MAX_ITERATIONS = 10_000_000;\nconst DK_BYTES = 32;\nconst TAG_BYTES = 16;\n\nasync function kekFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\", \"unwrapKey\"]);\n}\n\n/** The clear header is the wrap's associated data, `profile` included: changing any of it makes the record fail to open. */\nconst header = (r: Omit<ProfileKeyRecord, \"ciphertext\">) =>\n new TextEncoder().encode([r.format, r.version, r.kdf.name, r.kdf.iterations, r.kdf.salt, r.cipher.name, r.cipher.iv, r.profile].join(\"\\n\"));\n\nconst importDataKey = (raw: Uint8Array) => crypto.subtle.importKey(\"raw\", raw as BufferSource, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n\nfunction checkPassphrase(passphrase: string) {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the profile passphrase\");\n}\n\nasync function wrap(raw: Uint8Array, passphrase: string, profile: string): Promise<ProfileKeyRecord> {\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const clear = { format: \"ghostly-profile-key\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, profile } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await kekFrom(passphrase, salt, ITERATIONS), raw as BufferSource));\n return { ...clear, ciphertext: toBase64Url(ciphertext) };\n}\n\n/** Refuses what this version can't read before any KDF runs, as backups do. */\nfunction checked(record: ProfileKeyRecord, profile: string) {\n if (record?.format !== \"ghostly-profile-key\") throw new Error(\"This is not a Ghostly profile key\");\n if (record.version !== 1) throw new Error(\"This profile key comes from a newer Ghostly; update to open it\");\n if (record.kdf?.name !== \"PBKDF2-SHA256\" || !Number.isInteger(record.kdf.iterations) || record.kdf.iterations < ITERATIONS || record.kdf.iterations > MAX_ITERATIONS || record.cipher?.name !== \"AES-256-GCM\") throw new Error(\"Unsupported profile key encryption\");\n if (typeof record.profile !== \"string\" || record.profile !== profile) throw new Error(\"This profile key belongs to another profile\");\n const salt = fromBase64Url(record.kdf.salt), iv = fromBase64Url(record.cipher.iv), ciphertext = fromBase64Url(record.ciphertext);\n if (salt.length !== 16 || iv.length !== 12 || ciphertext.length !== DK_BYTES + TAG_BYTES) throw new Error(\"Unsupported profile key encryption\");\n return { salt, iv, ciphertext };\n}\n\n/** Turning encryption on: a fresh DK, wrapped under the passphrase, and the DK itself as a key that can't be read back. */\nexport async function createProfileKey(passphrase: string, profile: string): Promise<{ record: ProfileKeyRecord; key: CryptoKey }> {\n checkPassphrase(passphrase);\n const raw = crypto.getRandomValues(new Uint8Array(DK_BYTES));\n try { return { record: await wrap(raw, passphrase, profile), key: await importDataKey(raw) }; } finally { raw.fill(0); }\n}\n\n/** The start gate: the DK as a non-extractable key, or \"Wrong passphrase\" with nothing else read. */\nexport async function unlockProfileKey(record: ProfileKeyRecord, passphrase: string, profile: string): Promise<CryptoKey> {\n const { salt, iv, ciphertext } = checked(record, profile);\n const kek = await kekFrom(passphrase, salt, record.kdf.iterations);\n try {\n return await crypto.subtle.unwrapKey(\"raw\", ciphertext as BufferSource, kek, { name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, { name: \"AES-GCM\" }, false, [\"encrypt\", \"decrypt\"]);\n } catch { throw new Error(\"Wrong passphrase\"); }\n}\n\n/** Change passphrase: the same DK under a new KEK, salt and nonce. No sealed field changes. */\nexport async function rewrapProfileKey(record: ProfileKeyRecord, passphrase: string, next: string, profile: string): Promise<ProfileKeyRecord> {\n checkPassphrase(next);\n const { salt, iv, ciphertext } = checked(record, profile);\n let raw: Uint8Array;\n try {\n raw = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: header(record) as BufferSource }, await kekFrom(passphrase, salt, record.kdf.iterations), ciphertext as BufferSource));\n } catch { throw new Error(\"Wrong passphrase\"); }\n try { return await wrap(raw, next, profile); } finally { raw.fill(0); }\n}\n\n/**\n * Only the record key can hold a newline: the other parts come from the code, so the joined binding still reads one\n * way (the first two lines, the last line, and the key between them).\n */\nfunction binding(b: FieldBinding): Uint8Array {\n for (const part of [b.db, b.store, b.field]) if (!part || part.includes(\"\\n\")) throw new Error(\"Invalid sealed field binding\");\n return new TextEncoder().encode([\"ghostly-field/2\", b.db, b.store, b.key, b.field].join(\"\\n\"));\n}\n\nexport function isSealedField(value: unknown): value is SealedField {\n const v = value as Partial<SealedField> | null;\n return !!v && typeof v === \"object\" && v.v === 2 && typeof v.iv === \"string\" && typeof v.ct === \"string\";\n}\n\n/** Seals one field under DK with a fresh random 96-bit nonce and no KDF per field. */\nexport async function sealField(key: CryptoKey, where: FieldBinding, value: string): Promise<SealedField> {\n const iv = crypto.getRandomValues(new Uint8Array(12));\n const ct = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: binding(where) as BufferSource }, key, new TextEncoder().encode(value)));\n return { v: 2, iv: toBase64Url(iv), ct: toBase64Url(ct) };\n}\n\n/** Opens a field sealed for exactly this place under this DK; anything else fails instead of opening wrong. */\nexport async function openField(key: CryptoKey, where: FieldBinding, sealed: SealedField): Promise<string> {\n if (!isSealedField(sealed)) throw new Error(\"Unsupported sealed field version\");\n const aad = binding(where);\n try {\n const iv = fromBase64Url(sealed.iv);\n if (iv.length !== 12) throw new Error(\"nonce\");\n return new TextDecoder().decode(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource, additionalData: aad as BufferSource }, key, fromBase64Url(sealed.ct) as BufferSource));\n } catch { throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\"); }\n}\n","import { isSealedField, openField, sealField, type FieldBinding, type SealedField } from \"../shared/profileKey\";\nimport { newDeviceKey, sealSeed, unsealSeed, type EncryptedSeed } from \"./paymentAdapters/persistence\";\n\n/** Version 1: sealed under a random key stored beside it. It keeps a secret from a log, not from a reader of the profile. */\nexport interface DeviceSealed { sealed: EncryptedSeed; deviceKey: string }\n/** A secret the engine keeps: version 1 while the profile is not encrypted, version 2 under its data key once it is. */\nexport type SealedSecret = DeviceSealed | SealedField;\n/**\n * Where a secret belongs, in the peer database (WISP 04, Encrypted profile): its store, its own id (stable when the\n * secret moves inside its record, as a proof key does into the revocations) and what it is.\n */\nexport type SecretPlace = Omit<FieldBinding, \"db\">;\n\nconst PEER_DB = \"ghostly\";\n\n/**\n * The profile's data key (DK), when the profile is encrypted and unlocked: the one slot the engine owns. A\n * non-extractable key; nothing writes it anywhere. Empty, every secret is sealed as today (version 1).\n */\nlet slot: CryptoKey | null = null;\n/**\n * The profile's migration is over (no `migrating` mark): a sealed place then takes version 2 only. A version 1 or plain\n * value there was put by someone who could write the profile's database but not read it, and is refused.\n */\nlet sealedOnly = false;\nconst onDrop = new Set<() => void>();\nconst LOCKED = \"This profile is locked. Enter its passphrase first.\";\n\nexport function setDataKey(key: CryptoKey): void { slot = key; }\nexport function hasDataKey(): boolean { return slot !== null; }\n/** Off until the migration that seals every place has ended; set by it. */\nexport function setSealedOnly(on: boolean): void { sealedOnly = on; }\n/** Whether a sealed place may still hold a version 1 or plain value. */\nexport function takesUnsealed(): boolean { return !(slot && sealedOnly); }\n/** \"Lock and stop\", or a profile switch: the key goes, and so does every secret opened with it and kept in memory. */\nexport function dropDataKey(): void {\n slot = null;\n sealedOnly = false;\n for (const drop of [...onDrop]) drop();\n}\n/** A cache of opened secrets empties itself when the key goes. Returns the way to stop listening. */\nexport function whenDataKeyDropped(drop: () => void): () => void {\n onDrop.add(drop);\n return () => { onDrop.delete(drop); };\n}\n\nexport async function sealSecret(value: string, at: SecretPlace): Promise<SealedSecret> {\n if (slot) return sealField(slot, { db: PEER_DB, ...at }, value);\n const deviceKey = newDeviceKey();\n return { sealed: await sealSeed(value, deviceKey), deviceKey };\n}\n\n/** Version 2 only, for a field the database layer seals: refused while the profile is locked, never version 1. */\nexport async function sealPlace(value: string, at: SecretPlace): Promise<SealedField> {\n if (!slot) throw new Error(LOCKED);\n return sealField(slot, { db: PEER_DB, ...at }, value);\n}\n\n/** Reads both versions: a profile being encrypted holds some of each until its migration ends. */\nexport async function openSecret(secret: SealedSecret, at: SecretPlace): Promise<string> {\n if (!isSealedField(secret)) {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n return unsealSeed(secret.sealed, secret.deviceKey);\n }\n if (!slot) throw new Error(LOCKED);\n return openField(slot, { db: PEER_DB, ...at }, secret);\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { bytesToHex, utf8ToBytes } from \"@noble/hashes/utils.js\";\nimport { STORES } from \"../shared/idb\";\nimport { isSealedField, type SealedField } from \"../shared/profileKey\";\nimport { hasDataKey, openSecret, sealPlace, takesUnsealed, type SecretPlace } from \"./dataKey\";\n\n/**\n * Phase 1 of the encrypted profile (WISP 04, What is encrypted): the fields of the peer database that let someone act\n * as the person or spend, by store, as paths into the row. With the data key set they are written sealed (version 2,\n * bound to the store, the row's key and the path) and opened as they are read; without it, rows are written and read\n * as they always were. A field is sealed as its JSON, so an object (transport seeds, epoch secrets) is one field.\n */\nconst FIELDS: Record<string, readonly string[]> = {\n [STORES.links]: [\"seedB64\", \"encKeyB64\", \"participationSeed\", \"transportSeeds\", \"inviteCode\", \"pairedPeerKey\", \"peerTrust.verifiedKey\", \"ratchetState\"],\n [STORES.groups]: [\"invitation.seedB64\", \"entry.seedB64\", \"joining.seedB64\", \"state.seedB64\", \"state.secrets\", \"community.seedB64\", \"community.secrets\", \"community.entry.seedB64\", \"community.rv\"],\n [STORES.swaps]: [\"swap\", \"token\"],\n [STORES.melts]: [\"secrets\", \"outputs\"],\n // A sent token kept for Take it back, the outputs of a paid invoice not minted yet, and a Cashu review's swap and token.\n [STORES.payments]: [\"token\"],\n [STORES.quotes]: [\"outputs\"],\n [STORES.intents]: [\"prepared.swap\", \"prepared.token\"],\n};\n/** A group removed and invited again keeps the group it was (`previous`), with secrets of its own. */\nconst NESTED: Record<string, string> = { [STORES.groups]: \"previous\" };\n\n/**\n * A proof's secret is its row's key (`keyPath: \"secret\"`), and a sealed value can't be one: a sealed proof is kept under\n * this hash of its secret, the secret itself sealed beside it. The hash, not the secret, can be found again inside a\n * transaction, where WebCrypto can't be waited for.\n */\nexport const proofKey = (secret: string): string => bytesToHex(sha256(utf8ToBytes(`ghostly-proof/1\\n${secret}`)));\nconst SEALED_SECRET = \"sealedSecret\";\n\ntype Row = Record<string, unknown>;\ntype Seal = (json: string, at: SecretPlace) => SealedField;\n\nconst keyOf = (store: string, row: Row) =>\n String(store === STORES.melts || store === STORES.quotes ? row.quote : store === STORES.intents ? read(row, \"review.id\") : row.id);\n\nfunction read(row: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Row)[part] : undefined), row);\n}\n/** The row with `value` at `path`, copied along the way: the caller's row is never changed. */\nfunction written(row: Row, [part, ...rest]: string[], value: unknown): Row {\n return { ...row, [part]: rest.length ? written(row[part] as Row, rest, value) : value };\n}\n\n/** Every phase 1 value of a row that is there, with its path. */\nfunction places(store: string, row: Row, prefix = \"\"): { path: string; value: unknown }[] {\n const found = (FIELDS[store] ?? []).map((path) => ({ path: prefix + path, value: read(row, path) })).filter(({ value }) => value !== undefined);\n const nested = NESTED[store] && row[NESTED[store]];\n return nested && typeof nested === \"object\" ? [...found, ...places(store, nested as Row, `${prefix}${NESTED[store]}.`)] : found;\n}\n\nfunction sealWith<T>(store: string, value: T, seal: Seal): T {\n const row = value as Row;\n if (store === STORES.proofs) {\n if (row[SEALED_SECRET] !== undefined) return value;\n const secret = String(row.secret), key = proofKey(secret);\n return { ...row, secret: key, [SEALED_SECRET]: seal(JSON.stringify(secret), { store, key, field: \"secret\" }) } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) out = written(out, path.split(\".\"), seal(JSON.stringify(at), { store, key, field: path }));\n }\n return out as T;\n}\n\nconst slotOf = (json: string, at: SecretPlace) => [at.store, at.key, at.field, json].join(\"\\n\");\n\n/**\n * Seals made ahead of a transaction, for `row` to use inside it: IndexedDB commits a transaction that waits for\n * anything else, WebCrypto included. Whether rows are sealed is fixed when this is made, so a key dropped meanwhile\n * makes a write fail, never go out in the clear.\n */\nexport class RowSeals {\n /** Seals are made one batch after another, so writes that seal first are saved in the order they were asked for. */\n private static turn: Promise<unknown> = Promise.resolve();\n readonly on = hasDataKey();\n private ready = new Map<string, SealedField>();\n\n /** What these rows (or the proofs of these secrets) hold, sealed now. */\n async prepare(store: string, rows: readonly object[]): Promise<this> {\n if (!this.on) return this;\n const wanted = new Map<string, [string, SecretPlace]>();\n for (const row of rows) sealWith(store, row, (json, at) => { wanted.set(slotOf(json, at), [json, at]); return { v: 2, iv: \"\", ct: \"\" }; });\n const sealing = RowSeals.turn.then(async () => {\n for (const [slot, [json, at]] of wanted) if (!this.ready.has(slot)) this.ready.set(slot, await sealPlace(json, at));\n });\n RowSeals.turn = sealing.catch(() => {});\n await sealing;\n return this;\n }\n\n /** The row as it is written. Throws for a value not prepared: its transaction aborts, and nothing goes out in the clear. */\n row<T>(store: string, row: T): T {\n if (!this.on) return row;\n return sealWith(store, row, (json, at) => {\n const sealed = this.ready.get(slotOf(json, at));\n if (!sealed) throw new Error(\"A secret was not sealed before it was saved\");\n return sealed;\n });\n }\n}\n\nexport async function sealRow<T extends object>(store: string, row: T): Promise<T> {\n return (await new RowSeals().prepare(store, [row])).row(store, row);\n}\n\n/**\n * The store as a transaction's work sees it: what it puts is sealed from `seals`, and a proof is found by its secret.\n * Without the data key, the store itself.\n */\nexport function sealedStore(store: IDBObjectStore, seals: RowSeals): IDBObjectStore {\n if (!seals.on) return store;\n const proofs = store.name === STORES.proofs;\n return new Proxy(store, {\n get(target, name) {\n if (name === \"put\") return (row: object, ...key: [IDBValidKey?]) => target.put(seals.row(target.name, row), ...key);\n // A proof stored before the profile was encrypted is kept under its secret until the migration reseals it.\n if (proofs && name === \"delete\") return (secret: string) => { target.delete(secret); return target.delete(proofKey(secret)); };\n if (proofs && name === \"get\") return (secret: string) => target.get(proofKey(secret));\n const value: unknown = Reflect.get(target, name, target);\n return typeof value === \"function\" ? value.bind(target) : value;\n },\n });\n}\n\nfunction unsealed(): void {\n if (!takesUnsealed()) throw new Error(\"A secret of this profile was not sealed with its key\");\n}\n\n/** The row as the engine uses it: every sealed value opened, where it was. */\nexport async function openRow<T>(store: string, value: T): Promise<T> {\n if (!hasDataKey() || !value) return value;\n const row = value as Row;\n if (store === STORES.proofs) {\n const sealed = row[SEALED_SECRET];\n if (sealed === undefined) { unsealed(); return value; }\n const key = String(row.secret), secret = JSON.parse(await openSecret(sealed as SealedField, { store, key, field: \"secret\" })) as string;\n if (proofKey(secret) !== key) throw new Error(\"A sealed field could not be opened: it was changed, or it belongs to another record\");\n const { [SEALED_SECRET]: _sealed, ...rest } = row;\n return { ...rest, secret } as T;\n }\n const key = keyOf(store, row);\n let out = row;\n for (const { path, value: at } of places(store, row)) {\n if (!isSealedField(at)) { unsealed(); continue; }\n out = written(out, path.split(\".\"), JSON.parse(await openSecret(at, { store, key, field: path })));\n }\n return out as T;\n}\n\nexport function openRows<T>(store: string, rows: T[]): Promise<T[]> {\n return hasDataKey() ? Promise.all(rows.map((row) => openRow(store, row))) : Promise.resolve(rows);\n}\n","import { engineError, engineText } from \"@ghostly/core\";\nimport { STORES, openDb, store, transact, wrap } from \"../../shared/idb\";\nimport { openRow, openRows, sealRow } from \"../sealedRows\";\nimport type { IntentRepository, SavedIntent } from \"./coordinator\";\n/**\n * A USDT payment is one transaction at one account nonce. Another payment from the same account and chain that is\n * submitted or of unknown outcome holds its nonce until it confirms. A review made after it was sent took the next\n * nonce and may go at once. One made before (or read from an RPC that had not seen it yet) has the same or a lower\n * nonce: sent, it would replace the earlier transaction or be dropped, so it is refused. A row with no nonce refuses.\n */\nfunction nonceTaken(review:SavedIntent[\"review\"],intents:SavedIntent[]):boolean {\n if(review.method!==\"usdt\")return false;\n const from=review.evm?.from?.toLowerCase(), nonce=review.evm?.nonce;\n return intents.some(({review:other})=>other.id!==review.id && other.method===\"usdt\" && other.chainId===review.chainId && other.evm?.from?.toLowerCase()===from && [\"submitted\",\"unknown\"].includes(other.state)\n && !(typeof nonce===\"number\" && typeof other.evm?.nonce===\"number\" && nonce>other.evm.nonce));\n}\n/**\n * A Cashu review's swap and token are sealed when the profile is encrypted (sealedRows): they are read here opened.\n * `claim` and `cancel` change only the review, so they put back the row as it was read, sealed fields and all.\n */\nexport const intentRepository: IntentRepository = {\n async get(id) { return openRow(STORES.intents,await wrap<SavedIntent | undefined>((await store(STORES.intents,\"readonly\")).get(id))); },\n async list() { return openRows(STORES.intents,await wrap<SavedIntent[]>((await store(STORES.intents,\"readonly\")).getAll())); },\n async put(intent) { const row=await sealRow(STORES.intents,intent); await transact([STORES.intents],s=>{s[STORES.intents].put(row);}); },\n async claim(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n let reason=engineText(\"alreadySubmitted\");\n const request=tx.objectStore(STORES.intents).getAll();\n request.onsuccess=()=>{\n const intents:SavedIntent[]=request.result;\n saved=intents.find(item=>item.review.id===id)!;\n if(!saved || saved.review.state!==\"pending\") {tx.abort();return;}\n const duplicate=saved.review.requestId && intents.some(({review})=>review.id!==id && review.requestId===saved.review.requestId && review.linkId===saved.review.linkId && [\"submitted\",\"settled\",\"unknown\"].includes(review.state));\n if(duplicate){tx.abort();return;}\n if(nonceTaken(saved.review,intents)){reason=engineText(\"sentAfterReview\");tx.abort();return;}\n saved.review={...saved.review,state:\"submitted\",error:undefined,submittedAt:Date.now()};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(new Error(reason));\n });\n },\n async cancel(id) {\n const tx=(await openDb()).transaction(STORES.intents,\"readwrite\");\n return new Promise<SavedIntent>((resolve,reject)=>{\n let saved:SavedIntent;\n const request=tx.objectStore(STORES.intents).get(id);\n request.onsuccess=()=>{\n saved=request.result;\n if(!saved || saved.review.state!==\"pending\"){tx.abort();return;}\n saved.review={...saved.review,state:\"cancelled\"};\n tx.objectStore(STORES.intents).put(saved);\n };\n tx.oncomplete=()=>resolve(openRow(STORES.intents,saved));\n tx.onabort=tx.onerror=()=>reject(engineError(\"cannotCancelSubmitted\"));\n });\n },\n};\n/** Key for a wallet that needs no password: its seed is protected like the Cashu proofs in the same database. */\nexport function newDeviceKey():string {return btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/=+$/,\"\");}\nexport interface EncryptedSeed {version:1;salt:number[];iv:number[];ciphertext:number[]}\nasync function passwordKey(password:string,salt:Uint8Array<ArrayBuffer>) {\n const material=await crypto.subtle.importKey(\"raw\",new TextEncoder().encode(password),\"PBKDF2\",false,[\"deriveKey\"]);\n return crypto.subtle.deriveKey({name:\"PBKDF2\",hash:\"SHA-256\",salt,iterations:600000},material,{name:\"AES-GCM\",length:256},false,[\"encrypt\",\"decrypt\"]);\n}\nexport async function sealSeed(seed:string,password:string):Promise<EncryptedSeed> {\n if(password.length<12)throw new Error(\"Use at least 12 characters for the wallet password\");\n const salt=crypto.getRandomValues(new Uint8Array(16)),iv=crypto.getRandomValues(new Uint8Array(12));\n const ciphertext=await crypto.subtle.encrypt({name:\"AES-GCM\",iv},await passwordKey(password,salt),new TextEncoder().encode(seed));\n return {version:1,salt:[...salt],iv:[...iv],ciphertext:[...new Uint8Array(ciphertext)]};\n}\nexport async function unsealSeed(seed:EncryptedSeed,password:string):Promise<string> {\n if(seed.version!==1)throw new Error(\"Unsupported wallet backup version\");\n try {return new TextDecoder().decode(await crypto.subtle.decrypt({name:\"AES-GCM\",iv:new Uint8Array(seed.iv)},await passwordKey(password,new Uint8Array(seed.salt)),new Uint8Array(seed.ciphertext)));}\n catch {throw new Error(\"Could not unlock the wallet. Check the password and backup.\");}\n}\n","import { engineText } from \"@ghostly/core\";\n\n/**\n * A request's failure as a person says it, when the browser's own words say nothing: a request that timed out or was\n * given up (\"Fetch is aborted\" in Safari, \"signal timed out\" in Chromium) did not answer in time; one that never left\n * (\"Failed to fetch\", \"Load failed\") could not reach it. `host` names what was asked, when known. Anything else is\n * `null`: its own words are kept.\n */\nexport function networkReason(error: unknown, host?: string): string | null {\n const name = error instanceof Error ? error.name : \"\";\n const text = error instanceof Error ? error.message : String(error);\n if (name === \"AbortError\" || name === \"TimeoutError\" || /^(fetch is aborted|signal timed out|signal is aborted without reason|the (user|operation) (aborted a request|was aborted)\\.?|this operation was aborted|the operation timed out\\.?)$/i.test(text.trim()))\n return host ? engineText(\"hostTimedOut\", { host }) : engineText(\"networkTimedOut\");\n if (/^(failed to fetch|load failed|fetch failed|networkerror when attempting to fetch resource\\.?|network request failed)$/i.test(text.trim()))\n return host ? engineText(\"hostUnreachable\", { host }) : engineText(\"networkUnreachable\");\n return null;\n}\n\n/** A request URL's host, for a reason that names it; the URL itself when it does not parse. */\nexport function rpcHost(url: string): string {\n try { return new URL(url).host; } catch { return url; }\n}\n"],"mappings":";;;;;;;;;;AA6FA,SAAS,QAAQ,GAA6B;CAC5C,KAAK,MAAM,QAAQ;EAAC,EAAE;EAAI,EAAE;EAAO,EAAE;CAAK,GAAG,IAAI,CAAC,QAAQ,KAAK,SAAS,IAAI,GAAG,MAAM,IAAI,MAAM,8BAA8B;CAC7H,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO;EAAC;EAAmB,EAAE;EAAI,EAAE;EAAO,EAAE;EAAK,EAAE;CAAK,CAAC,C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,OAAO;AACT;;AAGA,SAAgB,QAAQ,KAAqB;CAC3C,IAAI;EAAE,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CAAM,QAAQ;EAAE,OAAO;CAAK;AACxD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { On as decodeBolt11 } from "./src-
|
|
1
|
+
import { On as decodeBolt11 } from "./src-CCt5s4DK.js";
|
|
2
2
|
import { t as NothingSpentError } from "./types-C4_KafL_.js";
|
|
3
|
-
import { n as parseNwcUri } from "./nwcProvider-
|
|
3
|
+
import { n as parseNwcUri } from "./nwcProvider-CGWqUjpB.js";
|
|
4
4
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
5
|
import * as nip04 from "nostr-tools/nip04";
|
|
6
6
|
import * as nip44 from "nostr-tools/nip44";
|
|
@@ -609,4 +609,4 @@ var NwcLightning = class NwcLightning {
|
|
|
609
609
|
//#endregion
|
|
610
610
|
export { NwcLightning };
|
|
611
611
|
|
|
612
|
-
//# sourceMappingURL=nwc-
|
|
612
|
+
//# sourceMappingURL=nwc-DoSEhUKb.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nwc-CHLWFV1R.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwc.ts"],"sourcesContent":["import { decodeBolt11 } from \"@ghostly/core\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport * as nip04 from \"nostr-tools/nip04\";\nimport * as nip44 from \"nostr-tools/nip44\";\nimport { finalizeEvent, getPublicKey, verifyEvent, type Event } from \"nostr-tools/pure\";\nimport type { InvoiceStatus, LightningCapabilities, LightningInfo, LightningInvoice, LightningPayResult, LightningPaymentRef, LightningPaymentStatus, LightningProvider } from \"./lightning\";\nimport { parseNwcUri, type NwcConnection } from \"./nwcProvider\";\nimport { NothingSpentError, type ProviderNetwork } from \"./types\";\n\n/**\n * Lightning through a wallet reached over Nostr Wallet Connect (NIP-47): Alby Hub, a node's NWC service, a\n * hosted wallet. The person pastes the wallet's `nostr+walletconnect://` URI; requests are signed with the\n * key it carries, encrypted to the wallet (NIP-44, or NIP-04 when its info event offers nothing else) and\n * sent through its relay; the answers come back the same way. That wallet holds the sats, applies its own\n * fee limit, and is custodial or not depending on what it is.\n *\n * Money safety (PROVIDERS.md): a request that never reached the relay, or an error code the wallet answers\n * before it tries to pay, is `NothingSpentError`. A `pay_invoice` whose answer does not come back in time,\n * or any other error, is an unknown outcome, and `paymentStatus` asks `lookup_invoice` until it ends.\n */\n\nconst KIND = { info: 13194, request: 23194, response: 23195 } as const;\n/** A relay message, an encrypted answer, an info event, an invoice: nothing bigger is read. */\nconst MAX_MESSAGE = 256 * 1024;\nconst MAX_CONTENT = 64 * 1024;\nconst MAX_INFO = 4096;\nconst MAX_INVOICE = 7089;\nconst CONNECT_MS = 10_000;\nconst ACK_MS = 10_000;\nconst REQUEST_MS = 20_000;\n/** A payment may take a while to route; an answer after this is an unknown outcome, looked up later. */\nconst PAY_MS = 90_000;\n/** The wallet must not start a payment it receives after this (NIP-47 `expiration`). */\nconst PAY_EXPIRY_S = 60;\n/** A payment the wallet never heard of is failed once its invoice can no longer be paid, with room for clocks. */\nconst EXPIRED_MARGIN_MS = 10 * 60_000;\nconst INVOICE_EXPIRY_S = 3600;\n\n/** Error codes a wallet answers before it tries to pay: nothing can have left it. (`BAD_REQUEST`: Alby Hub, an invoice it cannot read.) */\nconst REFUSED_BEFORE_PAYING = new Set([\"RATE_LIMITED\", \"NOT_IMPLEMENTED\", \"INSUFFICIENT_BALANCE\", \"QUOTA_EXCEEDED\", \"RESTRICTED\", \"UNAUTHORIZED\", \"UNSUPPORTED_ENCRYPTION\", \"BAD_REQUEST\"]);\nconst NETWORKS: Record<string, ProviderNetwork> = { mainnet: \"bitcoin\", bitcoin: \"bitcoin\", testnet: \"testnet\", testnet3: \"testnet\", testnet4: \"testnet\", signet: \"signet\", mutinynet: \"mutinynet\", regtest: \"regtest\" };\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst bytes = (text: string) => Uint8Array.from(text.match(/../g)!, (b) => parseInt(b, 16));\nconst now = () => Math.floor(Date.now() / 1000);\nconst isMsat = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;\n\n// -- one relay -----------------------------------------------------------------------------------------\n\n/** The request never reached the relay (not connected, refused by it): the wallet cannot have seen it. */\nexport class NotDelivered extends Error {\n constructor(message: string) { super(message); this.name = \"NotDelivered\"; }\n}\n/** An error the wallet answered, with its NIP-47 code. */\nexport class NwcError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = \"NwcError\"; }\n}\n/** No answer in time. The request may or may not have been acted on. */\nexport class NoAnswer extends Error {\n constructor(method: string) { super(`The wallet did not answer ${method} in time`); this.name = \"NoAnswer\"; }\n}\n\ninterface Filter { kinds: number[]; authors: string[]; \"#p\"?: string[]; since?: number; limit?: number }\ninterface Subscription { filter: Filter; event(event: unknown): void; eose?(): void }\n\n/**\n * A minimal NIP-01 client for one relay: it knows exactly whether an event was written to an open socket\n * and whether the relay acknowledged it, which is what tells \"nothing sent\" from \"unknown\" apart.\n * It reconnects when asked to send again, and subscriptions follow it.\n */\nexport class RelayConnection {\n private socket?: WebSocket;\n private opening?: Promise<WebSocket>;\n private readonly subs = new Map<string, Subscription>();\n private readonly acks = new Map<string, { ok(): void; fail(error: Error): void }>();\n private closed = false;\n\n constructor(readonly url: string, private readonly WebSocketImpl: typeof WebSocket = globalThis.WebSocket) {}\n\n open(): Promise<WebSocket> {\n if (this.closed) return Promise.reject(new Error(\"The wallet connection is closed\"));\n if (this.socket?.readyState === 1) return Promise.resolve(this.socket);\n if (!this.opening) {\n const opening = this.connectSocket();\n this.opening = opening;\n opening.catch(() => {}).finally(() => { if (this.opening === opening) this.opening = undefined; });\n }\n return this.opening;\n }\n\n private connectSocket(): Promise<WebSocket> {\n return new Promise<WebSocket>((resolve, reject) => {\n let settled = false;\n const socket = new this.WebSocketImpl(this.url);\n const done = (error?: Error) => {\n if (settled) return;\n settled = true; clearTimeout(timer);\n if (error) { try { socket.close(); } catch { /* already closed */ } reject(error); return; }\n if (this.closed) { socket.close(); reject(new Error(\"The wallet connection is closed\")); return; }\n this.socket = socket;\n for (const [id, sub] of this.subs) this.write([\"REQ\", id, sub.filter]);\n resolve(socket);\n };\n const timer = setTimeout(() => done(new Error(\"The wallet's relay did not answer\")), CONNECT_MS);\n socket.onopen = () => done();\n socket.onerror = () => done(new Error(\"Could not reach the wallet's relay\"));\n socket.onclose = () => {\n done(new Error(\"The wallet's relay closed the connection\"));\n if (this.socket !== socket) return;\n this.socket = undefined;\n // Written, not acknowledged: whether the relay kept it is unknown.\n for (const [id, ack] of this.acks) { this.acks.delete(id); ack.fail(new Error(\"The relay connection dropped before it confirmed the request\")); }\n };\n socket.onmessage = (message) => { if (this.socket === socket) this.receive(message.data); };\n });\n }\n\n subscribe(id: string, filter: Filter, sub: Omit<Subscription, \"filter\">) {\n this.subs.set(id, { ...sub, filter });\n this.write([\"REQ\", id, filter]);\n }\n\n unsubscribe(id: string) {\n if (this.subs.delete(id)) this.write([\"CLOSE\", id]);\n }\n\n /**\n * Events matching `filter` the relay has stored, until it says that is all (or `ms` pass). With\n * `waitForOne`, a relay that has none yet is listened to until one arrives live, within `ms`.\n */\n async fetch(filter: Filter, { ms = CONNECT_MS, waitForOne = false }: { ms?: number; waitForOne?: boolean } = {}): Promise<unknown[]> {\n await this.open();\n const id = `q${hex(crypto.getRandomValues(new Uint8Array(6)))}`, events: unknown[] = [];\n try {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n let stored = false;\n const finish = () => { clearTimeout(timer); resolve(); };\n this.subscribe(id, filter, {\n event: (e) => { if (events.length < 20) events.push(e); if (stored) finish(); },\n eose: () => { stored = true; if (events.length || !waitForOne) finish(); },\n });\n });\n } finally { this.unsubscribe(id); }\n return events;\n }\n\n /**\n * Resolves once the relay accepted the event. `NotDelivered` when it certainly did not reach it (no open\n * socket, refused); any other rejection means it may have.\n */\n async publish(event: Event): Promise<void> {\n let socket: WebSocket;\n try { socket = await this.open(); } catch (error) { throw new NotDelivered(error instanceof Error ? error.message : \"Could not reach the wallet's relay\"); }\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => { this.acks.delete(event.id); reject(new Error(\"The relay did not confirm the request\")); }, ACK_MS);\n this.acks.set(event.id, { ok: () => { clearTimeout(timer); resolve(); }, fail: (error) => { clearTimeout(timer); reject(error); } });\n // A socket that is not open anymore drops what it is given without a word: nothing was sent.\n if (socket.readyState !== 1 || socket !== this.socket) { this.acks.delete(event.id); clearTimeout(timer); reject(new NotDelivered(\"The relay connection closed\")); return; }\n socket.send(JSON.stringify([\"EVENT\", event]));\n });\n }\n\n close() {\n this.closed = true;\n for (const [id, ack] of this.acks) { this.acks.delete(id); ack.fail(new Error(\"The wallet connection is closed\")); }\n this.subs.clear();\n try { this.socket?.close(); } catch { /* already closed */ }\n this.socket = undefined;\n }\n\n private write(message: unknown[]) {\n if (this.socket?.readyState === 1) this.socket.send(JSON.stringify(message));\n }\n\n private receive(data: unknown) {\n if (typeof data !== \"string\" || data.length > MAX_MESSAGE) return;\n let message: unknown;\n try { message = JSON.parse(data); } catch { return; }\n if (!Array.isArray(message) || typeof message[1] !== \"string\") return;\n const [type, id] = message as [string, string];\n if (type === \"EVENT\") this.subs.get(id)?.event(message[2]);\n else if (type === \"EOSE\") this.subs.get(id)?.eose?.();\n else if (type === \"OK\") {\n const ack = this.acks.get(id);\n if (!ack) return;\n this.acks.delete(id);\n const reason = typeof message[3] === \"string\" ? message[3].slice(0, 120) : \"\";\n // \"duplicate:\" is a relay saying it already has it: delivered.\n if (message[2] === true || reason.startsWith(\"duplicate:\")) ack.ok();\n else ack.fail(new NotDelivered(`The relay refused the request${reason ? ` (${reason})` : \"\"}`));\n }\n }\n}\n\n// -- the wallet ----------------------------------------------------------------------------------------\n\n/** What `lookup_invoice` (and `make_invoice`) answer, as far as it is read. Amounts in millisats. */\ninterface NwcTransaction {\n type?: string;\n state?: string;\n invoice?: string;\n payment_hash?: string;\n preimage?: string;\n amount?: number;\n fees_paid?: number;\n settled_at?: number | null;\n expires_at?: number | null;\n}\n\nexport interface NwcOptions {\n signal?: AbortSignal;\n /** For tests: time limits, and a WebSocket other than the global one. */\n requestMs?: number;\n /** How long to wait for the wallet's info event (a new app connection publishes it a moment later). */\n infoMs?: number;\n payMs?: number;\n WebSocket?: typeof WebSocket;\n}\n\ninterface Pending { method: string; resolve(result: Record<string, unknown>): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }\n\nexport class NwcLightning implements LightningProvider {\n /** From the info event, then narrowed to what this connection may do (`get_info`). */\n capabilities: LightningCapabilities;\n private readonly clientPubkey: string;\n private readonly subscription = `nwc${hex(crypto.getRandomValues(new Uint8Array(6)))}`;\n private readonly pending = new Map<string, Pending>();\n private conversationKey?: Uint8Array;\n private network: ProviderNetwork = \"bitcoin\";\n private alias?: string;\n private closed = false;\n\n private constructor(private readonly connection: NwcConnection, private readonly relay: RelayConnection, readonly encryption: \"nip44_v2\" | \"nip04\", methods: ReadonlySet<string>, private readonly options: NwcOptions) {\n this.clientPubkey = getPublicKey(connection.secret);\n if (encryption === \"nip44_v2\") this.conversationKey = nip44.v2.utils.getConversationKey(connection.secret, connection.walletPubkey);\n this.capabilities = this.capabilitiesOf(methods);\n }\n\n /**\n * Reaches the wallet through the first relay that answers, reads its info event (the methods and the\n * encryption it offers), listens for its answers, and asks `get_info` for its network.\n */\n static async connect(uri: string, options: NwcOptions = {}): Promise<NwcLightning> {\n const connection = parseNwcUri(uri);\n options.signal?.throwIfAborted();\n let relay: RelayConnection | undefined, lastError: unknown;\n for (const url of connection.relays) {\n const candidate = new RelayConnection(url, options.WebSocket);\n try { await candidate.open(); relay = candidate; break; } catch (error) { candidate.close(); lastError = error; }\n }\n if (!relay) throw lastError instanceof Error ? lastError : new Error(\"Could not reach the wallet's relay\");\n let wallet: NwcLightning | undefined;\n try {\n const info = NwcLightning.newestInfo(await relay.fetch({ kinds: [KIND.info], authors: [connection.walletPubkey], limit: 5 }, { waitForOne: true, ms: options.infoMs }), connection.walletPubkey);\n if (!info) throw new Error(`The wallet has not published its NWC info on ${new URL(relay.url).host}: check the URI, or that the wallet is running`);\n const offered = (info.tags.find((t) => t[0] === \"encryption\")?.slice(1).join(\" \") ?? \"\").split(/\\s+/).filter(Boolean);\n // NIP-47: no `encryption` tag means a wallet that only speaks NIP-04.\n const encryption = offered.includes(\"nip44_v2\") ? \"nip44_v2\" : !offered.length || offered.includes(\"nip04\") ? \"nip04\" : undefined;\n if (!encryption) throw new Error(\"The wallet offers no encryption Ghostly speaks (NIP-44 or NIP-04)\");\n const methods = new Set(info.content.split(/\\s+/).filter(Boolean));\n wallet = new NwcLightning(connection, relay, encryption, methods, options);\n wallet.listen();\n if (options.signal) {\n const opened = wallet;\n if (options.signal.aborted) throw options.signal.reason;\n options.signal.addEventListener(\"abort\", () => void opened.close(), { once: true });\n }\n await wallet.readInfo(methods);\n return wallet;\n } catch (error) {\n if (wallet) await wallet.close(); else relay.close();\n throw error;\n }\n }\n\n private static newestInfo(events: unknown[], walletPubkey: string): Event | undefined {\n return (events as Event[])\n .filter((e) => e && e.kind === KIND.info && e.pubkey === walletPubkey && typeof e.content === \"string\" && e.content.length <= MAX_INFO && Array.isArray(e.tags) && verifyEvent(e))\n .sort((a, b) => b.created_at - a.created_at)[0];\n }\n\n private capabilitiesOf(methods: ReadonlySet<string>): LightningCapabilities {\n const lookup = methods.has(\"lookup_invoice\");\n // Paying needs looking up: a payment whose answer is lost could never be settled, and would hold the source.\n return { receive: methods.has(\"make_invoice\"), send: methods.has(\"pay_invoice\") && lookup, balance: methods.has(\"get_balance\"), lookup };\n }\n\n /**\n * `get_info` says the network and the methods this connection may use (the info event lists the\n * service's). Without it the wallet is taken to be on Bitcoin: a test wallet is then refused in the\n * Testnet mode and its invoices in the Mainnet one, while a real-money wallet never passes for a test one.\n */\n private async readInfo(offered: ReadonlySet<string>) {\n if (!offered.has(\"get_info\")) return;\n let info: Record<string, unknown>;\n try { info = await this.request(\"get_info\", {}); }\n catch (error) {\n // The service has it, this connection may not use it: the same as a wallet without it.\n if (error instanceof NwcError && [\"RESTRICTED\", \"UNAUTHORIZED\", \"NOT_IMPLEMENTED\"].includes(error.code)) return;\n throw error;\n }\n if (info.network !== undefined) {\n const network = typeof info.network === \"string\" ? NETWORKS[info.network.toLowerCase()] : undefined;\n if (!network) throw new Error(\"The wallet is on a network Ghostly does not know\");\n this.network = network;\n }\n if (typeof info.alias === \"string\" && info.alias.trim()) this.alias = info.alias.trim().slice(0, 40);\n if (Array.isArray(info.methods) && info.methods.every((m) => typeof m === \"string\")) {\n this.capabilities = this.capabilitiesOf(new Set(info.methods as string[]));\n }\n }\n\n private listen() {\n this.relay.subscribe(this.subscription, { kinds: [KIND.response], authors: [this.connection.walletPubkey], \"#p\": [this.clientPubkey], since: now() - 60 }, { event: (e) => this.answer(e) });\n }\n\n // -- requests and answers --\n\n private encrypt(text: string) {\n return this.conversationKey ? nip44.v2.encrypt(text, this.conversationKey) : nip04.encrypt(this.connection.secret, this.connection.walletPubkey, text);\n }\n\n private decrypt(content: string) {\n if (this.conversationKey && !content.includes(\"?iv=\")) return nip44.v2.decrypt(content, this.conversationKey);\n return nip04.decrypt(this.connection.secret, this.connection.walletPubkey, content);\n }\n\n /**\n * Sends one request and waits for its answer. `NotDelivered` when it never reached the relay; `NwcError`\n * for an error the wallet answered; `NoAnswer` (or a relay error) when the outcome is unknown.\n */\n async request(method: string, params: Record<string, unknown>, { ms = this.options.requestMs ?? REQUEST_MS, expiresIn }: { ms?: number; expiresIn?: number } = {}): Promise<Record<string, unknown>> {\n if (this.closed) throw new NotDelivered(\"The wallet connection is closed\");\n const tags = [[\"p\", this.connection.walletPubkey]];\n if (this.conversationKey) tags.push([\"encryption\", \"nip44_v2\"]);\n if (expiresIn) tags.push([\"expiration\", String(now() + expiresIn)]);\n const event = finalizeEvent({ kind: KIND.request, created_at: now(), tags, content: this.encrypt(JSON.stringify({ method, params })) }, this.connection.secret);\n const answer = new Promise<Record<string, unknown>>((resolve, reject) => {\n const timer = setTimeout(() => { this.pending.delete(event.id); reject(new NoAnswer(method)); }, ms);\n this.pending.set(event.id, { method, resolve, reject, timer });\n });\n // The answer can come before the relay's acknowledgement (or without one): whichever decides first wins.\n const delivered = this.relay.publish(event).then(() => undefined, (error: unknown) => {\n const waiting = this.pending.get(event.id);\n if (!(error instanceof NotDelivered) || !waiting) return undefined;\n clearTimeout(waiting.timer); this.pending.delete(event.id);\n return error;\n });\n return Promise.race([answer, delivered.then((error) => (error ? Promise.reject(error) : answer))]);\n }\n\n /** Reads an answer: from the wallet, signed, about a request of ours, of the method asked. Anything else is dropped. */\n private answer(raw: unknown) {\n const event = raw as Event;\n if (!event || typeof event !== \"object\" || event.kind !== KIND.response || event.pubkey !== this.connection.walletPubkey) return;\n if (typeof event.content !== \"string\" || event.content.length > MAX_CONTENT || !Array.isArray(event.tags)) return;\n const ref = event.tags.find((t) => Array.isArray(t) && t[0] === \"e\")?.[1];\n const pending = typeof ref === \"string\" ? this.pending.get(ref) : undefined;\n if (!pending || !event.tags.some((t) => Array.isArray(t) && t[0] === \"p\" && t[1] === this.clientPubkey)) return;\n if (!verifyEvent(event)) return;\n let body: { result_type?: unknown; error?: { code?: unknown; message?: unknown } | null; result?: unknown };\n try { body = JSON.parse(this.decrypt(event.content)); } catch { return; }\n if (!body || typeof body !== \"object\" || body.result_type !== pending.method) return;\n clearTimeout(pending.timer);\n this.pending.delete(ref!);\n if (body.error) {\n const code = typeof body.error.code === \"string\" ? body.error.code.slice(0, 40) : \"OTHER\";\n const message = typeof body.error.message === \"string\" && body.error.message.trim() ? body.error.message.trim().slice(0, 200) : code;\n pending.reject(new NwcError(code, message));\n } else if (body.result && typeof body.result === \"object\" && !Array.isArray(body.result)) pending.resolve(body.result as Record<string, unknown>);\n else pending.reject(new NwcError(\"OTHER\", \"The wallet sent an empty answer\"));\n }\n\n private async lookup(paymentHash: string): Promise<NwcTransaction> {\n const tx = await this.request(\"lookup_invoice\", { payment_hash: paymentHash }) as NwcTransaction;\n if (tx.payment_hash !== undefined && String(tx.payment_hash).toLowerCase() !== paymentHash) throw new Error(\"The wallet answered about another invoice\");\n return tx;\n }\n\n // -- LightningProvider --\n\n async info(): Promise<LightningInfo> {\n let balance: number | undefined;\n if (this.capabilities.balance) {\n const result = await this.request(\"get_balance\", {});\n if (!isMsat(result.balance)) throw new Error(\"The wallet returned an invalid balance\");\n balance = Math.floor(result.balance / 1000);\n }\n return { network: this.network, alias: `${this.alias ?? \"NWC wallet\"} via ${new URL(this.relay.url).host}`, balance };\n }\n\n async createInvoice(amount: number, memo?: string): Promise<LightningInvoice> {\n if (!Number.isSafeInteger(amount) || amount <= 0 || !Number.isSafeInteger(amount * 1000)) throw new Error(\"Invalid amount\");\n const result = await this.request(\"make_invoice\", { amount: amount * 1000, ...(memo ? { description: memo.slice(0, 200) } : {}), expiry: INVOICE_EXPIRY_S }) as NwcTransaction;\n const text = typeof result.invoice === \"string\" && result.invoice.length <= MAX_INVOICE ? result.invoice : \"\";\n const decoded = decodeBolt11(text);\n if (!decoded?.paymentHash || decoded.amountMsat !== BigInt(amount) * 1000n) throw new Error(\"The wallet returned an invoice that does not match the request\");\n if (result.payment_hash !== undefined && String(result.payment_hash).toLowerCase() !== decoded.paymentHash) throw new Error(\"The wallet returned an invoice that does not match its payment hash\");\n return { invoice: decoded.invoice, paymentHash: decoded.paymentHash, amount, expiresAt: decoded.expiresAt * 1000 };\n }\n\n async invoiceStatus(invoice: LightningInvoice): Promise<InvoiceStatus> {\n let tx: NwcTransaction;\n try { tx = await this.lookup(invoice.paymentHash); }\n catch (error) {\n if (error instanceof NwcError && error.code === \"NOT_FOUND\" && invoice.expiresAt < Date.now()) return { state: \"expired\" };\n throw error;\n }\n const expired = invoice.expiresAt < Date.now();\n if (tx.type === \"outgoing\") return { state: expired ? \"expired\" : \"open\" };\n // An incoming invoice's preimage is known before it is paid: only `state` or `settled_at` say it was.\n const state = tx.state ?? (tx.settled_at ? \"settled\" : \"pending\");\n if (state === \"settled\") return { state: \"paid\", amount: isMsat(tx.amount) ? Math.floor(tx.amount / 1000) : invoice.amount };\n if (state === \"expired\" || state === \"failed\") return { state: \"expired\" };\n return { state: expired ? \"expired\" : \"open\" };\n }\n\n /**\n * Pays through the wallet. NIP-47 carries no fee limit: the wallet applies its own, and the fee it\n * reports is passed on as it is.\n */\n async payInvoice(invoice: string, _maxFee: number): Promise<LightningPayResult> {\n const decoded = decodeBolt11(invoice);\n if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError(\"That invoice cannot be paid through NWC\");\n if (!this.capabilities.send) throw new NothingSpentError(\"This wallet connection may not pay and look up invoices\");\n let result: Record<string, unknown>;\n try {\n result = await this.request(\"pay_invoice\", { invoice: decoded.invoice }, { ms: this.options.payMs ?? PAY_MS, expiresIn: PAY_EXPIRY_S });\n } catch (error) {\n if (error instanceof NotDelivered) throw new NothingSpentError(`The payment did not reach the wallet: ${error.message}`);\n if (error instanceof NwcError && REFUSED_BEFORE_PAYING.has(error.code)) throw new NothingSpentError(`The wallet refused the payment: ${error.message}`);\n // Any other code may come after the wallet tried (Alby Hub answers INTERNAL with LND's failure reason).\n if (error instanceof NwcError) return this.confirmFailure(decoded.invoice, decoded.paymentHash, error);\n throw error;\n }\n const preimage = typeof result.preimage === \"string\" ? result.preimage.toLowerCase() : \"\";\n // \"Paid\" without a proof that pays this invoice is not taken at its word: it is looked up instead.\n if (!HEX64.test(preimage) || hex(sha256(bytes(preimage))) !== decoded.paymentHash) throw new Error(\"The wallet said it paid, without a proof that matches the invoice\");\n return { state: \"paid\", preimage, fee: isMsat(result.fees_paid) ? Math.ceil(result.fees_paid / 1000) : undefined };\n }\n\n /**\n * An error after the wallet may have tried (`PAYMENT_FAILED` \"may be due to a timeout\", `INTERNAL`,\n * `OTHER`…): its own record decides. Only a payment it records as failed is `NothingSpentError`; one it\n * records as paid is paid; anything else is pending, or unknown when it cannot be asked.\n */\n private async confirmFailure(invoice: string, paymentHash: string, failure: NwcError): Promise<LightningPayResult> {\n let status: LightningPaymentStatus;\n try { status = await this.paymentStatus({ invoice, paymentHash }); }\n catch { throw new Error(`The wallet said the payment failed (${failure.message}), and cannot confirm it yet`); }\n if (status.state === \"failed\") throw new NothingSpentError(`The payment failed: ${failure.message}`);\n return status.state === \"paid\" ? { state: \"paid\", fee: status.fee, preimage: status.preimage } : { state: \"pending\" };\n }\n\n async paymentStatus(payment: LightningPaymentRef): Promise<LightningPaymentStatus> {\n let tx: NwcTransaction;\n try { tx = await this.lookup(payment.paymentHash); }\n catch (error) {\n if (!(error instanceof NwcError && error.code === \"NOT_FOUND\")) throw error;\n // The wallet never heard of it: failed once nobody can pay that invoice anymore, until then it may still start.\n const expiresAt = (decodeBolt11(payment.invoice)?.expiresAt ?? Infinity) * 1000;\n return { state: expiresAt + EXPIRED_MARGIN_MS < Date.now() ? \"failed\" : \"pending\" };\n }\n // Our own invoice (a wallet paying itself): not an answer about the payment.\n if (tx.type === \"incoming\") return { state: \"pending\" };\n const preimage = typeof tx.preimage === \"string\" && HEX64.test(tx.preimage.toLowerCase()) ? tx.preimage.toLowerCase() : undefined;\n const proven = !!preimage && hex(sha256(bytes(preimage))) === payment.paymentHash;\n const state = tx.state ?? (tx.settled_at || proven ? \"settled\" : \"pending\");\n const fee = isMsat(tx.fees_paid) ? Math.ceil(tx.fees_paid / 1000) : undefined;\n if (state === \"settled\") {\n if (preimage && !proven) throw new Error(\"The wallet's proof of payment does not match the invoice\");\n return { state: \"paid\", fee, preimage };\n }\n if (state === \"failed\" || state === \"expired\") return { state: \"failed\" };\n return { state: \"pending\" };\n }\n\n async close() {\n if (this.closed) return;\n this.closed = true;\n for (const [id, pending] of this.pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.reject(new Error(\"The wallet connection is closed\")); }\n this.relay.close();\n }\n}\n"],"mappings":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YAAY,UAAU,WAAW,OAAO,EAAE,OAAO,SAAS;EACxE,OAAO,EAAE,OAAO,UAAU;CAC5B;CAEA,MAAM,QAAQ;EACZ,IAAI,KAAK,QAAQ;EACjB,KAAK,SAAS;EACd,KAAK,MAAM,CAAC,IAAI,YAAY,KAAK,SAAS;GAAE,aAAa,QAAQ,KAAK;GAAG,KAAK,QAAQ,OAAO,EAAE;GAAG,QAAQ,uBAAO,IAAI,MAAM,iCAAiC,CAAC;EAAG;EAChK,KAAK,MAAM,MAAM;CACnB;AACF"}
|
|
1
|
+
{"version":3,"file":"nwc-DoSEhUKb.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwc.ts"],"sourcesContent":["import { decodeBolt11 } from \"@ghostly/core\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport * as nip04 from \"nostr-tools/nip04\";\nimport * as nip44 from \"nostr-tools/nip44\";\nimport { finalizeEvent, getPublicKey, verifyEvent, type Event } from \"nostr-tools/pure\";\nimport type { InvoiceStatus, LightningCapabilities, LightningInfo, LightningInvoice, LightningPayResult, LightningPaymentRef, LightningPaymentStatus, LightningProvider } from \"./lightning\";\nimport { parseNwcUri, type NwcConnection } from \"./nwcProvider\";\nimport { NothingSpentError, type ProviderNetwork } from \"./types\";\n\n/**\n * Lightning through a wallet reached over Nostr Wallet Connect (NIP-47): Alby Hub, a node's NWC service, a\n * hosted wallet. The person pastes the wallet's `nostr+walletconnect://` URI; requests are signed with the\n * key it carries, encrypted to the wallet (NIP-44, or NIP-04 when its info event offers nothing else) and\n * sent through its relay; the answers come back the same way. That wallet holds the sats, applies its own\n * fee limit, and is custodial or not depending on what it is.\n *\n * Money safety (PROVIDERS.md): a request that never reached the relay, or an error code the wallet answers\n * before it tries to pay, is `NothingSpentError`. A `pay_invoice` whose answer does not come back in time,\n * or any other error, is an unknown outcome, and `paymentStatus` asks `lookup_invoice` until it ends.\n */\n\nconst KIND = { info: 13194, request: 23194, response: 23195 } as const;\n/** A relay message, an encrypted answer, an info event, an invoice: nothing bigger is read. */\nconst MAX_MESSAGE = 256 * 1024;\nconst MAX_CONTENT = 64 * 1024;\nconst MAX_INFO = 4096;\nconst MAX_INVOICE = 7089;\nconst CONNECT_MS = 10_000;\nconst ACK_MS = 10_000;\nconst REQUEST_MS = 20_000;\n/** A payment may take a while to route; an answer after this is an unknown outcome, looked up later. */\nconst PAY_MS = 90_000;\n/** The wallet must not start a payment it receives after this (NIP-47 `expiration`). */\nconst PAY_EXPIRY_S = 60;\n/** A payment the wallet never heard of is failed once its invoice can no longer be paid, with room for clocks. */\nconst EXPIRED_MARGIN_MS = 10 * 60_000;\nconst INVOICE_EXPIRY_S = 3600;\n\n/** Error codes a wallet answers before it tries to pay: nothing can have left it. (`BAD_REQUEST`: Alby Hub, an invoice it cannot read.) */\nconst REFUSED_BEFORE_PAYING = new Set([\"RATE_LIMITED\", \"NOT_IMPLEMENTED\", \"INSUFFICIENT_BALANCE\", \"QUOTA_EXCEEDED\", \"RESTRICTED\", \"UNAUTHORIZED\", \"UNSUPPORTED_ENCRYPTION\", \"BAD_REQUEST\"]);\nconst NETWORKS: Record<string, ProviderNetwork> = { mainnet: \"bitcoin\", bitcoin: \"bitcoin\", testnet: \"testnet\", testnet3: \"testnet\", testnet4: \"testnet\", signet: \"signet\", mutinynet: \"mutinynet\", regtest: \"regtest\" };\n\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst hex = (bytes: Uint8Array) => Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\nconst bytes = (text: string) => Uint8Array.from(text.match(/../g)!, (b) => parseInt(b, 16));\nconst now = () => Math.floor(Date.now() / 1000);\nconst isMsat = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 0;\n\n// -- one relay -----------------------------------------------------------------------------------------\n\n/** The request never reached the relay (not connected, refused by it): the wallet cannot have seen it. */\nexport class NotDelivered extends Error {\n constructor(message: string) { super(message); this.name = \"NotDelivered\"; }\n}\n/** An error the wallet answered, with its NIP-47 code. */\nexport class NwcError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = \"NwcError\"; }\n}\n/** No answer in time. The request may or may not have been acted on. */\nexport class NoAnswer extends Error {\n constructor(method: string) { super(`The wallet did not answer ${method} in time`); this.name = \"NoAnswer\"; }\n}\n\ninterface Filter { kinds: number[]; authors: string[]; \"#p\"?: string[]; since?: number; limit?: number }\ninterface Subscription { filter: Filter; event(event: unknown): void; eose?(): void }\n\n/**\n * A minimal NIP-01 client for one relay: it knows exactly whether an event was written to an open socket\n * and whether the relay acknowledged it, which is what tells \"nothing sent\" from \"unknown\" apart.\n * It reconnects when asked to send again, and subscriptions follow it.\n */\nexport class RelayConnection {\n private socket?: WebSocket;\n private opening?: Promise<WebSocket>;\n private readonly subs = new Map<string, Subscription>();\n private readonly acks = new Map<string, { ok(): void; fail(error: Error): void }>();\n private closed = false;\n\n constructor(readonly url: string, private readonly WebSocketImpl: typeof WebSocket = globalThis.WebSocket) {}\n\n open(): Promise<WebSocket> {\n if (this.closed) return Promise.reject(new Error(\"The wallet connection is closed\"));\n if (this.socket?.readyState === 1) return Promise.resolve(this.socket);\n if (!this.opening) {\n const opening = this.connectSocket();\n this.opening = opening;\n opening.catch(() => {}).finally(() => { if (this.opening === opening) this.opening = undefined; });\n }\n return this.opening;\n }\n\n private connectSocket(): Promise<WebSocket> {\n return new Promise<WebSocket>((resolve, reject) => {\n let settled = false;\n const socket = new this.WebSocketImpl(this.url);\n const done = (error?: Error) => {\n if (settled) return;\n settled = true; clearTimeout(timer);\n if (error) { try { socket.close(); } catch { /* already closed */ } reject(error); return; }\n if (this.closed) { socket.close(); reject(new Error(\"The wallet connection is closed\")); return; }\n this.socket = socket;\n for (const [id, sub] of this.subs) this.write([\"REQ\", id, sub.filter]);\n resolve(socket);\n };\n const timer = setTimeout(() => done(new Error(\"The wallet's relay did not answer\")), CONNECT_MS);\n socket.onopen = () => done();\n socket.onerror = () => done(new Error(\"Could not reach the wallet's relay\"));\n socket.onclose = () => {\n done(new Error(\"The wallet's relay closed the connection\"));\n if (this.socket !== socket) return;\n this.socket = undefined;\n // Written, not acknowledged: whether the relay kept it is unknown.\n for (const [id, ack] of this.acks) { this.acks.delete(id); ack.fail(new Error(\"The relay connection dropped before it confirmed the request\")); }\n };\n socket.onmessage = (message) => { if (this.socket === socket) this.receive(message.data); };\n });\n }\n\n subscribe(id: string, filter: Filter, sub: Omit<Subscription, \"filter\">) {\n this.subs.set(id, { ...sub, filter });\n this.write([\"REQ\", id, filter]);\n }\n\n unsubscribe(id: string) {\n if (this.subs.delete(id)) this.write([\"CLOSE\", id]);\n }\n\n /**\n * Events matching `filter` the relay has stored, until it says that is all (or `ms` pass). With\n * `waitForOne`, a relay that has none yet is listened to until one arrives live, within `ms`.\n */\n async fetch(filter: Filter, { ms = CONNECT_MS, waitForOne = false }: { ms?: number; waitForOne?: boolean } = {}): Promise<unknown[]> {\n await this.open();\n const id = `q${hex(crypto.getRandomValues(new Uint8Array(6)))}`, events: unknown[] = [];\n try {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n let stored = false;\n const finish = () => { clearTimeout(timer); resolve(); };\n this.subscribe(id, filter, {\n event: (e) => { if (events.length < 20) events.push(e); if (stored) finish(); },\n eose: () => { stored = true; if (events.length || !waitForOne) finish(); },\n });\n });\n } finally { this.unsubscribe(id); }\n return events;\n }\n\n /**\n * Resolves once the relay accepted the event. `NotDelivered` when it certainly did not reach it (no open\n * socket, refused); any other rejection means it may have.\n */\n async publish(event: Event): Promise<void> {\n let socket: WebSocket;\n try { socket = await this.open(); } catch (error) { throw new NotDelivered(error instanceof Error ? error.message : \"Could not reach the wallet's relay\"); }\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => { this.acks.delete(event.id); reject(new Error(\"The relay did not confirm the request\")); }, ACK_MS);\n this.acks.set(event.id, { ok: () => { clearTimeout(timer); resolve(); }, fail: (error) => { clearTimeout(timer); reject(error); } });\n // A socket that is not open anymore drops what it is given without a word: nothing was sent.\n if (socket.readyState !== 1 || socket !== this.socket) { this.acks.delete(event.id); clearTimeout(timer); reject(new NotDelivered(\"The relay connection closed\")); return; }\n socket.send(JSON.stringify([\"EVENT\", event]));\n });\n }\n\n close() {\n this.closed = true;\n for (const [id, ack] of this.acks) { this.acks.delete(id); ack.fail(new Error(\"The wallet connection is closed\")); }\n this.subs.clear();\n try { this.socket?.close(); } catch { /* already closed */ }\n this.socket = undefined;\n }\n\n private write(message: unknown[]) {\n if (this.socket?.readyState === 1) this.socket.send(JSON.stringify(message));\n }\n\n private receive(data: unknown) {\n if (typeof data !== \"string\" || data.length > MAX_MESSAGE) return;\n let message: unknown;\n try { message = JSON.parse(data); } catch { return; }\n if (!Array.isArray(message) || typeof message[1] !== \"string\") return;\n const [type, id] = message as [string, string];\n if (type === \"EVENT\") this.subs.get(id)?.event(message[2]);\n else if (type === \"EOSE\") this.subs.get(id)?.eose?.();\n else if (type === \"OK\") {\n const ack = this.acks.get(id);\n if (!ack) return;\n this.acks.delete(id);\n const reason = typeof message[3] === \"string\" ? message[3].slice(0, 120) : \"\";\n // \"duplicate:\" is a relay saying it already has it: delivered.\n if (message[2] === true || reason.startsWith(\"duplicate:\")) ack.ok();\n else ack.fail(new NotDelivered(`The relay refused the request${reason ? ` (${reason})` : \"\"}`));\n }\n }\n}\n\n// -- the wallet ----------------------------------------------------------------------------------------\n\n/** What `lookup_invoice` (and `make_invoice`) answer, as far as it is read. Amounts in millisats. */\ninterface NwcTransaction {\n type?: string;\n state?: string;\n invoice?: string;\n payment_hash?: string;\n preimage?: string;\n amount?: number;\n fees_paid?: number;\n settled_at?: number | null;\n expires_at?: number | null;\n}\n\nexport interface NwcOptions {\n signal?: AbortSignal;\n /** For tests: time limits, and a WebSocket other than the global one. */\n requestMs?: number;\n /** How long to wait for the wallet's info event (a new app connection publishes it a moment later). */\n infoMs?: number;\n payMs?: number;\n WebSocket?: typeof WebSocket;\n}\n\ninterface Pending { method: string; resolve(result: Record<string, unknown>): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout> }\n\nexport class NwcLightning implements LightningProvider {\n /** From the info event, then narrowed to what this connection may do (`get_info`). */\n capabilities: LightningCapabilities;\n private readonly clientPubkey: string;\n private readonly subscription = `nwc${hex(crypto.getRandomValues(new Uint8Array(6)))}`;\n private readonly pending = new Map<string, Pending>();\n private conversationKey?: Uint8Array;\n private network: ProviderNetwork = \"bitcoin\";\n private alias?: string;\n private closed = false;\n\n private constructor(private readonly connection: NwcConnection, private readonly relay: RelayConnection, readonly encryption: \"nip44_v2\" | \"nip04\", methods: ReadonlySet<string>, private readonly options: NwcOptions) {\n this.clientPubkey = getPublicKey(connection.secret);\n if (encryption === \"nip44_v2\") this.conversationKey = nip44.v2.utils.getConversationKey(connection.secret, connection.walletPubkey);\n this.capabilities = this.capabilitiesOf(methods);\n }\n\n /**\n * Reaches the wallet through the first relay that answers, reads its info event (the methods and the\n * encryption it offers), listens for its answers, and asks `get_info` for its network.\n */\n static async connect(uri: string, options: NwcOptions = {}): Promise<NwcLightning> {\n const connection = parseNwcUri(uri);\n options.signal?.throwIfAborted();\n let relay: RelayConnection | undefined, lastError: unknown;\n for (const url of connection.relays) {\n const candidate = new RelayConnection(url, options.WebSocket);\n try { await candidate.open(); relay = candidate; break; } catch (error) { candidate.close(); lastError = error; }\n }\n if (!relay) throw lastError instanceof Error ? lastError : new Error(\"Could not reach the wallet's relay\");\n let wallet: NwcLightning | undefined;\n try {\n const info = NwcLightning.newestInfo(await relay.fetch({ kinds: [KIND.info], authors: [connection.walletPubkey], limit: 5 }, { waitForOne: true, ms: options.infoMs }), connection.walletPubkey);\n if (!info) throw new Error(`The wallet has not published its NWC info on ${new URL(relay.url).host}: check the URI, or that the wallet is running`);\n const offered = (info.tags.find((t) => t[0] === \"encryption\")?.slice(1).join(\" \") ?? \"\").split(/\\s+/).filter(Boolean);\n // NIP-47: no `encryption` tag means a wallet that only speaks NIP-04.\n const encryption = offered.includes(\"nip44_v2\") ? \"nip44_v2\" : !offered.length || offered.includes(\"nip04\") ? \"nip04\" : undefined;\n if (!encryption) throw new Error(\"The wallet offers no encryption Ghostly speaks (NIP-44 or NIP-04)\");\n const methods = new Set(info.content.split(/\\s+/).filter(Boolean));\n wallet = new NwcLightning(connection, relay, encryption, methods, options);\n wallet.listen();\n if (options.signal) {\n const opened = wallet;\n if (options.signal.aborted) throw options.signal.reason;\n options.signal.addEventListener(\"abort\", () => void opened.close(), { once: true });\n }\n await wallet.readInfo(methods);\n return wallet;\n } catch (error) {\n if (wallet) await wallet.close(); else relay.close();\n throw error;\n }\n }\n\n private static newestInfo(events: unknown[], walletPubkey: string): Event | undefined {\n return (events as Event[])\n .filter((e) => e && e.kind === KIND.info && e.pubkey === walletPubkey && typeof e.content === \"string\" && e.content.length <= MAX_INFO && Array.isArray(e.tags) && verifyEvent(e))\n .sort((a, b) => b.created_at - a.created_at)[0];\n }\n\n private capabilitiesOf(methods: ReadonlySet<string>): LightningCapabilities {\n const lookup = methods.has(\"lookup_invoice\");\n // Paying needs looking up: a payment whose answer is lost could never be settled, and would hold the source.\n return { receive: methods.has(\"make_invoice\"), send: methods.has(\"pay_invoice\") && lookup, balance: methods.has(\"get_balance\"), lookup };\n }\n\n /**\n * `get_info` says the network and the methods this connection may use (the info event lists the\n * service's). Without it the wallet is taken to be on Bitcoin: a test wallet is then refused in the\n * Testnet mode and its invoices in the Mainnet one, while a real-money wallet never passes for a test one.\n */\n private async readInfo(offered: ReadonlySet<string>) {\n if (!offered.has(\"get_info\")) return;\n let info: Record<string, unknown>;\n try { info = await this.request(\"get_info\", {}); }\n catch (error) {\n // The service has it, this connection may not use it: the same as a wallet without it.\n if (error instanceof NwcError && [\"RESTRICTED\", \"UNAUTHORIZED\", \"NOT_IMPLEMENTED\"].includes(error.code)) return;\n throw error;\n }\n if (info.network !== undefined) {\n const network = typeof info.network === \"string\" ? NETWORKS[info.network.toLowerCase()] : undefined;\n if (!network) throw new Error(\"The wallet is on a network Ghostly does not know\");\n this.network = network;\n }\n if (typeof info.alias === \"string\" && info.alias.trim()) this.alias = info.alias.trim().slice(0, 40);\n if (Array.isArray(info.methods) && info.methods.every((m) => typeof m === \"string\")) {\n this.capabilities = this.capabilitiesOf(new Set(info.methods as string[]));\n }\n }\n\n private listen() {\n this.relay.subscribe(this.subscription, { kinds: [KIND.response], authors: [this.connection.walletPubkey], \"#p\": [this.clientPubkey], since: now() - 60 }, { event: (e) => this.answer(e) });\n }\n\n // -- requests and answers --\n\n private encrypt(text: string) {\n return this.conversationKey ? nip44.v2.encrypt(text, this.conversationKey) : nip04.encrypt(this.connection.secret, this.connection.walletPubkey, text);\n }\n\n private decrypt(content: string) {\n if (this.conversationKey && !content.includes(\"?iv=\")) return nip44.v2.decrypt(content, this.conversationKey);\n return nip04.decrypt(this.connection.secret, this.connection.walletPubkey, content);\n }\n\n /**\n * Sends one request and waits for its answer. `NotDelivered` when it never reached the relay; `NwcError`\n * for an error the wallet answered; `NoAnswer` (or a relay error) when the outcome is unknown.\n */\n async request(method: string, params: Record<string, unknown>, { ms = this.options.requestMs ?? REQUEST_MS, expiresIn }: { ms?: number; expiresIn?: number } = {}): Promise<Record<string, unknown>> {\n if (this.closed) throw new NotDelivered(\"The wallet connection is closed\");\n const tags = [[\"p\", this.connection.walletPubkey]];\n if (this.conversationKey) tags.push([\"encryption\", \"nip44_v2\"]);\n if (expiresIn) tags.push([\"expiration\", String(now() + expiresIn)]);\n const event = finalizeEvent({ kind: KIND.request, created_at: now(), tags, content: this.encrypt(JSON.stringify({ method, params })) }, this.connection.secret);\n const answer = new Promise<Record<string, unknown>>((resolve, reject) => {\n const timer = setTimeout(() => { this.pending.delete(event.id); reject(new NoAnswer(method)); }, ms);\n this.pending.set(event.id, { method, resolve, reject, timer });\n });\n // The answer can come before the relay's acknowledgement (or without one): whichever decides first wins.\n const delivered = this.relay.publish(event).then(() => undefined, (error: unknown) => {\n const waiting = this.pending.get(event.id);\n if (!(error instanceof NotDelivered) || !waiting) return undefined;\n clearTimeout(waiting.timer); this.pending.delete(event.id);\n return error;\n });\n return Promise.race([answer, delivered.then((error) => (error ? Promise.reject(error) : answer))]);\n }\n\n /** Reads an answer: from the wallet, signed, about a request of ours, of the method asked. Anything else is dropped. */\n private answer(raw: unknown) {\n const event = raw as Event;\n if (!event || typeof event !== \"object\" || event.kind !== KIND.response || event.pubkey !== this.connection.walletPubkey) return;\n if (typeof event.content !== \"string\" || event.content.length > MAX_CONTENT || !Array.isArray(event.tags)) return;\n const ref = event.tags.find((t) => Array.isArray(t) && t[0] === \"e\")?.[1];\n const pending = typeof ref === \"string\" ? this.pending.get(ref) : undefined;\n if (!pending || !event.tags.some((t) => Array.isArray(t) && t[0] === \"p\" && t[1] === this.clientPubkey)) return;\n if (!verifyEvent(event)) return;\n let body: { result_type?: unknown; error?: { code?: unknown; message?: unknown } | null; result?: unknown };\n try { body = JSON.parse(this.decrypt(event.content)); } catch { return; }\n if (!body || typeof body !== \"object\" || body.result_type !== pending.method) return;\n clearTimeout(pending.timer);\n this.pending.delete(ref!);\n if (body.error) {\n const code = typeof body.error.code === \"string\" ? body.error.code.slice(0, 40) : \"OTHER\";\n const message = typeof body.error.message === \"string\" && body.error.message.trim() ? body.error.message.trim().slice(0, 200) : code;\n pending.reject(new NwcError(code, message));\n } else if (body.result && typeof body.result === \"object\" && !Array.isArray(body.result)) pending.resolve(body.result as Record<string, unknown>);\n else pending.reject(new NwcError(\"OTHER\", \"The wallet sent an empty answer\"));\n }\n\n private async lookup(paymentHash: string): Promise<NwcTransaction> {\n const tx = await this.request(\"lookup_invoice\", { payment_hash: paymentHash }) as NwcTransaction;\n if (tx.payment_hash !== undefined && String(tx.payment_hash).toLowerCase() !== paymentHash) throw new Error(\"The wallet answered about another invoice\");\n return tx;\n }\n\n // -- LightningProvider --\n\n async info(): Promise<LightningInfo> {\n let balance: number | undefined;\n if (this.capabilities.balance) {\n const result = await this.request(\"get_balance\", {});\n if (!isMsat(result.balance)) throw new Error(\"The wallet returned an invalid balance\");\n balance = Math.floor(result.balance / 1000);\n }\n return { network: this.network, alias: `${this.alias ?? \"NWC wallet\"} via ${new URL(this.relay.url).host}`, balance };\n }\n\n async createInvoice(amount: number, memo?: string): Promise<LightningInvoice> {\n if (!Number.isSafeInteger(amount) || amount <= 0 || !Number.isSafeInteger(amount * 1000)) throw new Error(\"Invalid amount\");\n const result = await this.request(\"make_invoice\", { amount: amount * 1000, ...(memo ? { description: memo.slice(0, 200) } : {}), expiry: INVOICE_EXPIRY_S }) as NwcTransaction;\n const text = typeof result.invoice === \"string\" && result.invoice.length <= MAX_INVOICE ? result.invoice : \"\";\n const decoded = decodeBolt11(text);\n if (!decoded?.paymentHash || decoded.amountMsat !== BigInt(amount) * 1000n) throw new Error(\"The wallet returned an invoice that does not match the request\");\n if (result.payment_hash !== undefined && String(result.payment_hash).toLowerCase() !== decoded.paymentHash) throw new Error(\"The wallet returned an invoice that does not match its payment hash\");\n return { invoice: decoded.invoice, paymentHash: decoded.paymentHash, amount, expiresAt: decoded.expiresAt * 1000 };\n }\n\n async invoiceStatus(invoice: LightningInvoice): Promise<InvoiceStatus> {\n let tx: NwcTransaction;\n try { tx = await this.lookup(invoice.paymentHash); }\n catch (error) {\n if (error instanceof NwcError && error.code === \"NOT_FOUND\" && invoice.expiresAt < Date.now()) return { state: \"expired\" };\n throw error;\n }\n const expired = invoice.expiresAt < Date.now();\n if (tx.type === \"outgoing\") return { state: expired ? \"expired\" : \"open\" };\n // An incoming invoice's preimage is known before it is paid: only `state` or `settled_at` say it was.\n const state = tx.state ?? (tx.settled_at ? \"settled\" : \"pending\");\n if (state === \"settled\") return { state: \"paid\", amount: isMsat(tx.amount) ? Math.floor(tx.amount / 1000) : invoice.amount };\n if (state === \"expired\" || state === \"failed\") return { state: \"expired\" };\n return { state: expired ? \"expired\" : \"open\" };\n }\n\n /**\n * Pays through the wallet. NIP-47 carries no fee limit: the wallet applies its own, and the fee it\n * reports is passed on as it is.\n */\n async payInvoice(invoice: string, _maxFee: number): Promise<LightningPayResult> {\n const decoded = decodeBolt11(invoice);\n if (!decoded?.paymentHash || decoded.amountSat === null) throw new NothingSpentError(\"That invoice cannot be paid through NWC\");\n if (!this.capabilities.send) throw new NothingSpentError(\"This wallet connection may not pay and look up invoices\");\n let result: Record<string, unknown>;\n try {\n result = await this.request(\"pay_invoice\", { invoice: decoded.invoice }, { ms: this.options.payMs ?? PAY_MS, expiresIn: PAY_EXPIRY_S });\n } catch (error) {\n if (error instanceof NotDelivered) throw new NothingSpentError(`The payment did not reach the wallet: ${error.message}`);\n if (error instanceof NwcError && REFUSED_BEFORE_PAYING.has(error.code)) throw new NothingSpentError(`The wallet refused the payment: ${error.message}`);\n // Any other code may come after the wallet tried (Alby Hub answers INTERNAL with LND's failure reason).\n if (error instanceof NwcError) return this.confirmFailure(decoded.invoice, decoded.paymentHash, error);\n throw error;\n }\n const preimage = typeof result.preimage === \"string\" ? result.preimage.toLowerCase() : \"\";\n // \"Paid\" without a proof that pays this invoice is not taken at its word: it is looked up instead.\n if (!HEX64.test(preimage) || hex(sha256(bytes(preimage))) !== decoded.paymentHash) throw new Error(\"The wallet said it paid, without a proof that matches the invoice\");\n return { state: \"paid\", preimage, fee: isMsat(result.fees_paid) ? Math.ceil(result.fees_paid / 1000) : undefined };\n }\n\n /**\n * An error after the wallet may have tried (`PAYMENT_FAILED` \"may be due to a timeout\", `INTERNAL`,\n * `OTHER`…): its own record decides. Only a payment it records as failed is `NothingSpentError`; one it\n * records as paid is paid; anything else is pending, or unknown when it cannot be asked.\n */\n private async confirmFailure(invoice: string, paymentHash: string, failure: NwcError): Promise<LightningPayResult> {\n let status: LightningPaymentStatus;\n try { status = await this.paymentStatus({ invoice, paymentHash }); }\n catch { throw new Error(`The wallet said the payment failed (${failure.message}), and cannot confirm it yet`); }\n if (status.state === \"failed\") throw new NothingSpentError(`The payment failed: ${failure.message}`);\n return status.state === \"paid\" ? { state: \"paid\", fee: status.fee, preimage: status.preimage } : { state: \"pending\" };\n }\n\n async paymentStatus(payment: LightningPaymentRef): Promise<LightningPaymentStatus> {\n let tx: NwcTransaction;\n try { tx = await this.lookup(payment.paymentHash); }\n catch (error) {\n if (!(error instanceof NwcError && error.code === \"NOT_FOUND\")) throw error;\n // The wallet never heard of it: failed once nobody can pay that invoice anymore, until then it may still start.\n const expiresAt = (decodeBolt11(payment.invoice)?.expiresAt ?? Infinity) * 1000;\n return { state: expiresAt + EXPIRED_MARGIN_MS < Date.now() ? \"failed\" : \"pending\" };\n }\n // Our own invoice (a wallet paying itself): not an answer about the payment.\n if (tx.type === \"incoming\") return { state: \"pending\" };\n const preimage = typeof tx.preimage === \"string\" && HEX64.test(tx.preimage.toLowerCase()) ? tx.preimage.toLowerCase() : undefined;\n const proven = !!preimage && hex(sha256(bytes(preimage))) === payment.paymentHash;\n const state = tx.state ?? (tx.settled_at || proven ? \"settled\" : \"pending\");\n const fee = isMsat(tx.fees_paid) ? Math.ceil(tx.fees_paid / 1000) : undefined;\n if (state === \"settled\") {\n if (preimage && !proven) throw new Error(\"The wallet's proof of payment does not match the invoice\");\n return { state: \"paid\", fee, preimage };\n }\n if (state === \"failed\" || state === \"expired\") return { state: \"failed\" };\n return { state: \"pending\" };\n }\n\n async close() {\n if (this.closed) return;\n this.closed = true;\n for (const [id, pending] of this.pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.reject(new Error(\"The wallet connection is closed\")); }\n this.relay.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,IAAM,OAAO;CAAE,MAAM;CAAO,SAAS;CAAO,UAAU;AAAM;;AAE5D,IAAM,cAAc;AACpB,IAAM,cAAc;AACpB,IAAM,WAAW;AACjB,IAAM,cAAc;AACpB,IAAM,aAAa;AACnB,IAAM,SAAS;AACf,IAAM,aAAa;;AAEnB,IAAM,SAAS;;AAEf,IAAM,eAAe;;AAErB,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;;AAGzB,IAAM,wCAAwB,IAAI,IAAI;CAAC;CAAgB;CAAmB;CAAwB;CAAkB;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= {
|
|
|
67
67
|
parseNwcUri(secrets.uri ?? "");
|
|
68
68
|
},
|
|
69
69
|
async create({ secrets }, host) {
|
|
70
|
-
const { NwcLightning } = await import("./nwc-
|
|
70
|
+
const { NwcLightning } = await import("./nwc-DoSEhUKb.js");
|
|
71
71
|
return NwcLightning.connect(secrets.uri, { signal: host.signal });
|
|
72
72
|
}
|
|
73
73
|
};
|
|
74
74
|
//#endregion
|
|
75
75
|
export { parseNwcUri as n, nwc as t };
|
|
76
76
|
|
|
77
|
-
//# sourceMappingURL=nwcProvider-
|
|
77
|
+
//# sourceMappingURL=nwcProvider-CGWqUjpB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nwcProvider-
|
|
1
|
+
{"version":3,"file":"nwcProvider-CGWqUjpB.js","names":[],"sources":["../../../browser/src/engine/paymentAdapters/providers/nwcProvider.ts"],"sourcesContent":["import type { LightningProviderDescriptor } from \"./lightning\";\nimport { PROVIDER_PLATFORMS } from \"./types\";\n\n/**\n * Nostr Wallet Connect as the source picker lists it, and its connection URI. The client (`./nwc`) and its NIP-04 /\n * NIP-44 encryption load when a wallet connects, not with the app.\n */\n\nconst MAX_URI = 2048;\nconst MAX_RELAYS = 5;\nconst HEX64 = /^[0-9a-f]{64}$/;\nconst bytes = (text: string) => Uint8Array.from(text.match(/../g)!, (b) => parseInt(b, 16));\n\nexport interface NwcConnection {\n walletPubkey: string;\n relays: string[];\n /** The client key the wallet granted: a secret. */\n secret: Uint8Array;\n}\n\n/** Only secure relays, except on this machine (a local test relay). */\nfunction checkRelay(address: string): string {\n let relay: URL;\n try { relay = new URL(address); } catch { throw new Error(\"The connection URI has a relay that is not a URL\"); }\n if (relay.username || relay.password || relay.hash) throw new Error(\"The connection URI has a relay with credentials in it\");\n const loopback = [\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(relay.hostname);\n if (!(relay.protocol === \"wss:\" || (relay.protocol === \"ws:\" && loopback))) throw new Error(\"Use a wallet whose relay is secure (wss://)\");\n return relay.href;\n}\n\n/** Reads a `nostr+walletconnect://` URI. Its errors never repeat it: it holds a secret. */\nexport function parseNwcUri(input: string): NwcConnection {\n const text = (input ?? \"\").trim();\n if (text.length > MAX_URI) throw new Error(\"That connection URI is too long\");\n const match = /^(?:nostr\\+walletconnect|nostrwalletconnect):(?:\\/\\/)?([0-9a-fA-F]{64})\\/?\\?([^#]*)$/.exec(text);\n if (!match) throw new Error(\"That is not a Nostr Wallet Connect URI (nostr+walletconnect://…)\");\n const params = new URLSearchParams(match[2]);\n const secret = (params.get(\"secret\") ?? \"\").toLowerCase();\n if (!HEX64.test(secret) || /^0+$/.test(secret)) throw new Error(\"The connection URI has no valid secret\");\n const relays = [...new Set(params.getAll(\"relay\").map(checkRelay))];\n if (!relays.length) throw new Error(\"The connection URI names no relay\");\n if (relays.length > MAX_RELAYS) throw new Error(\"The connection URI names too many relays\");\n return { walletPubkey: match[1].toLowerCase(), relays, secret: bytes(secret) };\n}\n\nexport const nwc: LightningProviderDescriptor = {\n id: \"nwc\",\n label: \"Nostr Wallet Connect\",\n kind: \"lightning\",\n description: \"A wallet you connect with its NWC URI (Alby Hub, a node's NWC service, a hosted wallet). That wallet holds the sats and sets its own fee limit: custodial or not depends on the wallet.\",\n networks: [\"bitcoin\", \"testnet\", \"signet\", \"mutinynet\", \"regtest\"],\n platforms: PROVIDER_PLATFORMS,\n fields: [{\n name: \"uri\", label: \"Connection URI\", kind: \"secret\", placeholder: \"nostr+walletconnect://…\",\n help: \"From your wallet's app connections. Allow making, paying and looking up invoices, and reading the balance.\",\n }],\n validate({ secrets }) { parseNwcUri(secrets.uri ?? \"\"); },\n async create({ secrets }, host) {\n const { NwcLightning } = await import(\"./nwc\");\n return NwcLightning.connect(secrets.uri, { signal: host.signal });\n },\n};\n"],"mappings":";;;;;;AAQA,IAAM,UAAU;AAChB,IAAM,aAAa;AACnB,IAAM,QAAQ;AACd,IAAM,SAAS,SAAiB,WAAW,KAAK,KAAK,MAAM,KAAK,IAA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;EAAC;EAAW;EAAW;EAAU;EAAa;CAAS;CACjE,WAAW;CACX,QAAQ,CAAC;EACP,MAAM;EAAO,OAAO;EAAkB,MAAM;EAAU,aAAa;EACnE,MAAM;CACR,CAAC;CACD,SAAS,EAAE,WAAW;EAAE,YAAY,QAAQ,OAAO,EAAE;CAAG;CACxD,MAAM,OAAO,EAAE,WAAW,MAAM;EAC9B,MAAM,EAAE,iBAAiB,MAAM,OAAO;EACtC,OAAO,aAAa,QAAQ,QAAQ,KAAK,EAAE,QAAQ,KAAK,OAAO,CAAC;CAClE;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Ai as boundVerifiedIdentity, Oi as IdentityCheckUnavailable } from "./src-CCt5s4DK.js";
|
|
2
2
|
import { l as providerDescriptorProblems } from "./types-C4_KafL_.js";
|
|
3
3
|
//#region ../browser/src/shared/features.ts
|
|
4
4
|
/**
|
|
@@ -278,4 +278,4 @@ var ownDid = () => source();
|
|
|
278
278
|
//#endregion
|
|
279
279
|
export { registeredLightningProviders as a, boundedIdentityFetch as c, testSwitch as d, registeredIdentityProviders as i, verifyIdentity as l, setOwnDidSource as n, registeredOnchainProviders as o, onAdaptersChanged as r, reserveAdapterIds as s, ownDid as t, testBuild as u };
|
|
280
280
|
|
|
281
|
-
//# sourceMappingURL=ownDid-
|
|
281
|
+
//# sourceMappingURL=ownDid-CbGjRLBn.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownDid-yXtY_1B5.js","names":[],"sources":["../../../browser/src/shared/features.ts","../../../browser/src/proofs/verify.ts","../../../browser/src/plugins/bundled.ts","../../../browser/src/plugins/registry.ts","../../../browser/src/proofs/ownDid.ts"],"sourcesContent":["/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapterRegistry(): void {\n const s = store();\n s.plugins.clear(); s.seeded = false;\n for (const kind of KINDS) s.reserved[kind].clear();\n notify(s);\n}\n","/**\n * The profile's own Ghostly did:dht, which the DID provider refuses as an external identity. The UI and the engine each\n * set where to read it. Here, not in the provider, so setting it does not load the providers.\n */\nlet source: () => string | undefined = () => undefined;\nexport function setOwnDidSource(read: () => string | undefined): void { source = read; }\nexport const ownDid = (): string | undefined => source();\n"],"mappings":";;;;;;;;;AAgBA,IAAa,kBAA2B;CAAE,IAAI;EAAE,OAAiC;CAAyC,QAAQ;EAAE,OAAO;CAAO;AAAE;;;;;AAMpJ,IAAa,cAAc,QAA+B;CACxD,IAAI,CAAC,UAAU,GAAG,OAAO;CACzB,IAAI;EAAE,OAAO,WAAW,cAAc,QAAQ,GAAG,KAAK;CAAM,QAAQ;EAAE,OAAO;CAAM;AACrF;;;ACtBA,IAAM,MAAM;;;;;;;AAQZ,eAAsB,eAAe,WAA6C,WAA8B,UAAmB,KAA+C;CAChL,MAAM,EAAE,YAAY;CACpB,MAAM,WAAW,UAAU,MAAK,MAAK,EAAE,OAAO,QAAQ,QAAQ;CAC9D,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,8CAA8C;CAC7E,IAAI,QAAQ,YAAY,QAAQ,WAAW,KAAK,IAAI,SAAS,SAAS,UAAU,KAAA,MAA0B,GAAG,MAAM,IAAI,MAAM,0DAA0D;CACvL,IAAI,KAAK,UAAU,YAAY,IAAI,CAAC,CAAC,SAAA,OAAgC,MAAM,IAAI,MAAM,oBAAoB;CACzG,MAAM,SAAS,SAAS,cAAc,QAAQ;CAC9C,MAAM,WAAW,sBAAsB,MAAM,SAAS,OAAO,WAAW,QAAQ,GAAG,CAAC;CACpF,IAAI,SAAS,aAAa,oBAAoB,SAAS,YAAY,QAAQ,SAAS,MAAM,IAAI,MAAM,sCAAsC;CAC1I,IAAI,SAAS,aAAa,uBAAuB,CAAC,SAAS,UAAU,MAAM,IAAI,MAAM,0CAA0C;CAC/H,OAAO;AACT;;AAGA,SAAgB,mBAAmB,GAAoC;CACrE,MAAM,WAAqB,CAAC;CAC5B,IAAI,CAAC,yBAAyB,KAAK,EAAE,EAAE,GAAG,SAAS,KAAK,sCAAsC;CAC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AAO,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,OAAO,CAAC;AAAG;AACrH,SAAgB,+BAAuE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,aAAa,CAAC,CAAC;AAAG;AACvJ,SAAgB,6BAAmE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,CAAC,CAAC;AAAG;AACjJ,SAAgB,8BAAgE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,cAAc,CAAC,CAAC;AAAG;;;;;AAMjJ,SAAS,OAAO;CACd,MAAM,IAAI,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;;;;;;ACrJA,IAAI,eAAyC,KAAA;AAC7C,SAAgB,gBAAgB,MAAsC;CAAE,SAAS;AAAM;AACvF,IAAa,eAAmC,OAAO"}
|
|
1
|
+
{"version":3,"file":"ownDid-CbGjRLBn.js","names":[],"sources":["../../../browser/src/shared/features.ts","../../../browser/src/proofs/verify.ts","../../../browser/src/plugins/bundled.ts","../../../browser/src/plugins/registry.ts","../../../browser/src/proofs/ownDid.ts"],"sourcesContent":["/** Release policy: external identity experiments are retained for future work,\n * but must not advertise capabilities, start network lookups, or expose cached\n * external profiles. This does not gate Ghostly participation authentication. */\nexport const EXTERNAL_IDENTITIES_ENABLED: boolean = false;\n\n/** Mini-apps (WISP 1200): `apps/1` on paired sessions and the engine's `app*` calls. On from release 1.2 (a version\n * before 1.2.0 is never cut with it on: `RELEASE_GUARDS` in tools/scripts/changes.mjs). Off, nothing is offered to\n * contacts and every call is refused; a host that runs no apps pins its engine off (`NodeOptions.apps`). */\nexport const APPS_ENABLED: boolean = true;\n\n/**\n * A build that may be put into test mode: a development build (`import.meta.env.DEV`, which vitest also sets) or the\n * e2e suite's build (`VITE_APPS_TEST`, fixed when the build is made, as the mini-app switch is). A release build is\n * neither: Vite folds this to `false` there, so the storage flags the test fakes answer to are ignored. The fakes\n * themselves are still in the bundle (the registries import them); plugins may still pass fakes to the registry.\n */\nexport const testBuild = (): boolean => { try { return !!import.meta.env?.DEV || import.meta.env?.VITE_APPS_TEST === \"1\"; } catch { return false; } };\n\n/**\n * A suite's switch in the page's storage (`localStorage[\"ghostly-test-…\"]`), read only in a test build (`testBuild`): a\n * release build reads none, so a leftover or pasted key changes nothing there. Null when unset, unreadable or released.\n */\nexport const testSwitch = (key: string): string | null => {\n if (!testBuild()) return null;\n try { return globalThis.localStorage?.getItem(key) ?? null; } catch { return null; }\n};\n","import { boundVerifiedIdentity, IdentityCheckUnavailable, IDENTITY_MAX_EVIDENCE, IDENTITY_MAX_VALIDITY, type IdentityStatement, type VerifiedIdentity } from \"@ghostly/core\";\nimport type { IdentityFetch, IdentityProofProvider, IdentitySigner, VerifyContext } from \"./contract\";\n\nconst DAY = 86_400;\n\n/**\n * The checks every proof goes through, whatever its provider: known provider, validity within the\n * provider's limit, bounded evidence, strict parsing, the provider's own check, and the category rule\n * (a self-custodied proof proves exactly the subject it names; an attested one says who attests it).\n * The engine verifies a contact's proof, and the person's own proof before saving it, only through this.\n */\nexport async function verifyIdentity(providers: readonly IdentityProofProvider[], statement: IdentityStatement, evidence: unknown, ctx: VerifyContext): Promise<VerifiedIdentity> {\n const { binding } = statement;\n const provider = providers.find(p => p.id === binding.provider);\n if (!provider) throw new Error(\"This app cannot verify this kind of identity\");\n if (binding.expiresAt - binding.issuedAt > Math.min(provider.validity.maxDays * DAY, IDENTITY_MAX_VALIDITY)) throw new Error(\"The proof lasts longer than this kind of identity allows\");\n if (JSON.stringify(evidence ?? null).length > IDENTITY_MAX_EVIDENCE) throw new Error(\"Evidence too large\");\n const parsed = provider.parseEvidence(evidence);\n const verified = boundVerifiedIdentity(await provider.verify(statement, parsed, ctx));\n if (provider.category === \"self-custodied\" && verified.subject !== binding.subject) throw new Error(\"The evidence is for another identity\");\n if (provider.category === \"provider-attested\" && !verified.attester) throw new Error(\"The evidence does not say who attests it\");\n return verified;\n}\n\n/** Problems with a provider's descriptor, empty when it is well-formed. The registry and the contract suite use it. */\nexport function descriptorProblems(p: IdentityProofProvider): string[] {\n const problems: string[] = [];\n if (!/^[a-z][a-z0-9-]{0,31}$/.test(p.id)) problems.push(\"id must match ^[a-z][a-z0-9-]{0,31}$\");\n if (!p.label?.trim()) problems.push(\"label is empty\");\n if (!p.description?.trim()) problems.push(\"description is empty\");\n if (!p.privacy?.trim()) problems.push(\"privacy is empty: say what verify contacts\");\n if (p.category !== \"self-custodied\" && p.category !== \"provider-attested\") problems.push(\"category is unknown\");\n if (!p.platforms.length) problems.push(\"no platforms\");\n const { defaultDays, maxDays } = p.validity;\n if (!(Number.isInteger(defaultDays) && Number.isInteger(maxDays) && defaultDays >= 1 && defaultDays <= maxDays && maxDays * DAY <= IDENTITY_MAX_VALIDITY)) problems.push(\"validity must be whole days, 1 ≤ default ≤ max ≤ 400\");\n if (p.recheck && !(Number.isInteger(p.recheck.afterSeconds) && p.recheck.afterSeconds >= 60)) problems.push(\"recheck.afterSeconds must be at least 60\");\n if (!p.signers.length) problems.push(\"no signers\");\n const ids = p.signers.map(s => s.id);\n if (new Set(ids).size !== ids.length) problems.push(\"signer ids are not unique\");\n for (const s of p.signers as readonly IdentitySigner<unknown>[]) {\n if (![\"in-app\", \"external-tool\", \"redirect\", \"publish\"].includes(s.kind)) problems.push(`signer ${s.id} has an unknown kind`);\n if (s.kind === \"in-app\" && typeof s.run !== \"function\") problems.push(`signer ${s.id} has no run()`);\n if (s.kind === \"external-tool\" && (typeof s.instructions !== \"function\" || typeof s.parse !== \"function\")) problems.push(`signer ${s.id} needs instructions() and parse()`);\n if (s.kind === \"redirect\" && typeof s.start !== \"function\") problems.push(`signer ${s.id} has no start()`);\n if (s.kind === \"publish\" && (typeof s.instructions !== \"function\" || typeof s.evidence !== \"function\")) problems.push(`signer ${s.id} needs instructions() and evidence()`);\n }\n return problems;\n}\n\n/** Signers of a provider that run on this platform and are available in this window. */\nexport function availableSigners<E>(p: IdentityProofProvider<E>, platform: IdentityProofProvider[\"platforms\"][number]): IdentitySigner<E>[] {\n return p.signers.filter(s => (s.platforms ?? p.platforms).includes(platform) && (s.available?.() ?? true));\n}\n\n/**\n * The engine's `ctx.fetch`: HTTPS GET only, no credentials or referrer, a time-out, a size cap,\n * redirects refused unless asked for.\n * `online` false refuses everything (the person turned the network off).\n */\nexport function boundedIdentityFetch(options: { online: () => boolean; timeoutMs?: number; fetcher?: typeof fetch } = { online: () => true }): IdentityFetch {\n return async (url, { headers, maxBytes = 64 * 1024, signal, redirect = \"error\" } = {}) => {\n if (!options.online()) throw new IdentityCheckUnavailable(\"Offline: this identity cannot be checked now\");\n const target = new URL(url);\n if (target.protocol !== \"https:\" || target.username || target.password) throw new Error(\"Identity checks use HTTPS only\");\n const timeout = AbortSignal.timeout(options.timeoutMs ?? 10_000);\n const response = await (options.fetcher ?? fetch)(target.href, {\n headers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,\n credentials: \"omit\", referrerPolicy: \"no-referrer\", cache: \"no-store\", redirect,\n });\n if (Number(response.headers.get(\"content-length\")) > maxBytes) throw new Error(\"Identity check response too large\");\n const reader = response.body?.getReader();\n const parts: Uint8Array[] = [];\n let length = 0;\n if (reader) {\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n length += value.length;\n if (length > maxBytes) throw new Error(\"Identity check response too large\");\n parts.push(value);\n }\n } finally { await reader.cancel().catch(() => {}); }\n }\n const bytes = new Uint8Array(length);\n let offset = 0;\n for (const part of parts) { bytes.set(part, offset); offset += part.length; }\n return { status: response.status, contentType: response.headers.get(\"content-type\") ?? \"\", text: new TextDecoder().decode(bytes), bytes };\n };\n}\n","import type { GhostlyAdapterPlugin } from \"./registry\";\n\n/**\n * The adapter plugins compiled into this build. Empty unless the build lists some: `GHOSTLY_PLUGINS`\n * names their modules (comma-separated paths from the repository root, each default-exporting a\n * `GhostlyAdapterPlugin`), and the Vite plugin in `packages/browser/vite-plugin.ts` swaps this module\n * for one that imports them. Release builds never set it; the e2e build carries the SDK example.\n */\nexport const BUNDLED_PLUGINS: readonly GhostlyAdapterPlugin[] = [];\n","import type { LightningProviderDescriptor } from \"../engine/paymentAdapters/providers/lightning\";\nimport type { OnchainProviderDescriptor } from \"../engine/paymentAdapters/providers/onchain\";\nimport { providerDescriptorProblems, type ProviderDescriptor, type ProviderKind } from \"../engine/paymentAdapters/providers/types\";\nimport type { IdentityProofProvider } from \"../proofs/contract\";\nimport { descriptorProblems } from \"../proofs/verify\";\nimport { BUNDLED_PLUGINS } from \"./bundled\";\n\n/**\n * Adapters written outside the app: wallet sources (Lightning, on-chain) and identity-proof providers\n * that register here instead of being added to the built-in lists. A plugin is a plain object naming\n * its adapters; the registries (`providers/registry.ts`, `proofs/registry.ts`) list what is registered\n * after the built-ins and before the test fakes, and the same platform and mode rules apply to all.\n *\n * Two ways in:\n * - at build time: `GHOSTLY_PLUGINS` lists the modules and `bundled.ts` is swapped for them;\n * - at run time: code already running in the engine's realm calls `registerAdapters` before the\n * pickers are shown (or after: the engine re-reads the lists when something registers).\n *\n * Trust: a plugin runs with the app's privileges, in the app's own JavaScript realm. There is no\n * sandbox, no permission prompt and no store; whoever builds a plugin in, or loads one, trusts its\n * author with everything the app can do, keys and sats included. A manifest with permissions and an\n * isolated runtime are a later phase (docs/wisps/ADAPTER-ROADMAP.md, \"Plugins, apps, catalogs\").\n *\n * The state lives on `globalThis` under a well-known symbol, so a plugin bundled with its own copy of\n * the SDK (a second copy of this module) still registers into the same lists the app reads.\n */\n\n/** The generation of the adapter contracts. A plugin says which one it was written against. */\nexport const SDK_API = 1;\nexport const PLUGIN_ID = /^[a-z][a-z0-9-]{0,63}$/;\n\nexport interface GhostlyAdapterPlugin {\n /** Stable, unique among plugins: `^[a-z][a-z0-9-]{0,63}$`. */\n id: string;\n /** The plugin's own version, for people. */\n version?: string;\n /** The contract generation it was written against: `SDK_API`. Another one is refused. */\n sdk: number;\n lightning?: readonly LightningProviderDescriptor[];\n onchain?: readonly OnchainProviderDescriptor[];\n identities?: readonly IdentityProofProvider[];\n}\n\nexport type AdapterKind = ProviderKind | \"identity\";\n\ninterface Store {\n plugins: Map<string, GhostlyAdapterPlugin>;\n /** Ids the built-in registries own, per kind: a plugin cannot take one. */\n reserved: Record<AdapterKind, Set<string>>;\n listeners: Set<() => void>;\n seeded: boolean;\n}\n\nconst KEY = Symbol.for(\"ghostly.adapters/1\");\nfunction store(): Store {\n const g = globalThis as unknown as Record<symbol, Store | undefined>;\n return (g[KEY] ??= { plugins: new Map(), reserved: { lightning: new Set(), onchain: new Set(), identity: new Set() }, listeners: new Set(), seeded: false });\n}\n\nconst ids = (kind: AdapterKind, plugin: GhostlyAdapterPlugin): string[] => {\n // Not trusted to be well formed: pluginProblems reads it before saying what is wrong with it.\n const list: unknown = kind === \"identity\" ? plugin.identities : kind === \"lightning\" ? plugin.lightning : plugin.onchain;\n return Array.isArray(list) ? list.map((a: { id?: string } | null) => a?.id as string) : [];\n};\nconst KINDS: readonly AdapterKind[] = [\"lightning\", \"onchain\", \"identity\"];\n\n/** Problems with a plugin, empty when it can be registered. Does not look at what is already registered. */\nexport function pluginProblems(plugin: GhostlyAdapterPlugin): string[] {\n const problems: string[] = [];\n if (!plugin || typeof plugin !== \"object\") return [\"not a plugin object\"];\n if (!PLUGIN_ID.test(plugin.id ?? \"\")) problems.push(\"plugin id must match ^[a-z][a-z0-9-]{0,63}$\");\n if (plugin.sdk !== SDK_API) problems.push(`plugin was written for SDK API ${String(plugin.sdk)}; this app speaks ${SDK_API}`);\n if (plugin.version !== undefined && (typeof plugin.version !== \"string\" || plugin.version.length > 64)) problems.push(\"version must be a short string\");\n for (const kind of [\"lightning\", \"onchain\"] as const) {\n const list = plugin[kind];\n if (list === undefined) continue;\n if (!Array.isArray(list)) { problems.push(`${kind} must be a list of descriptors`); continue; }\n for (const d of list as ProviderDescriptor<unknown>[]) {\n if (!d || typeof d !== \"object\") { problems.push(`${kind} ${String(d)}: not a descriptor`); continue; }\n const own = providerDescriptorProblems(d);\n if (d?.kind && d.kind !== kind) own.push(`is listed under ${kind} but says kind ${String(d.kind)}`);\n problems.push(...own.map((p) => `${kind} ${String(d?.id)}: ${p}`));\n }\n }\n if (plugin.identities !== undefined) {\n if (!Array.isArray(plugin.identities)) problems.push(\"identities must be a list of providers\");\n else for (const p of plugin.identities) {\n if (!p || typeof p !== \"object\") problems.push(`identity ${String(p)}: not a provider`);\n else problems.push(...descriptorProblems(p).map((m) => `identity ${String(p.id)}: ${m}`));\n }\n }\n for (const kind of KINDS) {\n const list = ids(kind, plugin);\n if (new Set(list).size !== list.length) problems.push(`${kind} ids are not unique within the plugin`);\n }\n if (!KINDS.some((kind) => ids(kind, plugin).length)) problems.push(\"the plugin brings no adapter\");\n return problems;\n}\n\n/** The built-in registries say which ids are theirs. A plugin using one is refused. */\nexport function reserveAdapterIds(kind: AdapterKind, list: readonly string[]): void {\n const s = store();\n for (const id of list) s.reserved[kind].add(id);\n}\n\n/**\n * Registers a plugin's adapters. Throws, registering nothing, when the plugin is malformed, its id or\n * one of its adapters' ids is taken (by a built-in or by another plugin), or its contract generation\n * is another one. Returns the function that unregisters it.\n */\nexport function registerAdapters(plugin: GhostlyAdapterPlugin): () => void {\n const problems = pluginProblems(plugin);\n const s = store();\n if (!problems.length) {\n if (s.plugins.has(plugin.id)) problems.push(`a plugin with id ${plugin.id} is already registered`);\n for (const kind of KINDS) for (const id of ids(kind, plugin)) {\n if (s.reserved[kind].has(id)) problems.push(`${kind} ${id} is a built-in of this app`);\n for (const other of s.plugins.values()) if (ids(kind, other).includes(id)) problems.push(`${kind} ${id} is already registered by plugin ${other.id}`);\n }\n }\n if (problems.length) throw new Error(`Cannot register plugin ${String(plugin?.id)}: ${problems.join(\"; \")}`);\n s.plugins.set(plugin.id, plugin);\n notify(s);\n return () => { if (s.plugins.get(plugin.id) === plugin) { s.plugins.delete(plugin.id); notify(s); } };\n}\n\nfunction notify(s: Store) { for (const listener of s.listeners) { try { listener(); } catch { /* a listener's problem */ } } }\n\n/** Called when a plugin registers or unregisters: the engine re-reads the lists. */\nexport function onAdaptersChanged(listener: () => void): () => void {\n const s = store();\n s.listeners.add(listener);\n return () => { s.listeners.delete(listener); };\n}\n\n/** Every registered plugin, in registration order (bundled ones first). */\nexport function registeredPlugins(): readonly GhostlyAdapterPlugin[] { seed(); return [...store().plugins.values()]; }\nexport function registeredLightningProviders(): readonly LightningProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.lightning ?? []); }\nexport function registeredOnchainProviders(): readonly OnchainProviderDescriptor[] { return registeredPlugins().flatMap((p) => p.onchain ?? []); }\nexport function registeredIdentityProviders(): readonly IdentityProofProvider[] { return registeredPlugins().flatMap((p) => p.identities ?? []); }\n\n/**\n * The plugins compiled into this build register once, when they are first asked for. A broken one is\n * reported and skipped rather than taking the app down with it; the e2e that expects it fails instead.\n */\nfunction seed() {\n const s = store();\n if (s.seeded) return;\n s.seeded = true;\n for (const plugin of BUNDLED_PLUGINS) {\n try { registerAdapters(plugin); }\n catch (error) { console.error(`[ghostly] a bundled adapter plugin was not loaded: ${error instanceof Error ? error.message : String(error)}`); }\n }\n}\n\n/** Tests only: forget every registration, including the bundled ones. */\nexport function resetAdapterRegistry(): void {\n const s = store();\n s.plugins.clear(); s.seeded = false;\n for (const kind of KINDS) s.reserved[kind].clear();\n notify(s);\n}\n","/**\n * The profile's own Ghostly did:dht, which the DID provider refuses as an external identity. The UI and the engine each\n * set where to read it. Here, not in the provider, so setting it does not load the providers.\n */\nlet source: () => string | undefined = () => undefined;\nexport function setOwnDidSource(read: () => string | undefined): void { source = read; }\nexport const ownDid = (): string | undefined => source();\n"],"mappings":";;;;;;;;;AAgBA,IAAa,kBAA2B;CAAE,IAAI;EAAE,OAA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O,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,WAAW,CAAC,CAAC;AAAG;AACjJ,SAAgB,8BAAgE;CAAE,OAAO,kBAAkB,CAAC,CAAC,SAAS,MAAM,EAAE,cAAc,CAAC,CAAC;AAAG;;;;;AAMjJ,SAAS,OAAO;CACd,MAAM,IAAI,MAAM;CAChB,IAAI,EAAE,QAAQ;CACd,EAAE,SAAS;CACX,KAAK,MAAM,UAAU,iBACnB,IAAI;EAAE,iBAAiB,MAAM;CAAG,SACzB,OAAO;EAAE,QAAQ,MAAM,sDAAsD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CAAG;AAEnJ;;;;;;;ACrJA,IAAI,eAAyC,KAAA;AAC7C,SAAgB,gBAAgB,MAAsC;CAAE,SAAS;AAAM;AACvF,IAAa,eAAmC,OAAO"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { t as CliError } from "./errors-R4S2SAEM.js";
|
|
2
|
+
import { t as childEnv } from "./childEnv-BVOQK9EA.js";
|
|
2
3
|
import { execFileSync } from "node:child_process";
|
|
3
4
|
import { chmodSync, closeSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
4
5
|
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
@@ -80,9 +81,14 @@ function ownProfile(dir) {
|
|
|
80
81
|
if (!info.isDirectory() || !mine(info)) throw new CliError("refused", `${folder} is not a folder of this user's: ${what}`);
|
|
81
82
|
if ((info.mode & 63) !== 0) chmodSync(folder, 448);
|
|
82
83
|
for (const name of readdirSync(folder)) {
|
|
83
|
-
const path = join(folder, name), entry = lstatSync(path);
|
|
84
|
+
const path = join(folder, name), entry = lstatSync(path, { throwIfNoEntry: false });
|
|
85
|
+
if (!entry) continue;
|
|
84
86
|
if (entry.isSymbolicLink() || !mine(entry)) throw new CliError("refused", `${path} is a link or another user's: ${what}`);
|
|
85
|
-
if (entry.isFile() && (entry.mode & 63) !== 0)
|
|
87
|
+
if (entry.isFile() && (entry.mode & 63) !== 0) try {
|
|
88
|
+
chmodSync(path, 384);
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (error.code !== "ENOENT") throw error;
|
|
91
|
+
}
|
|
86
92
|
}
|
|
87
93
|
}
|
|
88
94
|
}
|
|
@@ -322,7 +328,7 @@ function processStart(pid) {
|
|
|
322
328
|
],
|
|
323
329
|
timeout: 2e3,
|
|
324
330
|
env: {
|
|
325
|
-
...
|
|
331
|
+
...childEnv(),
|
|
326
332
|
LC_ALL: "C"
|
|
327
333
|
}
|
|
328
334
|
}).trim() || null;
|
|
@@ -424,4 +430,4 @@ function holder(file, lock) {
|
|
|
424
430
|
//#endregion
|
|
425
431
|
export { runtimePath as S, userPath as _, checkShownName as a, ownSocket as b, ghostlyHome as c, lockPath as d, profileExists as f, startingPath as g, startingDaemon as h, checkProfileName as i, listProfiles as l, selectProfile as m, RESTORED_MARK as n, createProfile as o, profilePaths as p, acquireLock as r, currentProfile as s, DEFAULT_PROFILE as t, lockOwner as u, ownFolder as v, privateFolder as x, ownProfile as y };
|
|
426
432
|
|
|
427
|
-
//# sourceMappingURL=profiles-
|
|
433
|
+
//# sourceMappingURL=profiles-DgIfvBeN.js.map
|