aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/Nostr.svelte
blob: f6c870f9be48bdef3f556bb56a02fb76dd6d7c42 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<script lang="ts">
  import { onMount } from "svelte";
  import { browser } from "$app/environment";
  import { t } from "$lib/translations";
  import PasswordInput from "$comp/PasswordInput.svelte";
  import { Relay } from "nostr-tools/relay";
  import { bytesToHex, hexToBytes } from "@noble/hashes/utils";
  import {
    nip04,
    nip19,
    getEventHash,
    generateSecretKey,
    getPublicKey,
  } from "nostr-tools";
  import { getConversationKey, decrypt } from "nostr-tools/nip44";

  import { copy, focus, fail, post } from "$lib/utils";
  import { eventToSign, signer } from "$lib/store";
  import { nostrConnectRelay } from "$lib/nostr";
  import Success from "$comp/Success.svelte";

  let { id } = $props();
  let extensionAvailable = $derived(browser && window.nostr);

  let cancel = () => {
    eventToSign.set();
    showNsec = false;
    connectUrl = undefined;
    $signer = "cancel";
  };

  let signerAvailable = $derived(
    browser &&
      navigator.userAgent.includes("Android") &&
      navigator.clipboard &&
      navigator.clipboard.readText,
  );

  let hadSigner = $state(!!$signer);

  let connectUrl = $state();
  let nostrConnect = async () => {
    let connectionSecret = crypto.randomUUID();

    let sk = generateSecretKey();
    let pubkey = getPublicKey(sk);

    connectUrl = `nostrconnect://${pubkey}?relay=${encodeURIComponent(nostrConnectRelay)}&perms=sign_event%3A1&name=Coinos&secret=${connectionSecret}`;

    let relay = await Relay.connect(nostrConnectRelay);
    relay.subscribe([{ kinds: [24133], "#p": [pubkey] }], {
      async onevent(event) {
        let pk = event.pubkey;
        try {
          let result;
          try {
            ({ result } = JSON.parse(
              await nip04.decrypt(sk, pk, event.content),
            ));
          } catch (e) {
            let ck = await getConversationKey(sk, pk);
            ({ result } = JSON.parse(await decrypt(event.content, ck)));
          }

          if (result === connectionSecret || result === "ack") {
            $signer = {
              method: "connect",
              params: {
                sk: bytesToHex(sk),
                pk,
                pubkey,
              },
              ready: true,
            };
          }
        } catch (e) {
          console.log("failed to parse nostr connect event", e);
        }
      },
    });
  };

  let nsec = $state();
  let showNsec = $state();
  let toggleNsec = () => {
    $signer = {
      method: "nsec",
    };
  };

  let nsecSign = async () => {
    let sk;
    if (nsec.startsWith("nsec")) sk = nip19.decode(nsec).data as Uint8Array;
    else sk = hexToBytes(nsec);

    $signer = {
      method: "nsec",
      params: { sk: bytesToHex(sk), pk: getPublicKey(sk) },
      ready: true,
    };
  };

  let extensionSign = async () => {
    $signer = { method: "extension", ready: true };
  };

  let signerSign = async () => {
    document.addEventListener("focus", signerSigned, true);
  };

  const signerSigned = async () => {
    await new Promise((r) => setTimeout(r, 100));
    let sig = await navigator.clipboard.readText();
    $signer.params.sig = sig;
    $signer.ready = true;
    $signer = $signer;
  };

  let signUrl = $derived(
    `nostrsigner:${encodeURIComponent(JSON.stringify($eventToSign))}?compressionType=none&returnType=signature&type=sign_event&appName=Coinos`,
  );
</script>

{#if $eventToSign && !$signer?.ready}
  <div
    class="fixed inset-0 bg-base-100 bg-opacity-90 overflow-y-auto h-full w-full z-50"
  >
    <div
      class="relative mx-auto mt-10 p-5 border w-96 shadow-lg rounded-md bg-base-100 space-y-5"
    >
      <h1 class="text-center text-2xl font-semibold">Nostr sign</h1>

      {#if $eventToSign.sig && !hadSigner}
        <Success />
      {:else}
        {#if connectUrl}
          <div class="space-y-2">
            <a href={connectUrl} class="block space-y-2">
              <img
                src={`/qr/${encodeURIComponent(connectUrl)}/raw`}
                class="z-10 border-4 border-white"
                alt="QR"
              />
              <div class="break-all">
                {connectUrl}
              </div>
            </a>
            <a href={connectUrl} class="btn">
              <iconify-icon
                noobserver
                icon="ph:arrow-square-out-bold"
                width="32"
              ></iconify-icon>
              {$t("payments.openLink")}</a
            >
            <button class="btn" onclick={() => copy(connectUrl)}>
              <iconify-icon noobserver icon="ph:copy-bold" width="32"
              ></iconify-icon>
              {$t("payments.copy")}</button
            >
          </div>
        {:else}
          {#if $signer?.method === "nsec"}
            <input bind:value={nsec} placeholder="nsec..." />
            <button type="button" class="btn btn-accent" onclick={nsecSign}>
              <iconify-icon icon="ph:paper-plane-right-bold" width="32"
              ></iconify-icon>
              <div class="my-auto">Submit</div>
            </button>
          {/if}

          {#if !$signer}
            {#if extensionAvailable}
              <button type="button" class="btn" onclick={extensionSign}>
                <iconify-icon
                  icon="lucide-lab:bee"
                  width="32"
                  class="text-yellow-400"
                ></iconify-icon>
                <div class="my-auto">Browser extension</div>
              </button>
            {/if}

            <button type="button" class="btn" onclick={nostrConnect}>
              <img src="/images/nostr.png" class="w-8" alt="Nostr" />
              <div class="my-auto">Nostr connect</div>
            </button>

            <button type="button" class="btn" onclick={toggleNsec}>
              <iconify-icon icon="ph:key-bold" width="32"></iconify-icon>
              <div class="my-auto">Secret key</div>
            </button>
          {/if}
        {/if}

        <button type="button" class="btn" onclick={cancel}>
          <iconify-icon icon="ph:x-bold" width="32"></iconify-icon>
          <div class="my-auto">Cancel</div>
        </button>
      {/if}
    </div>
  </div>
{/if}