zc2 0.0.52

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
import { useEffect, useRef, useState, type FormEvent } from "react";
import { host, listen, type LoginEvent } from "../lib/agent";
import { Button, Pomegranate } from "../components/ui";
import { exitMessage } from "./Setup";

// The cold-start gate: the first thing a machine with no credentials sees.
// The whole sign-in happens in this app, never in the user's browser:
// - Google: zc starts a device-code sign-in (`zc login --json --no-browser`);
//   the hub's Google sign-in opens in a sheet on this window (auth_sheet.rs)
//   and returns to the device page, where the user approves; zc's poll gets
//   the key and the sheet closes.
// - Email and password: zc gets them on stdin (`zc login --password`), signs
//   in, approves its own device code. The password is never stored.
// Either way zc saves a revocable device key in `$ZAKURO_HOME/credentials`,
// and the app itself never talks to the hub (ADR ZC-0019).

type Phase =
  | { k: "idle" }
  | { k: "busy"; via: "password" | "google" }
  | { k: "sheet" }
  | { k: "done" }
  | { k: "error"; message: string };

export function Login({ onSignedIn }: { onSignedIn: () => void }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [staging, setStaging] = useState(false);
  // Production only, unless this host's GitHub token reads zakuro-ai/zc.
  const [stagingAllowed, setStagingAllowed] = useState(false);
  useEffect(() => {
    host.stagingAllowed().then(setStagingAllowed, () => setStagingAllowed(false));
  }, []);
  const [phase, setPhase] = useState<Phase>({ k: "idle" });
  const done = useRef(false);
  // Which sign-in started zc, read by the `login` listener.
  const phaseRef = useRef<"password" | "google" | null>(null);
  const mac = navigator.userAgent.includes("Mac");

  useEffect(() => {
    let un: (() => void) | undefined;
    let unSheet: (() => void) | undefined;
    const fail = (message: string) => {
      host.closeSigninSheet().catch(() => {});
      setPhase({ k: "error", message });
    };
    listen<LoginEvent>("login", (e) => {
      // Google: zc has a device code; show the hub's sign-in in the sheet.
      if (e.event === "code" && e.url && phaseRef.current === "google") {
        host.openGoogleSignin(e.url).then(
          () => setPhase({ k: "sheet" }),
          (err) => {
            host.cancelLogin().catch(() => {});
            fail(String((err as { message?: string }).message ?? err));
          },
        );
      }
      if (e.event === "error") fail(e.message ?? "Sign-in failed.");
      if (e.event === "signed_in") {
        done.current = true;
        host.closeSigninSheet().catch(() => {});
        setPassword("");
        setPhase({ k: "done" });
        window.setTimeout(onSignedIn, 600);
      }
      if (e.event === "exit" && !done.current) {
        setPhase((p) => (p.k === "busy" || p.k === "sheet" ? { k: "error", message: exitMessage(e) } : p));
      }
    }).then((f) => (un = f));
    // The sheet closed without a sign-in: the user cancelled (1) or it failed (2).
    listen<{ code: number }>("auth-sheet", ({ code }) => {
      if (done.current || code === 0) return;
      host.cancelLogin().catch(() => {});
      setPhase(code === 1 ? { k: "idle" } : { k: "error", message: "The sign-in sheet closed unexpectedly. Try again." });
    }).then((f) => (unSheet = f));
    return () => {
      un?.();
      unSheet?.();
      host.closeSigninSheet().catch(() => {});
      host.cancelLogin().catch(() => {});
    };
  }, [onSignedIn]);

  const submit = (ev: FormEvent) => {
    ev.preventDefault();
    if (!email.trim() || !password) {
      setPhase({ k: "error", message: "Enter your email and password." });
      return;
    }
    done.current = false;
    phaseRef.current = "password";
    setPhase({ k: "busy", via: "password" });
    host.passwordLogin(email.trim(), password, stagingAllowed && staging).catch((e) => setPhase({ k: "error", message: String((e as { message?: string }).message ?? e) }));
  };

  const google = () => {
    done.current = false;
    phaseRef.current = "google";
    setPhase({ k: "busy", via: "google" });
    host.startLogin(stagingAllowed && staging, true).catch((e) => setPhase({ k: "error", message: String((e as { message?: string }).message ?? e) }));
  };

  const busy = phase.k === "busy" || phase.k === "sheet" || phase.k === "done";
  const field = "w-full rounded-md border border-hairline bg-bg px-3 py-2 text-[13px] text-fg outline-none focus:border-wine disabled:opacity-60";

  return (
    <div className="grid h-full place-items-center bg-bg p-6" data-tauri-drag-region>
      <form onSubmit={submit} className="grid w-[380px] max-w-full gap-4 rounded-lg border border-hairline bg-surface px-8 py-9 shadow-overlay">
        <div className="grid justify-items-center gap-2 text-center">
          <Pomegranate className="h-10 w-10 text-wine" />
          <h1 className="m-0 text-[20px] font-semibold">Sign in to Zakuro</h1>
          <p className="m-0 text-[13px] text-fg-dim">Use your Zakuro Hub account to lend this {mac ? "Mac" : "machine"} and run jobs on the mesh.</p>
        </div>

        <Button type="button" className="w-full justify-center gap-2 py-2" disabled={busy} onClick={google}>
          <GoogleMark />
          {phase.k === "busy" && phase.via === "google" ? "Opening Google…" : phase.k === "sheet" ? "Finish in the sign-in sheet…" : "Continue with Google"}
        </Button>
        {phase.k === "sheet" && (
          <p className="m-0 -mt-2 text-center text-[11.5px] text-fg-dim">Pick your Google account, then approve this device on the hub page.</p>
        )}

        <div className="flex items-center gap-2 text-[11px] text-fg-dim" aria-hidden="true">
          <span className="h-px flex-1 bg-hairline" />
          or with email
          <span className="h-px flex-1 bg-hairline" />
        </div>

        <label className="grid gap-1 text-[12px] text-fg-dim">
          Email
          <input className={field} type="email" autoComplete="username" value={email} disabled={busy} onChange={(e) => setEmail(e.target.value)} />
        </label>
        <label className="grid gap-1 text-[12px] text-fg-dim">
          Password
          <input className={field} type="password" autoComplete="current-password" value={password} disabled={busy} onChange={(e) => setPassword(e.target.value)} />
        </label>

        {phase.k === "error" && (
          <p role="alert" className="m-0 text-[12.5px] text-wine-bright">
            {phase.message}
          </p>
        )}
        {phase.k === "done" && <p className="m-0 text-[13px] text-live">✓ Signed in. Starting Zakuro…</p>}

        <Button type="submit" variant="primary" className="w-full justify-center" disabled={busy}>
          {phase.k === "busy" && phase.via === "password" ? "Signing in…" : "Sign in"}
        </Button>

        {stagingAllowed && (
        <div className="flex items-center justify-center gap-1 text-[11.5px] text-fg-dim">
          Hub:
          {([false, true] as const).map((s) => (
            <button
              key={String(s)}
              type="button"
              disabled={busy}
              onClick={() => setStaging(s)}
              aria-pressed={staging === s}
              className={"rounded-sm px-1.5 py-0.5 " + (staging === s ? "bg-wine/10 font-semibold text-wine-bright" : "hover:bg-raised")}
            >
              {s ? "Staging" : "Production"}
            </button>
          ))}
        </div>
        )}
      </form>
    </div>
  );
}

/** Google's "G", in its brand colours (sign-in button guidelines). */
function GoogleMark() {
  return (
    <svg viewBox="0 0 48 48" className="h-4 w-4" aria-hidden="true">
      <path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z" />
      <path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z" />
      <path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z" />
      <path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z" />
    </svg>
  );
}