aboutsummaryrefslogtreecommitdiffstats
path: root/src/nostr-login.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/nostr-login.js')
-rw-r--r--src/nostr-login.js75
1 files changed, 65 insertions, 10 deletions
diff --git a/src/nostr-login.js b/src/nostr-login.js
index fe60261..e5490ec 100644
--- a/src/nostr-login.js
+++ b/src/nostr-login.js
@@ -36,7 +36,7 @@ import { hex, bech32 } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { entropyToMnemonic } from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
-import { getPublicKey, finalizeEvent, nip44 } from './nostr.js';
+import { getPublicKey, finalizeEvent, nip44, liveRelayList } from './nostr.js';
import { SimplePool } from 'nostr-tools/pool';
import { generateSecretKey } from 'nostr-tools/pure';
import { decode as nip19decode } from 'nostr-tools/nip19';
@@ -208,7 +208,24 @@ export function nostrConnectPending(timeoutMs = 180_000) {
} catch {}
return null;
}
-export async function nostrConnect({ relays = ['wss://relay.coinos.io', 'wss://nos.lol'], timeoutMs = 180_000, resume = null } = {}) {
+// The relays a nostrconnect:// link names: the signer app publishes its
+// approval there and we wait there, so a dead one is a login that spins
+// until it times out. A PAFF account's Amber sign-in sat on "waiting for
+// signer" while nos.lol (the link's second relay) refused connections, and
+// relay.nsec.app was down the same night (Adam, 2026-11-19). So the link
+// leads with relay.coinos.io and relay.primal.net (up, and both keep NIP-46
+// traffic), leaves out any relay this device has recently found dead, and
+// names three: one relay's outage no longer strands the handshake.
+const CONNECT_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net', 'wss://nos.lol', 'wss://offchain.pub'];
+export function connectRelays(candidates = CONNECT_RELAYS, n = 3) {
+ let live = candidates;
+ try { live = liveRelayList(candidates); } catch {}
+ const picked = live.slice(0, n);
+ // our own relay always: its ops are ours to fix, and the poller reads it
+ if (!picked.includes(candidates[0])) picked.unshift(candidates[0]);
+ return picked.slice(0, n);
+}
+export async function nostrConnect({ relays = connectRelays(), timeoutMs = 180_000, resume = null } = {}) {
const { BunkerSigner, createNostrConnectURI } = await loadNip46();
const local = resume ? hex.decode(resume.local) : generateSecretKey();
const secret = resume ? resume.secret : hex.encode(crypto.getRandomValues(new Uint8Array(16)));
@@ -324,7 +341,7 @@ let amberWatch = null;
const amberListeners = new Set();
export const onAmberChange = (fn) => { amberListeners.add(fn); return () => amberListeners.delete(fn); };
const amberChanged = () => { for (const fn of amberListeners) { try { fn(); } catch {} } };
-export const amberPending = () => (amberReq ? { type: amberReq.type, since: amberReq.ts } : null);
+export const amberPending = () => (amberReq ? { type: amberReq.type, since: amberReq.ts, needsTap: !!amberReq.needsTap } : null);
const HEX64 = /^[0-9a-f]{64}$/i;
// What an answer of this type looks like — anything else on the clipboard
// is somebody's grocery list, not a signature.
@@ -384,7 +401,10 @@ function amberWatchClipboard() {
if (amberReq && amberDeliver(txt)) return;
} catch {} // no permission: the paste box is the way in
};
- const onVis = () => { if (document.visibilityState === 'visible') setTimeout(read, 250); };
+ const onVis = () => {
+ if (document.visibilityState === 'hidden') { if (amberReq) amberReq.hidden = true; return; } // the signer came up
+ setTimeout(read, 250);
+ };
document.addEventListener('visibilitychange', onVis);
window.addEventListener('focus', onVis);
const iv = setInterval(read, 800);
@@ -395,6 +415,35 @@ function amberLaunch(url) {
if (typeof window !== 'undefined' && typeof window.__coinosAmberLaunch === 'function') { window.__coinosAmberLaunch(url); return; } // tests
window.location.href = url;
}
+// Chrome lets a page open another app only on the heels of a tap: without
+// one the `nostrsigner:` navigation is dropped with a console warning the
+// page never sees ("Navigation is blocked"). The first request rides the
+// Sign-in tap; the ones the login fires once an answer is back (decrypt the
+// backup, sign the relay list…) have no tap behind them, so they wait for
+// one — the card shows an Open button — instead of spinning forever. A
+// launch that leaves the page in front is taken as blocked too.
+export function amberOpen() {
+ const r = amberReq;
+ if (!r) return false;
+ r.needsTap = false;
+ r.hidden = false;
+ clearTimeout(r.timer);
+ r.timer = setTimeout(() => amberCancel('signer did not answer'), r.timeoutMs);
+ amberChanged();
+ amberLaunch(r.url);
+ if (typeof window !== 'undefined' && typeof window.__coinosAmberLaunch === 'function') return true; // tests: no app to come up
+ setTimeout(() => {
+ if (amberReq !== r || r.hidden || typeof document === 'undefined' || document.visibilityState !== 'visible') return;
+ r.needsTap = true;
+ amberChanged();
+ }, 2500);
+ return true;
+}
+const amberTapAvailable = () => {
+ if (typeof window !== 'undefined' && typeof window.__coinosAmberLaunch === 'function') return true; // tests
+ const ua = typeof navigator !== 'undefined' ? navigator.userActivation : null;
+ return ua ? ua.isActive : true;
+};
// One trip at a time: the app fires several signatures at once right after a
// sign-in (the backup, the relay list, the follows), and Amber can only be
// asked for one; the rest wait their turn in this chain.
@@ -404,11 +453,11 @@ function amberRequest(type, payload, params = {}, { timeoutMs = 180_000 } = {})
if (params.pubkey) q.set('pubkey', params.pubkey);
const url = 'nostrsigner:' + encodeURIComponent(payload || '') + '?' + q.toString();
const run = () => new Promise((resolve, reject) => {
- amberReq = { type, payload: payload || '', ts: Date.now(), resolve, reject,
+ amberReq = { type, payload: payload || '', url, ts: Date.now(), resolve, reject, timeoutMs,
timer: setTimeout(() => amberCancel('signer did not answer'), timeoutMs) };
amberWatch = amberWatchClipboard();
- amberChanged();
- amberLaunch(url);
+ if (amberTapAvailable()) amberOpen();
+ else { amberReq.needsTap = true; amberChanged(); }
});
const p = amberQueue.then(run, run);
amberQueue = p.catch(() => {});
@@ -482,8 +531,14 @@ export async function fetchWalletBackup(signer, relays = BACKUP_RELAYS) {
// `spending` rides along as a hint: a restored wallet paints its Spending
// side from the first frame instead of reflowing when the name lookup proves
// it seconds later.
-export async function publishWalletBackup(signer, { mnemonic, passphrase, spending }, relays = BACKUP_RELAYS) {
- const content = await signer.encryptSelf(JSON.stringify({ mnemonic, passphrase: passphrase || '', ...(spending ? { spending: true } : {}) }));
+// `recovery` marks a copy kept by a WAY BACK IN (a passkey, Google or nostr
+// key added from Settings): signing in with that key opens the account as
+// itself — its own identity, name and profile — rather than adopting the
+// key as the account's nostr identity the way a login does. `spendingOnly`
+// carries a sign-up's shape (no Savings side yet) to the next device.
+export async function publishWalletBackup(signer, { mnemonic, passphrase, spending, recovery, spendingOnly }, relays = BACKUP_RELAYS) {
+ const content = await signer.encryptSelf(JSON.stringify({ mnemonic, passphrase: passphrase || '',
+ ...(spending ? { spending: true } : {}), ...(recovery ? { recovery: true } : {}), ...(spendingOnly ? { spendingOnly: true } : {}) }));
const evt = await signer.signEvent({
kind: BACKUP_KIND, created_at: Math.floor(Date.now() / 1000),
tags: [['d', SEED_DTAG]], content,
@@ -505,7 +560,7 @@ export async function publishWalletBackup(signer, { mnemonic, passphrase, spendi
// deriving (key in hand) or generating (signer only).
export async function walletForSigner(signer) {
const found = await fetchWalletBackup(signer);
- if (found) return { mnemonic: found.mnemonic, passphrase: found.passphrase, spending: !!found.spending, mode: 'restored' };
+ if (found) return { mnemonic: found.mnemonic, passphrase: found.passphrase, spending: !!found.spending, recovery: !!found.recovery, spendingOnly: !!found.spendingOnly, mode: 'restored' };
if (signer.secret) {
// Publishing the derived seed costs nothing: the derivation is public,
// so anyone holding this key could compute it anyway. It buys the thing