aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/Toggle.svelte
blob: 0bc319ab25e6f5eadeb5c17fc8c06240c1161141 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
  let { id, value = $bindable() } = $props();
</script>

<label for={id} class="inline-flex relative items-center mr-5 cursor-pointer">
  <input
    type="checkbox"
    bind:checked={value}
    {id}
    name={id}
    class="sr-only peer"
  />
  <div
    class="w-11 h-6 bg-gray-200 rounded-full peer dark:bg-gray-700 peer-focus:ring-4 peer-focus:ring-gray-300 dark:peer-focus:ring-gray-800 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-0.5 after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-green-500"
></div>
</label>
.PreprocFile */ .highlight .c1 { color: #888 } /* Comment.Single */ .highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */ .highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */ .highlight .gr { color: #A00 } /* Generic.Error */ .highlight .gh { color: #333 } /* Generic.Heading */ .highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */ .highlight .go { color: #888 } /* Generic.Output */ .highlight .gp { color: #555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666 } /* Generic.Subheading */ .highlight .gt { color: #A00 } /* Generic.Traceback */ .highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #080 } /* Keyword.Pseudo */ .highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #00D; font-weight: bold } /* Literal.Number */ .highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */ .highlight .na { color: #369 } /* Name.Attribute */ .highlight .nb { color: #038 } /* Name.Builtin */ .highlight .nc { color: #B06; font-weight: bold } /* Name.Class */ .highlight .no { color: #036; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555 } /* Name.Decorator */ .highlight .ne { color: #B06; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #06B; font-weight: bold } /* Name.Function */ .highlight .nl { color: #369; font-style: italic } /* Name.Label */ .highlight .nn { color: #B06; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #369; font-weight: bold } /* Name.Property */ .highlight .nt { color: #B06; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #369 } /* Name.Variable */ .highlight .ow { color: #080 } /* Operator.Word */ .highlight .w { color: #BBB } /* Text.Whitespace */ .highlight .mb { color: #00D; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #00D; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #00D; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #00D; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #00D; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #D20; background-color: #FFF0F0 } /* Literal.String.Affix */ .highlight .sb { color: #D20; background-color: #FFF0F0 } /* Literal.String.Backtick */ .highlight .sc { color: #D20; background-color: #FFF0F0 } /* Literal.String.Char */ .highlight .dl { color: #D20; background-color: #FFF0F0 } /* Literal.String.Delimiter */ .highlight .sd { color: #D20; background-color: #FFF0F0 } /* Literal.String.Doc */ .highlight .s2 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Double */ .highlight .se { color: #04D; background-color: #FFF0F0 } /* Literal.String.Escape */ .highlight .sh { color: #D20; background-color: #FFF0F0 } /* Literal.String.Heredoc */ .highlight .si { color: #33B; background-color: #FFF0F0 } /* Literal.String.Interpol */ .highlight .sx { color: #2B2; background-color: #F0FFF0 } /* Literal.String.Other */ .highlight .sr { color: #080; background-color: #FFF0FF } /* Literal.String.Regex */ .highlight .s1 { color: #D20; background-color: #FFF0F0 } /* Literal.String.Single */ .highlight .ss { color: #A60; background-color: #FFF0F0 } /* Literal.String.Symbol */ .highlight .bp { color: #038 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #06B; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #369 } /* Name.Variable.Class */ .highlight .vg { color: #D70 } /* Name.Variable.Global */ .highlight .vi { color: #33B } /* Name.Variable.Instance */ .highlight .vm { color: #369 } /* Name.Variable.Magic */ .highlight .il { color: #00D; font-weight: bold } /* Literal.Number.Integer.Long */
<script lang="ts">
  import { onMount } from "svelte";
  import { browser } from "$app/environment";
  import { t } from "$lib/translations";
  import PasswordInput from "$comp/PasswordInput.svelte";
  import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";

  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 = undefined }: any = $props();
  let extensionAvailable = $derived(browser && window.nostr);

  let cancel = () => {
    eventToSign.set(undefined);
    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: string | undefined = $state();
  let nostrConnect = async () => {
    const { Relay } = await import("nostr-tools/relay");
    const { nip04, generateSecretKey, getPublicKey } = await import("nostr-tools");
    const { getConversationKey, decrypt } = await import("nostr-tools/nip44");
    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: string = $state("");
  let showNsec = $state();
  let toggleNsec = () => {
    $signer = {
      method: "nsec",
    };
  };

  let nsecSign = async () => {
    const { nip19, getPublicKey } = await import("nostr-tools");
    let sk: Uint8Array;
    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 as any).params.sig = sig;
    ($signer as any).ready = true;
    $signer = $signer;
  };

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

{#if $eventToSign && !$signer?.ready}
  <div class="fixed inset-0 bg-base-100/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 as any).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}