Load signer on launch, disconnect or switch pubkey if necessary

This commit is contained in:
2026-04-19 11:08:55 +04:00
parent f875fc1877
commit 4bd5c4bf2a

View File

@@ -6,13 +6,33 @@ const STORAGE_KEY = 'marco:nostr_pubkey';
export default class NostrAuthService extends Service { export default class NostrAuthService extends Service {
@tracked pubkey = null; @tracked pubkey = null;
signer = null;
constructor() { constructor() {
super(...arguments); super(...arguments);
const saved = localStorage.getItem(STORAGE_KEY); const saved = localStorage.getItem(STORAGE_KEY);
if (saved) { if (saved) {
this.pubkey = saved; this.pubkey = saved;
this._verifyPubkey();
}
}
async _verifyPubkey() {
if (typeof window.nostr === 'undefined') {
this.logout();
return;
}
try {
const signer = new ExtensionSigner();
const extensionPubkey = await signer.getPublicKey();
if (extensionPubkey !== this.pubkey) {
this.pubkey = extensionPubkey;
localStorage.setItem(STORAGE_KEY, this.pubkey);
}
} catch (e) {
console.warn('Failed to verify nostr pubkey, logging out', e);
this.logout();
} }
} }
@@ -20,15 +40,18 @@ export default class NostrAuthService extends Service {
return !!this.pubkey; return !!this.pubkey;
} }
get signer() {
if (typeof window.nostr !== 'undefined') {
return new ExtensionSigner();
}
return null;
}
async login() { async login() {
if (typeof window.nostr === 'undefined') { if (typeof window.nostr === 'undefined') {
throw new Error('No NIP-07 Nostr extension found (e.g., Alby, nos2x).'); throw new Error('No NIP-07 Nostr extension found (e.g., Alby, nos2x).');
} }
if (!this.signer) {
this.signer = new ExtensionSigner();
}
try { try {
this.pubkey = await this.signer.getPublicKey(); this.pubkey = await this.signer.getPublicKey();
localStorage.setItem(STORAGE_KEY, this.pubkey); localStorage.setItem(STORAGE_KEY, this.pubkey);
@@ -41,20 +64,15 @@ export default class NostrAuthService extends Service {
async signEvent(event) { async signEvent(event) {
if (!this.signer) { if (!this.signer) {
if (this.pubkey && typeof window.nostr !== 'undefined') { throw new Error(
this.signer = new ExtensionSigner(); 'Not connected or extension missing. Please connect Nostr again.'
} else { );
throw new Error(
'Not connected or extension missing. Please connect Nostr again.'
);
}
} }
return await this.signer.signEvent(event); return await this.signer.signEvent(event);
} }
logout() { logout() {
this.pubkey = null; this.pubkey = null;
this.signer = null;
localStorage.removeItem(STORAGE_KEY); localStorage.removeItem(STORAGE_KEY);
} }
} }