mirror of
https://github.com/PR0M3TH3AN/bitvid.git
synced 2026-10-27 07:52:24 +00:00
239 lines
9.4 KiB
HTML
239 lines
9.4 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<title>Nostr Ephemeral DM Tester (Using finalizeEvent)</title>
|
||
<link rel="stylesheet" href="../css/tailwind.generated.css" />
|
||
|
||
<!--
|
||
Nostr Ephemeral DM Tester (Using finalizeEvent)
|
||
|
||
This HTML file demonstrates how to create a simple ephemeral DM tool using nostr‑tools v2.17.0.
|
||
|
||
Key steps:
|
||
|
||
1. Decode the target npub (using nip19.decode) to extract the target public key.
|
||
2. Generate an ephemeral key pair with generateSecretKey (returns Uint8Array) and getPublicKey (returns hex string).
|
||
3. Encrypt the message using nip04.encrypt (NIP‑04 encryption) with the ephemeral private key and the target public key.
|
||
4. Build an event template (a kind‑4 event) with the encrypted message and a tag containing the target pubkey.
|
||
5. Finalize the event using finalizeEvent, which computes the event id, assigns the ephemeral pubkey, and signs the event.
|
||
6. Publish the event to multiple relays using SimplePool.publish, which returns a promise – we use Promise.any to ensure at least one relay accepted the event.
|
||
7. Connect to each relay using the Relay API (Relay.connect) and subscribe for the event (using onEvent and onEose callbacks) to verify that it is stored.
|
||
|
||
Important lessons:
|
||
|
||
- finalizeEvent greatly simplifies the process by handling id computation and signing.
|
||
- The publish API now returns a promise; using Promise.any allows us to wait until one relay accepts the event.
|
||
- The subscription API has changed – use the Relay API instead of the deprecated pool.sub.
|
||
- Detailed logging is essential for debugging, so logs are output both to the page and the console.
|
||
|
||
References:
|
||
- Nostr-tools documentation: :contentReference[oaicite:0]{index=0}
|
||
- Nostr protocol specifications and community examples.
|
||
-->
|
||
|
||
<!-- Load nostr‑tools v2.17.0 -->
|
||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/nostr.bundle.min.js"></script>
|
||
</head>
|
||
<body class="bg-surface font-sans text-text" data-ds="new">
|
||
<main
|
||
class="mx-auto flex min-h-screen max-w-2xl flex-col gap-6 p-6"
|
||
data-ds="new"
|
||
>
|
||
<header class="space-y-2">
|
||
<h1 class="text-3xl font-semibold text-text">
|
||
Nostr Ephemeral DM Tester (Using finalizeEvent)
|
||
</h1>
|
||
<p class="text-base leading-relaxed text-text">
|
||
Generates a random ephemeral key, encrypts your message (NIP‑04),
|
||
finalizes the event (computes event.id and signs it), then publishes
|
||
it. It also subscribes to each relay using the Relay API.
|
||
</p>
|
||
</header>
|
||
|
||
<form id="dm-form" class="space-y-4 rounded-xl bg-panel p-6 shadow-lg">
|
||
<div class="space-y-2">
|
||
<label for="npubInput" class="block text-sm font-semibold text-text"
|
||
>Target npub:</label
|
||
>
|
||
<input
|
||
type="text"
|
||
id="npubInput"
|
||
class="form-control"
|
||
placeholder="npub13yarr7j6vjqjjkahd63dmr27curypehx45ucue286ac7sft27y0srnpmpe"
|
||
required
|
||
/>
|
||
</div>
|
||
|
||
<div class="space-y-2">
|
||
<label for="msgInput" class="block text-sm font-semibold text-text"
|
||
>Message:</label
|
||
>
|
||
<textarea
|
||
id="msgInput"
|
||
rows="3"
|
||
class="textarea"
|
||
placeholder="Hello from ephemeral DM!"
|
||
></textarea>
|
||
</div>
|
||
|
||
<div class="flex justify-end">
|
||
<button type="submit" class="btn">Send DM</button>
|
||
</div>
|
||
</form>
|
||
|
||
<div
|
||
id="status"
|
||
role="status"
|
||
aria-live="polite"
|
||
class="status-log min-h-status-log space-y-2 rounded-xl bg-card p-4 text-text shadow-md"
|
||
></div>
|
||
</main>
|
||
|
||
<script>
|
||
document.addEventListener("DOMContentLoaded", () => {
|
||
// Logging functions for both on-page and console output.
|
||
function log(msg, type = "info") {
|
||
const div = document.createElement("div");
|
||
div.classList.add("status-line");
|
||
if (type === "error") div.classList.add("error");
|
||
if (type === "success") div.classList.add("success");
|
||
if (type === "warn") div.classList.add("warn");
|
||
div.textContent = msg;
|
||
document.getElementById("status").appendChild(div);
|
||
console.log(`[${type.toUpperCase()}] ${msg}`);
|
||
}
|
||
function clear() {
|
||
document.getElementById("status").innerHTML = "";
|
||
}
|
||
|
||
if (!window.NostrTools) {
|
||
log("NostrTools not loaded. Check console or ad-blockers.", "error");
|
||
return;
|
||
}
|
||
|
||
// Destructure the required functions and classes from nostr-tools.
|
||
// finalizeEvent is used to automatically compute the event id, sign the event, and assign the pubkey.
|
||
const {
|
||
generateSecretKey,
|
||
getPublicKey,
|
||
finalizeEvent,
|
||
nip04,
|
||
nip19,
|
||
SimplePool,
|
||
utils,
|
||
Relay // Relay API for subscriptions.
|
||
} = window.NostrTools;
|
||
|
||
// Define relay URLs.
|
||
const RELAYS = [
|
||
"wss://relay.snort.social",
|
||
"wss://relay.damus.io",
|
||
"wss://relay.primal.net"
|
||
];
|
||
|
||
// Create a SimplePool instance for publishing events.
|
||
const pool = new SimplePool();
|
||
|
||
// Main form submission handler.
|
||
document
|
||
.getElementById("dm-form")
|
||
.addEventListener("submit", async (ev) => {
|
||
ev.preventDefault();
|
||
clear();
|
||
|
||
try {
|
||
// 1) Retrieve and validate user input.
|
||
const npub = document.getElementById("npubInput").value.trim();
|
||
if (!npub.startsWith("npub")) {
|
||
throw new Error("Target must start with npub.");
|
||
}
|
||
const message =
|
||
document.getElementById("msgInput").value.trim() ||
|
||
"Hello from ephemeral DM!";
|
||
|
||
// 2) Decode the npub to obtain the target public key.
|
||
log("Decoding target npub...");
|
||
const decoded = nip19.decode(npub);
|
||
log(`[DEBUG] Decoded npub: ${JSON.stringify(decoded)}`);
|
||
if (decoded.type !== "npub") {
|
||
throw new Error("Decoded type is not npub.");
|
||
}
|
||
const targetPubHex = decoded.data;
|
||
log(`Target pubkey: ${targetPubHex.slice(0, 16)}...`);
|
||
|
||
// 3) Generate an ephemeral key pair.
|
||
log("Generating ephemeral key...");
|
||
const ephemeralPriv = generateSecretKey(); // Returns a Uint8Array.
|
||
const ephemeralPubHex = getPublicKey(ephemeralPriv); // Returns a hex string.
|
||
log(`Ephemeral pubkey: ${ephemeralPubHex.slice(0, 16)}...`);
|
||
|
||
// 4) Encrypt the message using NIP‑04 encryption.
|
||
log("Encrypting message (nip04)...");
|
||
const ciphertext = await nip04.encrypt(
|
||
ephemeralPriv,
|
||
targetPubHex,
|
||
message
|
||
);
|
||
log(`[DEBUG] Ciphertext: ${ciphertext}`);
|
||
log("Encryption done.");
|
||
|
||
// 5) Build the DM event template (without id and signature).
|
||
const now = Math.floor(Date.now() / 1000);
|
||
const eventTemplate = {
|
||
kind: 4,
|
||
created_at: now,
|
||
tags: [["p", targetPubHex]],
|
||
content: ciphertext
|
||
};
|
||
log(
|
||
`[DEBUG] Event template before finalizing: ${JSON.stringify(
|
||
eventTemplate
|
||
)}`
|
||
);
|
||
|
||
// 6) Finalize the event: compute the event id, sign it, and assign the pubkey.
|
||
const event = finalizeEvent(eventTemplate, ephemeralPriv);
|
||
log(`[DEBUG] Final event: ${JSON.stringify(event)}`);
|
||
|
||
// 7) Publish the event to all relays.
|
||
log("Publishing to relays...");
|
||
// pool.publish now accepts an array of relay URLs and returns a promise.
|
||
await Promise.any(pool.publish(RELAYS, event));
|
||
log("At least one relay accepted the event.", "success");
|
||
|
||
// 8) For each relay, connect using the Relay API and subscribe to verify event storage.
|
||
for (const url of RELAYS) {
|
||
log(`Connecting to ${url} for subscription...`);
|
||
const relay = await Relay.connect(url);
|
||
relay.subscribe([{ authors: [ephemeralPubHex], kinds: [4] }], {
|
||
onEvent(foundEvent) {
|
||
if (foundEvent.id === event.id) {
|
||
log(
|
||
`[${url}] => Found our DM in storage! ID: ${foundEvent.id.slice(
|
||
0,
|
||
8
|
||
)}...`,
|
||
"success"
|
||
);
|
||
}
|
||
},
|
||
onEose() {
|
||
relay.close();
|
||
}
|
||
});
|
||
}
|
||
|
||
log(
|
||
"Done. If the logs show 'Relay accepted' and 'Found our DM in storage', the event is on at least one relay. Another client must subscribe to ephemeralPubHex or #p=targetPubHex to see it."
|
||
);
|
||
} catch (err) {
|
||
log("Error: " + err.message, "error");
|
||
console.error(err);
|
||
}
|
||
});
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|