mirror of
https://github.com/block/buzz.git
synced 2026-11-30 21:21:48 +00:00
feat(proxy): NIP-28 translation proxy for third-party Nostr clients (#43)
This commit is contained in:
17
scripts/nostr-tools-test-package.json
Normal file
17
scripts/nostr-tools-test-package.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "nostr-tools-test",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"nostr-tools": "^2.23.3",
|
||||
"ws": "^8.19.0"
|
||||
}
|
||||
}
|
||||
140
scripts/test-proxy-e2e-live.sh
Executable file
140
scripts/test-proxy-e2e-live.sh
Executable file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env bash
|
||||
# Live e2e test for sprout-proxy — requires relay on :3000 and proxy on :4869
|
||||
set -euo pipefail
|
||||
|
||||
PROXY_URL="ws://0.0.0.0:4869"
|
||||
PROXY_HTTP="http://localhost:4869"
|
||||
ADMIN_SECRET="test-admin-secret"
|
||||
|
||||
PASS=0
|
||||
FAIL=0
|
||||
|
||||
ok() { PASS=$((PASS+1)); echo " ✅ $1"; }
|
||||
fail() { FAIL=$((FAIL+1)); echo " ❌ $1"; }
|
||||
|
||||
echo "═══ sprout-proxy e2e tests ═══"
|
||||
echo ""
|
||||
|
||||
# ── Test 1: NIP-11 ──────────────────────────────────────────────────────
|
||||
echo "1. NIP-11 relay info"
|
||||
NIP11=$(curl -sf "$PROXY_HTTP" -H "Accept: application/nostr+json")
|
||||
if echo "$NIP11" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d['name']=='sprout-proxy'" 2>/dev/null; then
|
||||
ok "NIP-11 returns valid relay info"
|
||||
else
|
||||
fail "NIP-11 check failed"
|
||||
fi
|
||||
|
||||
# ── Test 2: Register guest ──────────────────────────────────────────────
|
||||
echo "2. Guest registration (pubkey-based)"
|
||||
GUEST_SK=$(nak key generate)
|
||||
GUEST_PK=$(nak key public "$GUEST_SK")
|
||||
CHANNEL_UUID="6f953bb4-f761-4bc2-98de-392470c2b897"
|
||||
|
||||
REG=$(curl -sf -X POST "$PROXY_HTTP/admin/guests" \
|
||||
-H "Authorization: Bearer $ADMIN_SECRET" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"pubkey\": \"$GUEST_PK\", \"channels\": \"$CHANNEL_UUID\"}")
|
||||
if echo "$REG" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d['pubkey']=='$GUEST_PK'" 2>/dev/null; then
|
||||
ok "Guest registered: $GUEST_PK"
|
||||
else
|
||||
fail "Guest registration failed: $REG"
|
||||
fi
|
||||
|
||||
# ── Test 3: List guests ─────────────────────────────────────────────────
|
||||
echo "3. List guests"
|
||||
LIST=$(curl -sf "$PROXY_HTTP/admin/guests" -H "Authorization: Bearer $ADMIN_SECRET")
|
||||
if echo "$LIST" | python3 -c "import sys,json; d=json.load(sys.stdin); assert len(d['guests'])>=1" 2>/dev/null; then
|
||||
ok "Guest list returns registered guests"
|
||||
else
|
||||
fail "Guest list failed: $LIST"
|
||||
fi
|
||||
|
||||
# ── Test 4: Admin auth required ─────────────────────────────────────────
|
||||
echo "4. Admin auth enforcement"
|
||||
NOAUTH=$(curl -s -o /dev/null -w "%{http_code}" "$PROXY_HTTP/admin/guests")
|
||||
if [ "$NOAUTH" = "401" ]; then
|
||||
ok "Admin endpoint rejects unauthenticated requests"
|
||||
else
|
||||
fail "Expected 401, got $NOAUTH"
|
||||
fi
|
||||
|
||||
# ── Test 5: WebSocket AUTH challenge ────────────────────────────────────
|
||||
echo "5. WebSocket NIP-42 challenge"
|
||||
CHALLENGE=$(echo "" | timeout 3 websocat -t -1 "$PROXY_URL" 2>/dev/null | head -1)
|
||||
if echo "$CHALLENGE" | python3 -c "import sys,json; d=json.loads(sys.stdin.read()); assert d[0]=='AUTH'" 2>/dev/null; then
|
||||
ok "Proxy sends NIP-42 AUTH challenge on connect"
|
||||
else
|
||||
fail "No AUTH challenge received: $CHALLENGE"
|
||||
fi
|
||||
|
||||
# ── Test 6: Full NIP-42 handshake (pubkey-based, no token) ─────────────
|
||||
echo "6. Full NIP-42 auth handshake (pubkey-based)"
|
||||
|
||||
# Use a Python script to do the full handshake on a single WebSocket connection.
|
||||
RESPONSE=$(uv run python3 -c "
|
||||
import asyncio, json, subprocess, sys
|
||||
|
||||
async def test():
|
||||
import websockets
|
||||
async with websockets.connect('$PROXY_URL') as ws:
|
||||
# 1. Receive AUTH challenge
|
||||
msg = json.loads(await ws.recv())
|
||||
assert msg[0] == 'AUTH', f'Expected AUTH, got {msg[0]}'
|
||||
challenge = msg[1]
|
||||
|
||||
# 2. Create signed auth event with nak
|
||||
auth_json = subprocess.check_output([
|
||||
'nak', 'event', '--sec', '$GUEST_SK', '-k', '22242',
|
||||
'--tag', 'relay=$PROXY_URL',
|
||||
'--tag', f'challenge={challenge}',
|
||||
'-c', ''
|
||||
], text=True).strip()
|
||||
|
||||
# 3. Send AUTH response
|
||||
await ws.send(json.dumps(['AUTH', json.loads(auth_json)]))
|
||||
|
||||
# 4. Read OK
|
||||
ok_msg = json.loads(await ws.recv())
|
||||
print(json.dumps(ok_msg))
|
||||
|
||||
asyncio.run(test())
|
||||
" 2>&1) || true
|
||||
|
||||
echo " Response: $RESPONSE"
|
||||
|
||||
if echo "$RESPONSE" | python3 -c "import sys,json; d=json.loads(sys.stdin.read()); assert d[0]=='OK' and d[2]==True" 2>/dev/null; then
|
||||
ok "NIP-42 auth succeeded (pubkey-based, no token)"
|
||||
else
|
||||
# Fall back: try without websockets library (use websocat with named pipe)
|
||||
fail "NIP-42 auth handshake: $RESPONSE"
|
||||
fi
|
||||
|
||||
# ── Test 7: Create invite token ─────────────────────────────────────────
|
||||
echo "7. Invite token creation"
|
||||
INVITE=$(curl -sf -X POST "$PROXY_HTTP/admin/invite" \
|
||||
-H "Authorization: Bearer $ADMIN_SECRET" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"channels\": \"$CHANNEL_UUID\", \"hours\": 1, \"max_uses\": 5}")
|
||||
TOKEN=$(echo "$INVITE" | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])" 2>/dev/null)
|
||||
if [ -n "$TOKEN" ]; then
|
||||
ok "Invite token created: ${TOKEN:0:30}..."
|
||||
else
|
||||
fail "Invite token creation failed: $INVITE"
|
||||
fi
|
||||
|
||||
# ── Test 8: Revoke guest ────────────────────────────────────────────────
|
||||
echo "8. Guest revocation"
|
||||
REVOKE=$(curl -sf -X DELETE "$PROXY_HTTP/admin/guests" \
|
||||
-H "Authorization: Bearer $ADMIN_SECRET" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"pubkey\": \"$GUEST_PK\"}")
|
||||
if echo "$REVOKE" | python3 -c "import sys,json; d=json.load(sys.stdin); assert d['revoked']==True" 2>/dev/null; then
|
||||
ok "Guest revoked"
|
||||
else
|
||||
fail "Guest revocation failed: $REVOKE"
|
||||
fi
|
||||
|
||||
# ── Summary ─────────────────────────────────────────────────────────────
|
||||
echo ""
|
||||
echo "═══ Results: $PASS passed, $FAIL failed ═══"
|
||||
[ "$FAIL" -eq 0 ] && exit 0 || exit 1
|
||||
89
scripts/test-proxy-e2e.sh
Executable file
89
scripts/test-proxy-e2e.sh
Executable file
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env bash
|
||||
# End-to-end test for sprout-proxy
|
||||
# Prerequisites:
|
||||
# - Sprout relay running on :3000 (just relay)
|
||||
# - Sprout proxy running on :4869 (just proxy)
|
||||
# - websocat installed (cargo install websocat)
|
||||
# - curl installed
|
||||
# - jq installed
|
||||
set -euo pipefail
|
||||
|
||||
PROXY_URL="${PROXY_URL:-ws://localhost:4869}"
|
||||
PROXY_HTTP="${PROXY_HTTP:-http://localhost:4869}"
|
||||
RELAY_HTTP="${RELAY_HTTP:-http://localhost:3000}"
|
||||
|
||||
echo "=== Sprout Proxy E2E Test ==="
|
||||
echo "Proxy: $PROXY_URL"
|
||||
echo "Relay: $RELAY_HTTP"
|
||||
|
||||
# Step 1: Check NIP-11
|
||||
echo ""
|
||||
echo "--- Step 1: NIP-11 Info Document ---"
|
||||
NIP11=$(curl -sf -H "Accept: application/nostr+json" "$PROXY_HTTP/" || true)
|
||||
if [ -z "$NIP11" ]; then
|
||||
echo "FAIL: NIP-11 endpoint not responding"
|
||||
exit 1
|
||||
fi
|
||||
echo "$NIP11" | jq .
|
||||
echo "PASS: NIP-11 document served"
|
||||
|
||||
# Step 2: Create invite token
|
||||
echo ""
|
||||
echo "--- Step 2: Create Invite Token ---"
|
||||
# Get a channel UUID from the relay
|
||||
CHANNEL_ID=$(curl -sf "$RELAY_HTTP/api/channels" -H "X-Pubkey: 0101010101010101010101010101010101010101010101010101010101010101" | jq -r '.[0].id // empty')
|
||||
if [ -z "$CHANNEL_ID" ]; then
|
||||
echo "WARN: No channels found in relay. Creating a test channel..."
|
||||
CHANNEL_ID=$(curl -sf -X POST "$RELAY_HTTP/api/channels" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-Pubkey: 0101010101010101010101010101010101010101010101010101010101010101" \
|
||||
-d '{"name":"proxy-test","channel_type":"stream","visibility":"open"}' | jq -r '.id')
|
||||
fi
|
||||
echo "Using channel: $CHANNEL_ID"
|
||||
|
||||
INVITE=$(curl -sf -X POST "$PROXY_HTTP/admin/invite" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"channels\": \"$CHANNEL_ID\", \"hours\": 1, \"max_uses\": 10}" || true)
|
||||
if [ -z "$INVITE" ]; then
|
||||
echo "FAIL: Could not create invite token"
|
||||
exit 1
|
||||
fi
|
||||
TOKEN=$(echo "$INVITE" | jq -r '.token')
|
||||
echo "Token: ${TOKEN:0:30}..."
|
||||
echo "PASS: Invite token created"
|
||||
|
||||
# Step 3: Connect and test NIP-42 + kind:40 query
|
||||
echo ""
|
||||
echo "--- Step 3: WebSocket Connection Test ---"
|
||||
echo "Connecting to $PROXY_URL?token=$TOKEN ..."
|
||||
|
||||
# Use a timeout approach: send a REQ for kind:40, expect AUTH challenge + EOSE
|
||||
# websocat with -t (text) and timeout
|
||||
RESULT=$(echo '["REQ","test-sub",{"kinds":[40],"limit":10}]' | \
|
||||
timeout 5 websocat -t -1 "$PROXY_URL?token=$TOKEN" 2>/dev/null || true)
|
||||
|
||||
if [ -z "$RESULT" ]; then
|
||||
echo "FAIL: No response from proxy (timeout or connection refused)"
|
||||
echo "Make sure the proxy is running: just proxy"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Response: $RESULT"
|
||||
|
||||
# Check if we got an AUTH challenge (expected before we authenticate)
|
||||
if echo "$RESULT" | grep -q '"AUTH"'; then
|
||||
echo "PASS: Received NIP-42 AUTH challenge"
|
||||
else
|
||||
echo "INFO: Did not receive AUTH challenge in first message"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== Test Summary ==="
|
||||
echo "NIP-11: PASS"
|
||||
echo "Invite creation: PASS"
|
||||
echo "WebSocket connection: PASS"
|
||||
echo ""
|
||||
echo "For full interactive testing, use:"
|
||||
echo " websocat $PROXY_URL?token=$TOKEN"
|
||||
echo " Then send: [\"AUTH\", <signed-kind-22242-event>]"
|
||||
echo " Then send: [\"REQ\",\"sub1\",{\"kinds\":[40],\"limit\":10}]"
|
||||
152
scripts/test-proxy-nostr-sdk-python.py
Normal file
152
scripts/test-proxy-nostr-sdk-python.py
Normal file
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
sprout-proxy E2E test using nostr-sdk v0.44 (Python bindings for rust-nostr)
|
||||
|
||||
nostr-sdk is the official Rust Nostr SDK with Python/Swift/Flutter bindings.
|
||||
Second most popular Nostr SDK after nostr-tools, powers native clients.
|
||||
|
||||
Tests:
|
||||
1. NIP-42 authentication (automatic_authentication)
|
||||
2. Channel discovery (kind:40)
|
||||
3. Channel metadata (kind:41)
|
||||
4. Send channel message (kind:42 via EventBuilder.channel_msg)
|
||||
5. Read messages (kind:42 fetch + round-trip verification)
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
import nostr_sdk
|
||||
|
||||
RELAY_URL = "ws://localhost:4869"
|
||||
PRIVKEY_HEX = open("/tmp/guest3_privkey.txt").read().strip()
|
||||
CHANNEL_EVENT_ID_HEX = "8155f2a8685beb2b4c5ac1796d555ac0b8e8ae1d3a76a7a3f63cce57905cddeb"
|
||||
|
||||
results = []
|
||||
|
||||
def ok(name, detail=""):
|
||||
results.append((name, True))
|
||||
print(f" ✅ {name}" + (f" — {detail}" if detail else ""))
|
||||
|
||||
def fail(name, detail=""):
|
||||
results.append((name, False))
|
||||
print(f" ❌ {name}" + (f" — {detail}" if detail else ""))
|
||||
|
||||
|
||||
async def main():
|
||||
print("=" * 64)
|
||||
print(" nostr-sdk v0.44 (Python/Rust) E2E TEST against sprout-proxy")
|
||||
print("=" * 64)
|
||||
|
||||
keys = nostr_sdk.Keys.parse(PRIVKEY_HEX)
|
||||
pubkey = keys.public_key().to_hex()
|
||||
print(f" Relay: {RELAY_URL}")
|
||||
print(f" Pubkey: {pubkey[:24]}...")
|
||||
print()
|
||||
|
||||
relay_url = nostr_sdk.RelayUrl.parse(RELAY_URL)
|
||||
channel_eid = nostr_sdk.EventId.parse(CHANNEL_EVENT_ID_HEX)
|
||||
timeout = timedelta(seconds=10)
|
||||
|
||||
signer = nostr_sdk.NostrSigner.keys(keys)
|
||||
client = nostr_sdk.ClientBuilder().signer(signer).build()
|
||||
client.automatic_authentication(True)
|
||||
|
||||
# ── 1. Connect + NIP-42 Auth ─────────────────────────────────────────
|
||||
print("[1/5] Connect + NIP-42 Authentication")
|
||||
try:
|
||||
await client.add_relay(relay_url)
|
||||
await client.connect()
|
||||
await asyncio.sleep(2)
|
||||
ok("NIP-42 Auth", f"automatic_authentication as {pubkey[:16]}...")
|
||||
except Exception as e:
|
||||
fail("NIP-42 Auth", str(e))
|
||||
return
|
||||
|
||||
# ── 2. Channel Discovery (kind:40) ───────────────────────────────────
|
||||
print("\n[2/5] Channel Discovery (kind:40)")
|
||||
try:
|
||||
f40 = nostr_sdk.Filter().kind(nostr_sdk.Kind(40)).limit(100)
|
||||
events = await client.fetch_events(f40, timeout)
|
||||
evts = events.to_vec()
|
||||
if evts:
|
||||
for e in evts:
|
||||
content = json.loads(e.content()) if e.content() else {}
|
||||
name = content.get("name", "?")
|
||||
print(f" • {name} (id: {e.id().to_hex()[:24]}...)")
|
||||
ok("Channel Discovery", f"{len(evts)} channel(s)")
|
||||
else:
|
||||
fail("Channel Discovery", "no kind:40 events")
|
||||
except Exception as e:
|
||||
fail("Channel Discovery", str(e))
|
||||
|
||||
# ── 3. Channel Metadata (kind:41) ────────────────────────────────────
|
||||
print("\n[3/5] Channel Metadata (kind:41)")
|
||||
try:
|
||||
f41 = nostr_sdk.Filter().kind(nostr_sdk.Kind(41)).event(channel_eid).limit(5)
|
||||
meta = await client.fetch_events(f41, timeout)
|
||||
meta_vec = meta.to_vec()
|
||||
if meta_vec:
|
||||
c = json.loads(meta_vec[0].content())
|
||||
ok("Channel Metadata", f'name="{c.get("name")}", about="{c.get("about","")[:50]}"')
|
||||
else:
|
||||
fail("Channel Metadata", "no kind:41 events")
|
||||
except Exception as e:
|
||||
fail("Channel Metadata", str(e))
|
||||
|
||||
# ── 4. Send Channel Message (kind:42) ────────────────────────────────
|
||||
print("\n[4/5] Send Channel Message (EventBuilder.channel_msg)")
|
||||
ts = int(time.time())
|
||||
msg_text = f"Hello from nostr-sdk Python! 🐍 [{ts}]"
|
||||
try:
|
||||
builder = nostr_sdk.EventBuilder.channel_msg(channel_eid, relay_url, msg_text)
|
||||
output = await client.send_event_builder(builder)
|
||||
sent_id = output.id.to_hex() # .id is a property, not a method
|
||||
ok("Send Message", f'"{msg_text}" (id: {sent_id[:16]}...)')
|
||||
except Exception as e:
|
||||
fail("Send Message", str(e))
|
||||
|
||||
# ── 5. Read Messages + Round-Trip ────────────────────────────────────
|
||||
print("\n[5/5] Read Messages + Round-Trip Verification")
|
||||
try:
|
||||
f42 = nostr_sdk.Filter().kind(nostr_sdk.Kind(42)).event(channel_eid).limit(10)
|
||||
msgs = await client.fetch_events(f42, timeout)
|
||||
msg_vec = msgs.to_vec()
|
||||
found_ours = False
|
||||
print(f" {len(msg_vec)} message(s):")
|
||||
for e in msg_vec:
|
||||
marker = "→ " if "nostr-sdk Python" in e.content() else " "
|
||||
print(f" {marker}[{e.author().to_hex()[:12]}...] {e.content()[:65]}")
|
||||
if "nostr-sdk Python" in e.content():
|
||||
found_ours = True
|
||||
if found_ours:
|
||||
ok("Read + Round-Trip", f"our message verified among {len(msg_vec)}")
|
||||
elif msg_vec:
|
||||
ok("Read + Round-Trip", f"{len(msg_vec)} messages (ours may be propagating)")
|
||||
else:
|
||||
fail("Read + Round-Trip", "no messages")
|
||||
except Exception as e:
|
||||
fail("Read + Round-Trip", str(e))
|
||||
|
||||
await client.disconnect()
|
||||
|
||||
# ── Summary ──────────────────────────────────────────────────────────
|
||||
print("\n" + "=" * 64)
|
||||
print(" RESULTS")
|
||||
print("=" * 64)
|
||||
all_pass = True
|
||||
for name, passed in results:
|
||||
print(f" {'✅ PASS' if passed else '❌ FAIL'} {name}")
|
||||
if not passed:
|
||||
all_pass = False
|
||||
print("=" * 64)
|
||||
if all_pass:
|
||||
print(" 🎉 ALL TESTS PASSED — nostr-sdk Python works with sprout-proxy!")
|
||||
else:
|
||||
print(" ⚠️ Some tests failed")
|
||||
print("=" * 64)
|
||||
|
||||
|
||||
asyncio.run(main())
|
||||
260
scripts/test-proxy-nostr-tools.mjs
Normal file
260
scripts/test-proxy-nostr-tools.mjs
Normal file
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* sprout-proxy E2E test using nostr-tools v2.23.3
|
||||
*
|
||||
* nostr-tools is the most widely-used Nostr library in the ecosystem,
|
||||
* powering Coracle, Snort, Damus Web, and hundreds of other clients.
|
||||
*
|
||||
* Tests the full NIP-28 channel flow through sprout-proxy:
|
||||
* 1. NIP-42 authentication (automatic via onauth callback)
|
||||
* 2. Channel discovery (kind:40)
|
||||
* 3. Channel metadata (kind:41)
|
||||
* 4. Send a channel message (kind:42 via NIP-28 channelMessageEvent)
|
||||
* 5. Receive messages (kind:42 subscription)
|
||||
* 6. Live streaming (real-time event delivery)
|
||||
*/
|
||||
|
||||
import { Relay } from 'nostr-tools/relay'
|
||||
import { finalizeEvent, getPublicKey } from 'nostr-tools/pure'
|
||||
import { channelMessageEvent } from 'nostr-tools/nip28'
|
||||
import { hexToBytes } from 'nostr-tools/utils'
|
||||
import WebSocket from 'ws'
|
||||
|
||||
// ── Config ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const RELAY_URL = process.env.RELAY_URL || 'ws://localhost:4869'
|
||||
const GUEST_PRIVKEY_HEX = process.env.GUEST_PRIVKEY
|
||||
const CHANNEL_EVENT_ID = process.env.CHANNEL_EVENT_ID
|
||||
|
||||
if (!GUEST_PRIVKEY_HEX || !CHANNEL_EVENT_ID) {
|
||||
console.error('Usage: GUEST_PRIVKEY=<hex> CHANNEL_EVENT_ID=<hex> node test-sprout-proxy.mjs')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const secretKey = hexToBytes(GUEST_PRIVKEY_HEX)
|
||||
const pubkey = getPublicKey(secretKey)
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
const results = []
|
||||
function pass(name, detail) {
|
||||
results.push({ name, ok: true })
|
||||
console.log(` ✅ ${name}${detail ? ` — ${detail}` : ''}`)
|
||||
}
|
||||
function fail(name, detail) {
|
||||
results.push({ name, ok: false })
|
||||
console.log(` ❌ ${name}${detail ? ` — ${detail}` : ''}`)
|
||||
}
|
||||
|
||||
/** Collect events from a subscription until EOSE, with timeout. */
|
||||
function list(relay, filters, timeoutMs = 8000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const events = []
|
||||
const timer = setTimeout(() => {
|
||||
sub.close()
|
||||
resolve(events)
|
||||
}, timeoutMs)
|
||||
|
||||
const sub = relay.subscribe(filters, {
|
||||
onevent(evt) { events.push(evt) },
|
||||
oneose() {
|
||||
clearTimeout(timer)
|
||||
sub.close()
|
||||
resolve(events)
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// ── Main ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function main() {
|
||||
console.log('═'.repeat(64))
|
||||
console.log(' nostr-tools v2.23 E2E TEST against sprout-proxy')
|
||||
console.log('═'.repeat(64))
|
||||
console.log(` Relay: ${RELAY_URL}`)
|
||||
console.log(` Pubkey: ${pubkey.slice(0, 24)}...`)
|
||||
console.log()
|
||||
|
||||
// ── 1. Connect + NIP-42 Auth ──────────────────────────────────────────
|
||||
|
||||
console.log('[1/6] Connect + NIP-42 Authentication')
|
||||
|
||||
// nostr-tools' Relay class calls onauth when it receives an AUTH challenge.
|
||||
// We set it before connecting so the handshake is automatic.
|
||||
const relay = new Relay(RELAY_URL, { websocketImplementation: WebSocket })
|
||||
|
||||
// Wire up the NIP-42 auth callback BEFORE connecting.
|
||||
// nostr-tools calls: relay.auth(onauth) → onauth(makeAuthEvent(url, challenge))
|
||||
// So onauth receives an unsigned event template and must return a signed event.
|
||||
let authResolved = false
|
||||
relay.onauth = async (authEventTemplate) => {
|
||||
const signed = finalizeEvent(authEventTemplate, secretKey)
|
||||
authResolved = true
|
||||
return signed
|
||||
}
|
||||
|
||||
try {
|
||||
await relay.connect()
|
||||
} catch (e) {
|
||||
fail('Connect', e.message)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Wait a moment for the AUTH challenge to arrive and be handled
|
||||
// nostr-tools' onauth is called synchronously when the AUTH message arrives
|
||||
await new Promise(r => setTimeout(r, 1500))
|
||||
|
||||
if (authResolved) {
|
||||
pass('NIP-42 Auth', `challenge received, signed as ${pubkey.slice(0, 16)}...`)
|
||||
} else {
|
||||
// Auth might still work reactively — the proxy sends CLOSED/OK auth-required
|
||||
// which triggers nostr-tools to call relay.auth()
|
||||
console.log(' ⏳ No proactive AUTH challenge yet — testing reactive auth...')
|
||||
}
|
||||
|
||||
// ── 2. Channel Discovery (kind:40) ────────────────────────────────────
|
||||
|
||||
console.log('\n[2/6] Channel Discovery (kind:40)')
|
||||
|
||||
try {
|
||||
const channels = await list(relay, [{ kinds: [40], limit: 100 }])
|
||||
if (channels.length > 0) {
|
||||
for (const evt of channels) {
|
||||
try {
|
||||
const c = JSON.parse(evt.content)
|
||||
console.log(` • ${c.name || '(unnamed)'} (id: ${evt.id.slice(0, 24)}...)`)
|
||||
} catch { console.log(` • (id: ${evt.id.slice(0, 24)}...)`) }
|
||||
}
|
||||
pass('Channel Discovery', `${channels.length} channel(s)`)
|
||||
} else {
|
||||
fail('Channel Discovery', 'no kind:40 events returned')
|
||||
}
|
||||
} catch (e) {
|
||||
fail('Channel Discovery', e.message)
|
||||
}
|
||||
|
||||
// ── 3. Channel Metadata (kind:41) ─────────────────────────────────────
|
||||
|
||||
console.log('\n[3/6] Channel Metadata (kind:41)')
|
||||
|
||||
try {
|
||||
const meta = await list(relay, [{ kinds: [41], '#e': [CHANNEL_EVENT_ID], limit: 5 }])
|
||||
if (meta.length > 0) {
|
||||
const c = JSON.parse(meta[0].content)
|
||||
pass('Channel Metadata', `name="${c.name}", about="${(c.about || '').slice(0, 50)}"`)
|
||||
} else {
|
||||
fail('Channel Metadata', 'no kind:41 events')
|
||||
}
|
||||
} catch (e) {
|
||||
fail('Channel Metadata', e.message)
|
||||
}
|
||||
|
||||
// ── 4. Send Channel Message (kind:42 via NIP-28) ──────────────────────
|
||||
|
||||
console.log('\n[4/6] Send Channel Message (NIP-28 channelMessageEvent)')
|
||||
|
||||
const ts = Math.floor(Date.now() / 1000)
|
||||
const msgText = `Hello from nostr-tools! 📦 [${ts}]`
|
||||
|
||||
let sentEvent
|
||||
try {
|
||||
sentEvent = channelMessageEvent({
|
||||
channel_create_event_id: CHANNEL_EVENT_ID,
|
||||
relay_url: RELAY_URL,
|
||||
content: msgText,
|
||||
created_at: ts,
|
||||
}, secretKey)
|
||||
|
||||
await relay.publish(sentEvent)
|
||||
pass('Send Message', `"${msgText}" (id: ${sentEvent.id.slice(0, 16)}...)`)
|
||||
} catch (e) {
|
||||
fail('Send Message', e.message)
|
||||
}
|
||||
|
||||
// ── 5. Read Messages (kind:42) ────────────────────────────────────────
|
||||
|
||||
console.log('\n[5/6] Read Messages (kind:42 query)')
|
||||
|
||||
try {
|
||||
const msgs = await list(relay, [{ kinds: [42], '#e': [CHANNEL_EVENT_ID], limit: 10 }])
|
||||
let foundOurs = false
|
||||
console.log(` ${msgs.length} message(s):`)
|
||||
for (const evt of msgs) {
|
||||
const marker = evt.content.includes('nostr-tools') ? '→ ' : ' '
|
||||
console.log(` ${marker}[${evt.pubkey.slice(0, 12)}...] ${evt.content.slice(0, 65)}`)
|
||||
if (evt.content.includes('nostr-tools')) foundOurs = true
|
||||
}
|
||||
if (foundOurs) {
|
||||
pass('Read Messages', `found our message among ${msgs.length}`)
|
||||
} else if (msgs.length > 0) {
|
||||
pass('Read Messages', `${msgs.length} messages (ours may be propagating)`)
|
||||
} else {
|
||||
fail('Read Messages', 'no messages')
|
||||
}
|
||||
} catch (e) {
|
||||
fail('Read Messages', e.message)
|
||||
}
|
||||
|
||||
// ── 6. Live Streaming ─────────────────────────────────────────────────
|
||||
|
||||
console.log('\n[6/6] Live Streaming (real-time event delivery)')
|
||||
|
||||
try {
|
||||
const streamResult = await new Promise((resolve) => {
|
||||
const timer = setTimeout(() => { sub.close(); resolve(false) }, 8000)
|
||||
|
||||
const sub = relay.subscribe([{
|
||||
kinds: [42],
|
||||
'#e': [CHANNEL_EVENT_ID],
|
||||
since: ts,
|
||||
}], {
|
||||
onevent(evt) {
|
||||
if (evt.content.includes('stream-ping')) {
|
||||
clearTimeout(timer)
|
||||
sub.close()
|
||||
resolve(true)
|
||||
}
|
||||
},
|
||||
oneose() {
|
||||
// After EOSE, publish a new message that should arrive live
|
||||
const ping = channelMessageEvent({
|
||||
channel_create_event_id: CHANNEL_EVENT_ID,
|
||||
relay_url: RELAY_URL,
|
||||
content: `nostr-tools stream-ping ${Date.now()}`,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
}, secretKey)
|
||||
relay.publish(ping).catch(() => {})
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (streamResult) {
|
||||
pass('Live Streaming', 'received real-time event')
|
||||
} else {
|
||||
fail('Live Streaming', 'timed out')
|
||||
}
|
||||
} catch (e) {
|
||||
fail('Live Streaming', e.message)
|
||||
}
|
||||
|
||||
// ── Summary ───────────────────────────────────────────────────────────
|
||||
|
||||
relay.close()
|
||||
|
||||
console.log('\n' + '═'.repeat(64))
|
||||
console.log(' RESULTS')
|
||||
console.log('═'.repeat(64))
|
||||
let allPass = true
|
||||
for (const r of results) {
|
||||
console.log(` ${r.ok ? '✅ PASS' : '❌ FAIL'} ${r.name}`)
|
||||
if (!r.ok) allPass = false
|
||||
}
|
||||
console.log('═'.repeat(64))
|
||||
console.log(allPass
|
||||
? ' 🎉 ALL TESTS PASSED — nostr-tools works with sprout-proxy!'
|
||||
: ' ⚠️ Some tests failed')
|
||||
console.log('═'.repeat(64))
|
||||
process.exit(allPass ? 0 : 1)
|
||||
}
|
||||
|
||||
main().catch(e => { console.error('Fatal:', e); process.exit(1) })
|
||||
Reference in New Issue
Block a user