Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

9.2 KB
Raw Blame
/**
 * Desktop mode (ADELIE_DESKTOP_TOKEN, or the pre-rename PENGUIN_DESKTOP_TOKEN the shell still
 * exports): the shell that spawned this server proves itself
 * with a per-launch random token, which backs two endpoints with different consumption
 * rules:
 *
 * - `GET /api/auth/claim?token=…` — ONE-SHOT: the window's first navigation
 *   redeems the token for a standard admin cookie session; every later attempt fails,
 *   so a leaked URL cannot be replayed.
 * - `POST /api/desktop/shutdown` (Authorization: Bearer <token>) — REUSABLE for the
 *   process lifetime: the token here identifies the supervising shell, which may need
 *   the endpoint at any point (POSIX quit, and the only graceful path on Windows,
 *   where killing a child is a hard TerminateProcess).
 *
 * Comparisons hash both sides first so timingSafeEqual gets equal-length buffers.
 *
 * The service is also the shell↔web relay for the surfaces the shell owns: client updates, the
 * tray icon, the pet window and the Windows login item. In both directions it is the same
 * utilityProcess message channel (index.ts wires the port) — the shell pushes its current state,
 * the web reads it at GET /api/desktop/update, /api/desktop/tray, /api/desktop/pet or
 * /api/desktop/login-item and writes back a command that
 * is forwarded to the shell. The window itself stays a plain browser — every capability flows
 * through this HTTP surface, never a renderer IPC bridge.
 *
 * The same channel carries the Workspace picker's macOS folder access: a request the shell
 * answers (its main process reads a folder in the app's own name), and a command that opens
 * System Settings at a privacy pane.
 */
import { createHash, timingSafeEqual } from "node:crypto";
import type {
  DesktopFolderAccessResult,
  DesktopLoginItemPatch,
  DesktopLoginItemStatus,
  DesktopPetPatch,
  DesktopPetStatus,
  DesktopPrivacyPane,
  DesktopTrayPatch,
  DesktopTrayStatus,
  DesktopUpdateStatus,
  DesktopUpdaterCommandMessage,
} from "../api/types.js";

/** What the page may ask the shell's updater to do (the relayed command's `action`). */
export type UpdaterCommand = DesktopUpdaterCommandMessage["action"];

function digest(value: string): Buffer {
  return createHash("sha256").update(value).digest();
}

export class DesktopService {
  private readonly tokenDigest: Buffer;
  private loginConsumed = false;
  private shutdownHandler: (() => void) | null = null;

  constructor(token: string) {
    this.tokenDigest = digest(token);
  }

  /** Constant-time token check (no consumption). */
  verifyToken(candidate: string): boolean {
    return timingSafeEqual(digest(candidate), this.tokenDigest);
  }

  /** One-shot login redemption: true exactly once, for the correct token. */
  redeemLoginToken(candidate: string): boolean {
    if (this.loginConsumed || !this.verifyToken(candidate)) return false;
    this.loginConsumed = true;
    return true;
  }

  /** index.ts registers the actual graceful-shutdown trigger after assembly. */
  onShutdownRequest(handler: () => void): void {
    this.shutdownHandler = handler;
  }

  /** Invoked by the shutdown route; false when no handler is registered (tests). */
  requestShutdown(): boolean {
    if (!this.shutdownHandler) return false;
    this.shutdownHandler();
    return true;
  }

  // --- client-update relay ---------------------------------------------------

  private updateStatus: DesktopUpdateStatus | null = null;
  private updateCommandSender: ((action: UpdaterCommand) => void) | null = null;

  /** Latest shell snapshot; null until the shell's first push lands. */
  getUpdateStatus(): DesktopUpdateStatus | null {
    return this.updateStatus;
  }

  /** index.ts stores each shell push here (already validated at the message port). */
  setUpdateStatus(status: DesktopUpdateStatus): void {
    this.updateStatus = status;
  }

  /** index.ts registers the message-port sender; absent outside a shell-forked process. */
  onUpdateCommand(sender: (action: UpdaterCommand) => void): void {
    this.updateCommandSender = sender;
  }

  /** Invoked by the update routes; false when no shell port is wired (tests, plain runs). */
  requestUpdateCommand(action: UpdaterCommand): boolean {
    if (!this.updateCommandSender) return false;
    this.updateCommandSender(action);
    return true;
  }

  // --- tray-icon relay -------------------------------------------------------

  private trayStatus: DesktopTrayStatus | null = null;
  private trayCommandSender: ((patch: DesktopTrayPatch) => void) | null = null;

