// Faithful mirror of hyperident-gateway's proven 2-peer connection logic
// (repos/hyperident-gateway/lib/hyperswarm-router.js). NO dht opts, NO early exit —
// the gateway is a daemon that never gives up; Hyperswarm's RetryTimer backs off and the
// first NAT holepunch can land well after 60s. Run the SAME command on both boxes:
//
// bare scripts/gw-mirror.mjs <label>
//
// It logs every connection (elapsed + peer key) and a periodic heartbeat with dht.firewalled
// + live swarm stats, and it KEEPS RUNNING. If the gateway connects these boxes, so does this.
import '../lib/bare-globals.js'
import Hyperswarm from 'hyperswarm'
import crypto from 'hypercore-crypto'
import b4a from 'b4a'
const argv = (typeof Bare !== 'undefined' && Bare.argv) ? Bare.argv : process.argv
const has = (n) => argv.indexOf('--' + n) >= 0
const label = argv.slice(2).find((a) => a && !a.startsWith('--')) || 'peer'
// Role: default symmetric (gateway pattern). --server / --client replicate HPP's ASYMMETRIC
// topology (peer=server-only announces; bridge=client-only looks up) to isolate whether the
// asymmetry — vs the bridge's one-shot 15s timeout — is what breaks the membrane connect.
const server = has('client') ? false : true // --client → client-only
const client = has('server') ? false : true // --server → server-only
// Fixed, SHARED topic (both instances derive the same hash) — exactly the gateway's scheme.
const topic = crypto.hash(b4a.from('hpp-gw-mirror-test')).subarray(0, 32)
const swarm = new Hyperswarm() // plain — identical to hyperswarm-router.js:74
const t0 = Date.now()
let n = 0
swarm.on('connection', (conn, info) => {
n++
console.log(JSON.stringify({ ev: 'CONNECTED', label, n, ms: Date.now() - t0, client: info.client, remote: b4a.toString(info.publicKey, 'hex').slice(0, 12) }))
conn.on('error', () => {})
conn.on('close', () => console.log(JSON.stringify({ ev: 'closed', label, ms: Date.now() - t0, remote: b4a.toString(info.publicKey, 'hex').slice(0, 12) })))
conn.write(b4a.from('hi:' + label))
conn.on('data', (d) => console.log(JSON.stringify({ ev: 'recv', label, msg: b4a.toString(d).slice(0, 20) })))
})
const disc = swarm.join(topic, { server, client }) // gateway: both true; HPP: asymmetric via flags
await disc.flushed()
console.log(JSON.stringify({ ev: 'JOINED', label, role: { server, client }, topic: b4a.toString(topic, 'hex').slice(0, 16), me: b4a.toString(swarm.keyPair.publicKey, 'hex').slice(0, 12) }))
setInterval(() => {
const s = swarm.stats.connects
console.log(JSON.stringify({ ev: 'hb', label, ms: Date.now() - t0, conns: swarm.connections.size, firewalled: swarm.dht.firewalled, cAtt: s.client.attempted, cOpen: s.client.opened, sOpen: s.server.opened }))
}, 15000)
// NO exit — persist like the gateway daemon.