iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / src / connected.tsmain at aacbc74

// connected.ts — A CONNECT THAT ENDED, AS THE WIZARD TAB SEES IT. The Cloud has no access to the
// mind, so it cannot see the mind's ChatGPT secret. When `iterate chatgpt connect` has stored it,
// the CLI sends the person's browser to `/connected?ai=chatgpt&domain=<the mind>`
// (core/lib/src/cli/chatgpt.ts). That page records the end in this origin's localStorage, and an
// open wizard tab hears it through the `storage` event, with no reload.
// Anyone can open /connected by hand and it grants nothing: the worst case is a wizard tab that says "connected" too early.
import { useSyncExternalStore } from "react";
import { z } from "zod";

const KEY = "iterate-cloud.connected";
/** A record counts for an hour: a connect takes 15 minutes at most, and a reload keeps it. */
const FRESH_MS = 60 * 60_000;
const Record = z.object({ ai: z.literal("chatgpt"), domain: z.string(), at: z.number() });
export type ConnectedAi = z.infer<typeof Record>["ai"];

/** What the `/connected` page records, or null for a link that names no AI or no domain. */
export function connectedOf(params: URLSearchParams): { ai: ConnectedAi; domain: string } | null {
  const parsed = Record.omit({ at: true }).safeParse({
    ai: params.get("ai"),
    domain: params.get("domain")?.trim().toLowerCase(),
  });
  return parsed.success && /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(parsed.data.domain)
    ? parsed.data
    : null;
}

export function recordConnected(ai: ConnectedAi, domain: string) {
  try {
    // `at` changes the value each time, so every open tab hears each connect
    localStorage.setItem(KEY, JSON.stringify({ ai, domain, at: Date.now() }));
  } catch {
    /* no storage (a private window): the wizard tab keeps its plain Continue */
  }
}

const read = () => {
  try {
    return localStorage.getItem(KEY);
  } catch {
    return null;
  }
};
const recordOf = (raw: string | null) => {
  try {
    return Record.safeParse(JSON.parse(raw || "null"));
  } catch {
    return Record.safeParse(null);
  }
};
const listen = (changed: () => void) => {
  const heard = (event: StorageEvent) => event.key === KEY && changed();
  addEventListener("storage", heard);
  return () => removeEventListener("storage", heard);
};

/** True once a connect of `ai` ended for the mind at `domain` (the CLI may name it
 *  `iterate.<domain>`), in this browser, within the hour. */
export function useConnected(ai: ConnectedAi, domain: string): boolean {
  const raw = useSyncExternalStore(listen, read, () => null);
  const parsed = recordOf(raw);
  if (!parsed.success) return false;
  const { data } = parsed;
  return (
    data.ai === ai &&
    (data.domain === domain || data.domain === `iterate.${domain}`) &&
    Date.now() - data.at < FRESH_MS
  );
}