  /** Latest shell push; null until the shell's first one lands (the page then reads it as on). */
  getTrayStatus(): DesktopTrayStatus | null {
    return this.trayStatus;
  }

  /** index.ts stores each shell push here (already validated at the message port). */
  setTrayStatus(status: DesktopTrayStatus): void {
    this.trayStatus = status;
  }

  /** index.ts registers the message-port sender; absent outside a shell-forked process. */
  onTrayCommand(sender: (patch: DesktopTrayPatch) => void): void {
    this.trayCommandSender = sender;
  }

  /** Invoked by the tray route; false when no shell port is wired (tests, plain runs). */
  requestTrayCommand(patch: DesktopTrayPatch): boolean {
    if (!this.trayCommandSender) return false;
    this.trayCommandSender(patch);
    return true;
  }

  // --- pet-window relay ------------------------------------------------------

  private petStatus: DesktopPetStatus | null = null;
  private petCommandSender: ((patch: DesktopPetPatch) => void) | null = null;

  /** Latest shell push; null until the shell's first one lands (the page then reads it as off). */
  getPetStatus(): DesktopPetStatus | null {
    return this.petStatus;
  }

  /** index.ts stores each shell push here (already validated at the message port). */
  setPetStatus(status: DesktopPetStatus): void {
    this.petStatus = status;
  }

  /** index.ts registers the message-port sender; absent outside a shell-forked process. */
  onPetCommand(sender: (patch: DesktopPetPatch) => void): void {
    this.petCommandSender = sender;
  }

  /** Invoked by the pet route; false when no shell port is wired (tests, plain runs). */
  requestPetCommand(patch: DesktopPetPatch): boolean {
    if (!this.petCommandSender) return false;
    this.petCommandSender(patch);
    return true;
  }

  // --- login-item relay (Windows) --------------------------------------------

  private loginItemStatus: DesktopLoginItemStatus | null = null;
  private loginItemCommandSender: ((patch: DesktopLoginItemPatch) => void) | null = null;

  /**
   * What Windows currently says about starting the app when the user signs in; null until the
   * shell's first push lands. Where the tray and the pet fall back to their own defaults, this one
   * has none to fall back to and does not invent one: the state belongs to the operating system,
   * and the page draws its row only for a status a shell has actually confirmed `supported`. An
   * absent status is therefore rendered as no row at all rather than as a wrong switch.
   */
  getLoginItemStatus(): DesktopLoginItemStatus | null {
    return this.loginItemStatus;
  }

  /** index.ts stores each shell push here (already validated at the message port). */
  setLoginItemStatus(status: DesktopLoginItemStatus): void {
    this.loginItemStatus = status;
  }

  /** index.ts registers the message-port sender; absent outside a shell-forked process. */
  onLoginItemCommand(sender: (patch: DesktopLoginItemPatch) => void): void {
    this.loginItemCommandSender = sender;
  }

  /** Invoked by the login-item route; false when no shell port is wired (tests, plain runs). */
  requestLoginItemCommand(patch: DesktopLoginItemPatch): boolean {
    if (!this.loginItemCommandSender) return false;
    this.loginItemCommandSender(patch);
    return true;
  }

  // --- macOS folder-access relay ----------------------------------------------

  private folderAccessSender: FolderAccessSender | null = null;
  private privacySettingsSender: ((pane: DesktopPrivacyPane) => void) | null = null;

  /** index.ts registers the message-port request; absent outside a shell-forked process. */
  onFolderAccessRequest(sender: FolderAccessSender): void {
    this.folderAccessSender = sender;
  }

  /**
   * Invoked by the dirs access route: has the shell read `path` in the app's own name. Null
   * when no shell port is wired (tests, plain runs); the promise resolves null when the shell
   * does not answer in time.
   */
  requestFolderAccess(path: string): Promise<DesktopFolderAccessResult | null> | null {
    return this.folderAccessSender?.(path) ?? null;
  }

  /** index.ts registers the message-port sender; absent outside a shell-forked process. */
  onPrivacySettingsCommand(sender: (pane: DesktopPrivacyPane) => void): void {
    this.privacySettingsSender = sender;
  }

  /** Invoked by the privacy-settings route; false when no shell port is wired (tests, plain runs). */
  requestPrivacySettings(pane: DesktopPrivacyPane): boolean {
    if (!this.privacySettingsSender) return false;
    this.privacySettingsSender(pane);
    return true;
  }
}

/** Asks the shell to read one folder; resolves with its answer, or null when none came in time. */
export type FolderAccessSender = (path: string) => Promise<DesktopFolderAccessResult | null>;