Open signer apps on desktop, log out remote signers via NIP-46 #135

Merged
raucao merged 2 commits from feature/remote_signers_everywhere into master 2026-11-28 15:41:54 +00:00
6 changed files with 365 additions and 34 deletions

No files matched your search

+113 -11
View File
@@ -2,13 +2,24 @@ import Component from '@glimmer/component';
import { action } from '@ember/object';
import { service } from '@ember/service';
import { on } from '@ember/modifier';
import { tracked } from '@glimmer/tracking';
import { eq } from 'ember-truth-helpers';
import qrCode from '../modifiers/qr-code';
// How long to wait for the signer app to take over the page (via the OS
// `nostrconnect:` protocol handler) before assuming it did not open.
const SIGNER_LAUNCH_TIMEOUT = 2000;
export default class NostrConnectComponent extends Component {
@service nostrAuth;
@service toast;
@tracked showSignerHint = false;
@tracked showQrCode = false;
_launchAttempt = 0;
_launchTeardown = null;
get hasExtension() {
return typeof window !== 'undefined' && typeof window.nostr !== 'undefined';
}
@@ -75,6 +86,80 @@ export default class NostrConnectComponent extends Component {
}
}
@action
toggleQrCode() {
this.showQrCode = !this.showQrCode;
}
// The anchor's default navigation is what hands the `nostrconnect:` URI to
// the OS, so we must not preventDefault. We only watch for signs that a
// signer app actually took over — the page being hidden or blurred, or a
// navigation error for the `nostrconnect:` scheme (no protocol handler) —
// and otherwise reveal a hint pointing at the QR code / copy link fallback.
@action
openSigner() {
this.showSignerHint = false;
this._teardownLaunch();
const attempt = (this._launchAttempt += 1);
let launched = false;
const teardown = [];
const revealHint = () => {
if (attempt === this._launchAttempt) this.showSignerHint = true;
};
const markLaunched = () => {
launched = true;
this._teardownLaunch();
};
const onVisibility = () => {
if (document.visibilityState === 'hidden') markLaunched();
};
const onBlur = () => markLaunched();
const onNavigateError = (event) => {
if (!event.destination?.url?.startsWith('nostrconnect:')) return;
this._teardownLaunch();
revealHint();
};
document.addEventListener('visibilitychange', onVisibility);
teardown.push(() =>
document.removeEventListener('visibilitychange', onVisibility)
);
window.addEventListener('blur', onBlur, { once: true });
teardown.push(() => window.removeEventListener('blur', onBlur));
if ('navigation' in window) {
window.navigation.addEventListener('navigateerror', onNavigateError);
teardown.push(() =>
window.navigation.removeEventListener('navigateerror', onNavigateError)
);
}
const timer = setTimeout(() => {
if (launched || attempt !== this._launchAttempt) return;
this._teardownLaunch();
revealHint();
}, SIGNER_LAUNCH_TIMEOUT);
teardown.push(() => clearTimeout(timer));
this._launchTeardown = teardown;
}
_teardownLaunch() {
if (!this._launchTeardown) return;
for (const fn of this._launchTeardown) fn();
this._launchTeardown = null;
}
willDestroy() {
this._teardownLaunch();
super.willDestroy(...arguments);
}
<template>
<div class="nostr-connect-modal">
<h2>Connect with Nostr</h2>
@@ -104,29 +189,46 @@ export default class NostrConnectComponent extends Component {
type="button"
{{on "click" this.connectApp}}
>
Mobile Signer App (Amber, etc.)
Signer app (Amber, Regent, etc.)
</button>
</div>
{{#if (eq this.nostrAuth.connectStatus "waiting")}}
<div class="nostr-connect-status">
{{#if this.nostrAuth.isMobile}}
<p>Waiting for you to approve the connection in your mobile signer
app...</p>
<div class="mobile-connect-actions">
<a href={{this.nostrAuth.connectUri}} class="btn btn-primary">
Open Signer App
</a>
<p>Approve the connection in your signer app on this device, or scan
the QR code with a signer app on another device.</p>
<div class="signer-connect-actions">
<a
href={{this.nostrAuth.connectUri}}
class="btn btn-primary"
{{on "click" this.openSigner}}
>
Open signer app
</a>
<div class="signer-connect-secondary">
<button
class="btn btn-outline"
type="button"
{{on "click" this.copyConnectUri}}
>
Copy Connection Link
Copy connection link
</button>
<button
class="btn btn-outline"
type="button"
{{on "click" this.toggleQrCode}}
>
{{if this.showQrCode "Hide QR code" "Show QR code"}}
</button>
</div>
{{else}}
<p>Scan this QR code with a Nostr signer app (like Amber):</p>
</div>
{{#if this.showSignerHint}}
<p class="signer-connect-hint">
Didn't open your signer app? Scan the QR code or copy the
connection link.
</p>
{{/if}}
{{#if this.showQrCode}}
<div class="qr-code-container">
<canvas {{qrCode this.nostrAuth.connectUri}}></canvas>
</div>
+22 -18
View File
@@ -19,7 +19,8 @@ const STORAGE_KEY_CONNECT_RELAY = 'marco:nostr_connect_relay';
const DEFAULT_CONNECT_RELAY = 'wss://nostr.kosmos.org';
import { isMobile } from '../utils/device';
/** How long to wait for a remote signer to acknowledge a NIP-46 logout. */
export const REMOTE_SIGNER_LOGOUT_TIMEOUT = 10000;
export default class NostrAuthService extends Service {
@service nostrRelay;
@@ -79,10 +80,6 @@ export default class NostrAuthService extends Service {
}
}
get isMobile() {
return isMobile();
}
/**
* NIP-46 client metadata: name/url/image are display hints for the signer
* app, and the requested permissions let it pre-approve what Marco signs.
@@ -193,15 +190,9 @@ export default class NostrAuthService extends Service {
},
});
// Set the uri for display (e.g., to redirect via intent)
// Set the uri so the UI can offer to open a signer app or show a QR code
this.connectUri = this._signerInstance.getNostrConnectURI(metadata);
// Trigger the deep link intent immediately for the user if on mobile
if (this.isMobile) {
console.debug('Mobile detected, triggering deep link intent.');
window.location.href = this.connectUri;
}
// Start listening to the relay
console.debug('Opening signer connection to relay...');
await this._signerInstance.open();
@@ -291,17 +282,15 @@ export default class NostrAuthService extends Service {
}
async disconnect() {
const instance = this._signerInstance;
const wasConnect = this.signerType === 'connect';
// Clear local state immediately, regardless of what the remote signer does.
this.pubkey = null;
this.nostrData?.loadProfile(null);
this.signerType = null;
this.connectStatus = null;
this.connectUri = null;
if (
this._signerInstance &&
typeof this._signerInstance.close === 'function'
) {
await this._signerInstance.close();
}
this._signerInstance = null;
localStorage.removeItem(STORAGE_KEY);
@@ -309,5 +298,20 @@ export default class NostrAuthService extends Service {
localStorage.removeItem(STORAGE_KEY_CONNECT_LOCAL_KEY);
localStorage.removeItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY);
localStorage.removeItem(STORAGE_KEY_CONNECT_RELAY);
if (!instance) return;
if (wasConnect && typeof instance.logout === 'function') {
// NIP-46: tell the remote signer to drop the session. logout() also
// closes the local connection and is a no-op when not connected. It is
// a courtesy hint, so a failure must not stop the local disconnect.
try {
await instance.logout({ timeout: REMOTE_SIGNER_LOGOUT_TIMEOUT });
} catch (error) {
console.warn('Failed to send NIP-46 logout to remote signer', error);
}
} else if (typeof instance.close === 'function') {
await instance.close();
}
}
}
+16 -1
View File
@@ -2027,13 +2027,28 @@ button.create-place {
margin-top: 1.5rem;
}
.mobile-connect-actions {
.signer-connect-actions {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-top: 1rem;
}
.signer-connect-secondary {
display: flex;
gap: 0.5rem;
}
.signer-connect-secondary > * {
flex: 1;
}
.signer-connect-hint {
margin-top: 1rem;
color: #b45309;
font-size: 0.9rem;
}
.nostr-connect-status {
margin-top: 1.5rem;
text-align: center;
+2 -4
View File
@@ -17,10 +17,6 @@ export class MockNostrAuthService extends Service {
);
}
get isMobile() {
return false;
}
get signer() {
return null;
}
@@ -62,6 +58,8 @@ export class MockNostrDataService extends Service {
return this.profiles[pubkey];
}
loadProfile() {}
getEventRelays() {
return [];
}
@@ -0,0 +1,129 @@
import { module, test } from 'qunit';
import { setupRenderingTest } from 'marco/tests/helpers';
import {
render,
click,
waitUntil,
settled,
findAll,
} from '@ember/test-helpers';
import Service from '@ember/service';
import NostrConnect from 'marco/components/nostr-connect';
import { setupNostrMocks } from 'marco/tests/helpers/mock-nostr';
class MockToastService extends Service {
show() {}
}
const CONNECT_URI = 'nostrconnect://abc123@wss://relay.test';
module('Integration | Component | nostr-connect', function (hooks) {
setupRenderingTest(hooks);
setupNostrMocks(hooks);
hooks.beforeEach(function () {
this.owner.register('service:toast', MockToastService);
this.nostrAuth = this.owner.lookup('service:nostrAuth');
this.nostrAuth.connectStatus = 'waiting';
this.nostrAuth.connectUri = CONNECT_URI;
// Clicking the `nostrconnect://` anchor would attempt a real navigation in
// the test browser. Prevent only the default action; the component's click
// listener still runs.
this.preventNav = (event) => {
if (event.target.closest?.('a[href^="nostrconnect:"]')) {
event.preventDefault();
}
};
document.addEventListener('click', this.preventNav, true);
});
hooks.afterEach(function () {
document.removeEventListener('click', this.preventNav, true);
});
test('offers a signer app option without calling it mobile-only', async function (assert) {
await render(<template><NostrConnect /></template>);
assert
.dom('.nostr-connect-options')
.includesText('Signer app (Amber, Regent, etc.)');
assert
.dom('.nostr-connect-modal')
.doesNotIncludeText('Mobile Signer', 'not described as mobile-only');
});
test('offers opening the signer app on any device while waiting', async function (assert) {
await render(<template><NostrConnect /></template>);
assert.dom('a.btn').hasText('Open signer app');
assert.dom('a.btn').hasAttribute('href', CONNECT_URI);
assert
.dom('.signer-connect-secondary')
.includesText('Copy connection link');
assert.dom('.signer-connect-secondary').includesText('Show QR code');
assert.dom('.qr-code-container').doesNotExist('QR code hidden by default');
});
test('toggles the QR code on and off', async function (assert) {
await render(<template><NostrConnect /></template>);
const [, toggle] = findAll('.signer-connect-secondary .btn');
await click(toggle);
assert.dom('.qr-code-container canvas').exists('QR code shown on demand');
assert.dom(toggle).hasText('Hide QR code');
await click(toggle);
assert.dom('.qr-code-container').doesNotExist('QR code hidden again');
assert.dom(toggle).hasText('Show QR code');
});
test('reveals a fallback hint when the signer app does not open', async function (assert) {
await render(<template><NostrConnect /></template>);
assert.dom('.signer-connect-hint').doesNotExist('hint hidden initially');
await click('a.btn');
await waitUntil(() => document.querySelector('.signer-connect-hint'), {
timeout: 4000,
message: 'fallback hint appears after the launch timeout',
});
assert.dom('.signer-connect-hint').includesText('Scan the QR code');
});
test('stays quiet when the page is hidden (signer app took over)', async function (assert) {
const originalVisibility = Object.getOwnPropertyDescriptor(
document,
'visibilityState'
);
try {
await render(<template><NostrConnect /></template>);
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: () => 'hidden',
});
await click('a.btn');
document.dispatchEvent(new Event('visibilitychange'));
await new Promise((resolve) => setTimeout(resolve, 2300));
await settled();
assert
.dom('.signer-connect-hint')
.doesNotExist('no hint when the signer app opened');
} finally {
if (originalVisibility) {
Object.defineProperty(document, 'visibilityState', originalVisibility);
} else {
delete document.visibilityState;
}
}
});
});
+83
View File
@@ -0,0 +1,83 @@
import { module, test } from 'qunit';
import { setupTest } from 'marco/tests/helpers';
import sinon from 'sinon';
import NostrAuthService, {
REMOTE_SIGNER_LOGOUT_TIMEOUT,
} from 'marco/services/nostr-auth';
const STORAGE_KEY_CONNECT_REMOTE_PUBKEY = 'marco:nostr_connect_remote_pubkey';
module('Unit | Service | nostr-auth', function (hooks) {
setupTest(hooks);
hooks.beforeEach(function () {
localStorage.clear();
this.owner.register('service:nostrAuth', NostrAuthService);
this.service = this.owner.lookup('service:nostrAuth');
});
hooks.afterEach(function () {
sinon.restore();
localStorage.clear();
});
test('disconnect sends a NIP-46 logout for a remote signer', async function (assert) {
const logout = sinon.spy(async () => {});
const close = sinon.spy(async () => {});
this.service.signerType = 'connect';
this.service.pubkey = 'a'.repeat(64);
localStorage.setItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY, 'b'.repeat(64));
this.service._signerInstance = { logout, close };
await this.service.disconnect();
assert.true(logout.calledOnce, 'sends the logout request');
assert.deepEqual(
logout.firstCall.args[0],
{ timeout: REMOTE_SIGNER_LOGOUT_TIMEOUT },
'waits for the acknowledgement with the configured timeout'
);
assert.false(close.called, 'does not close separately (logout does it)');
assert.strictEqual(this.service.pubkey, null, 'clears the pubkey');
assert.strictEqual(this.service.signerType, null, 'clears the signer type');
assert.strictEqual(
localStorage.getItem(STORAGE_KEY_CONNECT_REMOTE_PUBKEY),
null,
'clears the persisted connection state'
);
});
test('disconnect closes the connection for an extension signer', async function (assert) {
const close = sinon.spy(async () => {});
this.service.signerType = 'extension';
this.service.pubkey = 'a'.repeat(64);
this.service._signerInstance = { close };
await this.service.disconnect();
assert.true(close.calledOnce, 'closes the extension connection');
assert.strictEqual(this.service.pubkey, null, 'clears the pubkey');
});
test('disconnect still resolves when the remote signer logout fails', async function (assert) {
const logout = sinon.spy(async () => {
throw new Error('signer offline');
});
this.service.signerType = 'connect';
this.service.pubkey = 'a'.repeat(64);
this.service._signerInstance = { logout };
await this.service.disconnect();
assert.true(logout.calledOnce, 'attempts the logout');
assert.strictEqual(
this.service.pubkey,
null,
'local state is cleared even if the signer is unreachable'
);
});
});