|
| 1 | +/** |
| 2 | + * Heartwood NIP-46 Bunker — remote signing sidecar. |
| 3 | + * |
| 4 | + * Standalone daemon that holds the user's nsec and responds to signing |
| 5 | + * requests from NIP-46 clients (Amber, NostrHub, etc.) over Nostr relays. |
| 6 | + * Clients never see the nsec — only signatures and public keys leave the Pi. |
| 7 | + * |
| 8 | + * Reads secrets from /var/lib/heartwood/ (shared with heartwood-device). |
| 9 | + */ |
| 10 | + |
| 11 | +import { readFileSync, writeFileSync, existsSync } from 'node:fs' |
| 12 | +import { getConversationKey, encrypt, decrypt } from 'nostr-tools/nip44' |
| 13 | +import { finalizeEvent, getPublicKey, generateSecretKey } from 'nostr-tools/pure' |
| 14 | +import { decode as nip19decode } from 'nostr-tools/nip19' |
| 15 | +import { SimplePool } from 'nostr-tools/pool' |
| 16 | +import WebSocket from 'ws' |
| 17 | + |
| 18 | +globalThis.WebSocket = WebSocket |
| 19 | + |
| 20 | +const DATA_DIR = '/var/lib/heartwood' |
| 21 | +const DEFAULT_RELAYS = [ |
| 22 | + 'wss://relay.damus.io', |
| 23 | + 'wss://relay.nostr.band', |
| 24 | + 'wss://nos.lol', |
| 25 | + 'wss://relay.trotters.cc', |
| 26 | +] |
| 27 | + |
| 28 | +// --- 1. Read nsec from master.secret --- |
| 29 | + |
| 30 | +const secretPath = `${DATA_DIR}/master.secret` |
| 31 | +if (!existsSync(secretPath)) { |
| 32 | + console.error('FATAL: master.secret not found — is heartwood-device configured?') |
| 33 | + process.exit(1) |
| 34 | +} |
| 35 | + |
| 36 | +const secretPayload = readFileSync(secretPath, 'utf-8').trim() |
| 37 | +if (!secretPayload.startsWith('bunker:')) { |
| 38 | + console.error('FATAL: master.secret is not in bunker mode (expected "bunker:<nsec>")') |
| 39 | + process.exit(1) |
| 40 | +} |
| 41 | + |
| 42 | +const nsec = secretPayload.slice('bunker:'.length) |
| 43 | +const { type, data: userSk } = nip19decode(nsec) |
| 44 | +if (type !== 'nsec') { |
| 45 | + console.error('FATAL: invalid nsec in master.secret') |
| 46 | + process.exit(1) |
| 47 | +} |
| 48 | + |
| 49 | +const userPk = getPublicKey(userSk) |
| 50 | + |
| 51 | +// --- 2. Read relay list from config.json --- |
| 52 | + |
| 53 | +let relays = DEFAULT_RELAYS |
| 54 | +const configPath = `${DATA_DIR}/config.json` |
| 55 | +if (existsSync(configPath)) { |
| 56 | + try { |
| 57 | + const config = JSON.parse(readFileSync(configPath, 'utf-8')) |
| 58 | + if (Array.isArray(config.relays) && config.relays.length > 0) { |
| 59 | + relays = config.relays |
| 60 | + } |
| 61 | + } catch { |
| 62 | + console.warn('WARN: could not parse config.json, using default relays') |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// --- 3. Load or generate bunker keypair --- |
| 67 | + |
| 68 | +const bunkerKeyPath = `${DATA_DIR}/bunker.key` |
| 69 | +let bunkerSk |
| 70 | + |
| 71 | +if (existsSync(bunkerKeyPath)) { |
| 72 | + const hex = readFileSync(bunkerKeyPath, 'utf-8').trim() |
| 73 | + bunkerSk = Uint8Array.from(Buffer.from(hex, 'hex')) |
| 74 | +} else { |
| 75 | + bunkerSk = generateSecretKey() |
| 76 | + const hex = Buffer.from(bunkerSk).toString('hex') |
| 77 | + writeFileSync(bunkerKeyPath, hex, { mode: 0o600 }) |
| 78 | + console.log('Generated new bunker keypair') |
| 79 | +} |
| 80 | + |
| 81 | +const bunkerPk = getPublicKey(bunkerSk) |
| 82 | + |
| 83 | +// --- 4. Connect to relays and subscribe --- |
| 84 | + |
| 85 | +const pool = new SimplePool() |
| 86 | + |
| 87 | +pool.subscribeMany( |
| 88 | + relays, |
| 89 | + { kinds: [24133], '#p': [bunkerPk] }, |
| 90 | + { |
| 91 | + onevent: async (event) => { |
| 92 | + try { |
| 93 | + await handleRequest(event) |
| 94 | + } catch (e) { |
| 95 | + console.error(`Error handling request: ${e.message}`) |
| 96 | + } |
| 97 | + }, |
| 98 | + }, |
| 99 | +) |
| 100 | + |
| 101 | +// --- 5. Write bunker URI --- |
| 102 | + |
| 103 | +const relayParams = relays.map((r) => `relay=${encodeURIComponent(r)}`).join('&') |
| 104 | +const bunkerUri = `bunker://${bunkerPk}?${relayParams}` |
| 105 | + |
| 106 | +writeFileSync(`${DATA_DIR}/bunker-uri.txt`, bunkerUri) |
| 107 | + |
| 108 | +console.log(`Bunker started`) |
| 109 | +console.log(` URI: ${bunkerUri}`) |
| 110 | +console.log(` Signing: ${userPk.slice(0, 12)}...`) |
| 111 | +console.log(` Relays: ${relays.join(', ')}`) |
| 112 | + |
| 113 | +// --- 6. Request handler --- |
| 114 | + |
| 115 | +async function handleRequest(event) { |
| 116 | + const clientPk = event.pubkey |
| 117 | + const conversationKey = getConversationKey(bunkerSk, clientPk) |
| 118 | + |
| 119 | + let request |
| 120 | + try { |
| 121 | + const plaintext = decrypt(event.content, conversationKey) |
| 122 | + request = JSON.parse(plaintext) |
| 123 | + } catch { |
| 124 | + console.error('Failed to decrypt request') |
| 125 | + return |
| 126 | + } |
| 127 | + |
| 128 | + console.log(`Request ${request.id}: ${request.method}`) |
| 129 | + |
| 130 | + let result = '' |
| 131 | + let error |
| 132 | + |
| 133 | + switch (request.method) { |
| 134 | + case 'connect': |
| 135 | + result = 'ack' |
| 136 | + break |
| 137 | + |
| 138 | + case 'ping': |
| 139 | + result = 'pong' |
| 140 | + break |
| 141 | + |
| 142 | + case 'get_public_key': |
| 143 | + result = userPk |
| 144 | + break |
| 145 | + |
| 146 | + case 'sign_event': { |
| 147 | + const template = JSON.parse(request.params[0]) |
| 148 | + const signed = finalizeEvent(template, userSk) |
| 149 | + result = JSON.stringify(signed) |
| 150 | + break |
| 151 | + } |
| 152 | + |
| 153 | + case 'nip44_encrypt': { |
| 154 | + const ck = getConversationKey(userSk, request.params[0]) |
| 155 | + result = encrypt(request.params[1], ck) |
| 156 | + break |
| 157 | + } |
| 158 | + |
| 159 | + case 'nip44_decrypt': { |
| 160 | + const ck = getConversationKey(userSk, request.params[0]) |
| 161 | + result = decrypt(request.params[1], ck) |
| 162 | + break |
| 163 | + } |
| 164 | + |
| 165 | + default: |
| 166 | + error = `unsupported method: ${request.method}` |
| 167 | + } |
| 168 | + |
| 169 | + // Build and publish encrypted response |
| 170 | + const response = error |
| 171 | + ? JSON.stringify({ id: request.id, result: '', error }) |
| 172 | + : JSON.stringify({ id: request.id, result }) |
| 173 | + |
| 174 | + const encrypted = encrypt(response, conversationKey) |
| 175 | + const responseEvent = finalizeEvent( |
| 176 | + { |
| 177 | + kind: 24133, |
| 178 | + created_at: Math.floor(Date.now() / 1000), |
| 179 | + tags: [['p', clientPk]], |
| 180 | + content: encrypted, |
| 181 | + }, |
| 182 | + bunkerSk, |
| 183 | + ) |
| 184 | + |
| 185 | + await Promise.any(pool.publish(relays, responseEvent)) |
| 186 | + console.log(`Response ${request.id}: ${error ?? 'ok'}`) |
| 187 | +} |
| 188 | + |
| 189 | +// --- 7. Clean shutdown --- |
| 190 | + |
| 191 | +function shutdown() { |
| 192 | + console.log('Shutting down...') |
| 193 | + pool.close(relays) |
| 194 | + bunkerSk.fill(0) |
| 195 | + userSk.fill(0) |
| 196 | + process.exit(0) |
| 197 | +} |
| 198 | + |
| 199 | +process.on('SIGINT', shutdown) |
| 200 | +process.on('SIGTERM', shutdown) |
0 commit comments