Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

10.0 KB
Raw Blame
import {
  PLUGIN_OAUTH_TTL_MS,
  oauthExact,
  oauthId,
  oauthPublicKey,
  parsePluginSecretOffer,
  parsePluginSecretInput,
  parsePluginConnectionOffer,
  parsePluginConnectionInput,
  parsePluginAuthorizationOffer,
  parsePluginAuthorizationRequest,
  type PluginOauthCallback,
  parsePluginDeviceOffer,
  parseInputHandoffOffer,
  parseInputHandoffPresentation,
  parseInputHandoffValueReply,
  type InputHandoffPicture,
  type InputHandoffPresentation,
  type InputHandoffSubmission,
  type PluginOauthRequest,
  type PluginOauthAction,
  type PluginSecretPresentation,
  type PluginConnectionPresentation,
} from "@cindy/device-link";
import { MobileOauthBox, type PluginOauthCrypto } from "./pluginOauthCrypto";
const object = (v: unknown): Record<string, unknown> => {
  if (!v || typeof v !== "object" || Array.isArray(v))
    throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
  return v as Record<string, unknown>;
};
/** Presentation/inputs remain in a dedicated native form. The execution Host owns exchange, vault save and result. */
export async function runMobilePluginAuthorization(deps: {
  crypto: PluginOauthCrypto;
  invoke(request: PluginOauthRequest): Promise<unknown>;
  action: PluginOauthAction;
  kind: "oauth" | "secret" | "connection" | "input";
  secretPresentation?: PluginSecretPresentation;
  /** 代输入: the exact step the owner answered, and the answer. */
  inputPresentation?: InputHandoffPresentation;
  inputSubmission?: InputHandoffSubmission;
  /** 代输入 screenshot step: show the sealed picture, then return the owner's tap or typing. */
  inputPicture?(picture: InputHandoffPicture): Promise<InputHandoffSubmission>;
  connectionPresentation?: PluginConnectionPresentation;
  inputSecret?: string;
  inputConnection?: { host: string; token: string };
  showAuthorization(
    url: string,
    code: string | undefined,
    expiresAt: number,
  ): Promise<void>;
  receiveLoopback?(request: { url: string; callbackUrl: string; state: string }, expiresAt: number, signal: AbortSignal): Promise<PluginOauthCallback>;
  clearInput(): void;
  assertCurrent(): void;
  pause(): Promise<void>;
  isForeground?(): boolean;
  now?(): number;
}): Promise<void> {
  const now = deps.now ?? Date.now,
    deadline = now() + PLUGIN_OAUTH_TTL_MS,
    key = new MobileOauthBox(deps.crypto);
  let id: string | undefined,
    finished = false;
  try {
    deps.assertCurrent();
    const caps = object(await deps.invoke({ op: "capabilities" }));
    if (
      caps.version !== 1 ||
      caps.encrypted !== true ||
      caps.callback !== "desktop-loopback" ||
      (deps.kind === "secret" && caps.secretSubmission !== true) ||
      (deps.kind === "connection" && caps.connectionSubmission !== true) ||
      (deps.kind === "input" && caps.inputHandoff !== true)
    )
      throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
    deps.assertCurrent();
    const start = object(
      await deps.invoke({
        op: "start",
        ...deps.action,
        publicKey: key.publicKey,
        ...(caps.deviceUserCode === true
          ? { deviceUserCode: true as const }
          : {}),
        ...(caps.authorizationV1 === true
          ? { authorizationV1: true as const }
          : {}),
        ...(deps.kind === "secret" ? { secretSubmission: true as const } : {}),
        ...(deps.kind === "connection"
          ? { connectionSubmission: true as const }
          : {}),
        ...(deps.kind === "input" ? { inputHandoff: true as const } : {}),
      }),
    );
    if (!oauthId(start.id) || !oauthPublicKey(start.publicKey))
      throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
    id = start.id;
    const peerKey = start.publicKey;
    let opened = false;
    const deliver = async (value: unknown) => {
      deps.assertCurrent();
      const box = await key.seal(peerKey, id!, "callback", value);
      deps.clearInput();
      deps.inputSecret = undefined;
      deps.inputConnection = undefined;
      deps.inputSubmission = undefined;
      deps.assertCurrent();
      const result = object(
        await deps.invoke({ op: "callback", id: id!, box }),
      );
      if (result.accepted !== true) throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
    };
    const receiveLoopback = async (request: { url: string; callbackUrl: string; state: string }) => {
      if (!deps.receiveLoopback) throw new Error("PLUGIN_OAUTH_UPDATE_REQUIRED");
      const abort = new AbortController();
      let checking = false;
      const monitor = setInterval(() => {
        if (checking || deps.isForeground?.() === false) return;
        checking = true;
        void (async () => {
          try {
            deps.assertCurrent();
            const status = object(await deps.invoke({ op: "status", id: id! }));
            deps.assertCurrent();
            if (!["authorizing", "starting"].includes(String(status.phase))) abort.abort();
          } catch { if (deps.isForeground?.() !== false) abort.abort(); }
          finally { checking = false; }
        })();
      }, 600);
      try {
        const value = await deps.receiveLoopback(request, deadline, abort.signal);
        while (deps.isForeground?.() === false) {
          deps.assertCurrent();
          if (now() >= deadline) throw new Error("PLUGIN_OAUTH_CLOSED");
          await new Promise((resolve) => setTimeout(resolve, 200));
        }
        deps.assertCurrent();
        if (now() >= deadline) throw new Error("PLUGIN_OAUTH_CLOSED");
        return value;
      } finally { clearInterval(monitor); abort.abort(); }
    };
    while (now() < deadline) {
      await deps.pause();
      deps.assertCurrent();
      const status = object(await deps.invoke({ op: "status", id }));
      deps.assertCurrent();
      if (status.phase === "succeeded") {
        finished = true;
        return;
      }
      if (
        !["starting", "authorizing", "exchanging"].includes(
          String(status.phase),
        )
      )
        throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
      if (status.phase !== "authorizing" || opened) continue;
      if (typeof status.offer !== "string")
        throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
      const raw = object(await key.open(peerKey, id, "offer", status.offer));
      if (deps.kind === "input") {
        if (
          raw.kind !== "input-entry" ||
          !deps.inputPresentation ||
          (!deps.inputSubmission && !deps.inputPicture)
        )
          throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
        const offer = parseInputHandoffOffer(raw);
        // The owner answered exactly this step; anything else is a newer screen.
        if (
          JSON.stringify(offer.presentation) !==
          JSON.stringify(parseInputHandoffPresentation(deps.inputPresentation))
        )
          throw new Error("INPUT_HANDOFF_STALE");
        if (offer.picture) {
          // Only a caller that asked for this step's picture receives it; a prepared form answer never does.
          if (!deps.inputPicture || deps.inputSubmission)
            throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
          deps.inputSubmission = await deps.inputPicture(offer.picture);
          deps.assertCurrent();
        }
        await deliver(
          parseInputHandoffValueReply({
            kind: "input-value",
            state: offer.state,
            submission: deps.inputSubmission,
          }),
        );
      } else if (deps.kind === "secret") {
        const offer = parsePluginSecretOffer(raw);
        if (
          JSON.stringify(offer.presentation) !==
          JSON.stringify(deps.secretPresentation)
        )
          throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
        const value = parsePluginSecretInput(deps.inputSecret);
        if (value.length > offer.presentation.maxLength)
          throw new Error("PLUGIN_SECRET_UNAVAILABLE");
        await deliver({ kind: "secret-value", state: offer.state, value });
      } else if (deps.kind === "connection") {
        const offer = parsePluginConnectionOffer(raw);
        if (
          JSON.stringify(offer.presentation) !==
          JSON.stringify(deps.connectionPresentation)
        )
          throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
        await deliver({
          kind: "connection-value",
          state: offer.state,
          value: parsePluginConnectionInput(deps.inputConnection),
        });
      } else if (raw.kind === "authorization") {
        if (caps.authorizationV1 !== true)
          throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
        const offer = parsePluginAuthorizationOffer(raw);
        if (offer.request.kind === "loopback") {
          const value = await receiveLoopback(offer.request);
          await deliver({ ...value, state: offer.state });
          opened = true;
          continue;
        }
        await deps.showAuthorization(
          offer.request.url,
          offer.request.kind === "device" ? offer.request.userCode : undefined,
          Math.min(deadline, offer.request.expiresAt ?? deadline),
        );
        await deliver({ kind: "device-opened", state: offer.state });
      } else if (raw.kind === "device") {
        if (caps.deviceAuthorization !== true)
          throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
        const offer = parsePluginDeviceOffer(raw);
        await deps.showAuthorization(
          offer.authorizeUrl,
          offer.userCode,
          deadline,
        );
        await deliver({ kind: "device-opened", state: offer.state });
      } else {
        oauthExact(raw, [
          "authorizeUrl",
          "callbackUrl",
          "corsHosts",
          "corsOrigins",
          "state",
        ]);
        const request = parsePluginAuthorizationRequest({ kind: "loopback", url: raw.authorizeUrl, callbackUrl: raw.callbackUrl, state: raw.state });
        if (request.kind !== "loopback") throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
        await deliver(await receiveLoopback(request));
      }
      opened = true;
    }
    throw new Error("OAUTH_BRIDGE_UNAVAILABLE");
  } finally {
    deps.clearInput();
    deps.inputSecret = undefined;
    deps.inputConnection = undefined;
    deps.inputSubmission = undefined;
    if (!finished && id)
      await deps.invoke({ op: "cancel", id }).catch(() => {});
    key.dispose();
  }
}