Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

7.2 KB
Raw Blame
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";

import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import * as DesktopSavedEnvironments from "../settings/DesktopSavedEnvironments.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import {
  DesktopConnectionCatalogStoreReadError,
  DesktopConnectionCatalogStoreDocumentDecodeError,
  DesktopConnectionCatalogStoreDecodeError,
  DesktopConnectionCatalogStoreMigrationError,
  DesktopConnectionCatalogStoreProtectionError,
  DesktopConnectionCatalogStoreWriteError,
  writeDocument,
  encodeRuntimeConnectionCatalogDocumentJson,
  readDocument,
} from "./ConnectionCatalogDocument.ts";
import { migrateSavedEnvironmentRecords } from "./LegacyConnectionCatalogMigration.ts";

export { DesktopConnectionCatalogStoreWriteError } from "./ConnectionCatalogDocument.ts";

export { DesktopConnectionCatalogStoreDecodeError } from "./ConnectionCatalogDocument.ts";

export { DesktopConnectionCatalogStoreReadError } from "./ConnectionCatalogDocument.ts";

export { DesktopConnectionCatalogStoreDocumentDecodeError } from "./ConnectionCatalogDocument.ts";

export { DesktopConnectionCatalogStoreMigrationError } from "./ConnectionCatalogDocument.ts";

export { DesktopConnectionCatalogStoreProtectionError } from "./ConnectionCatalogDocument.ts";

export class DesktopConnectionCatalogStore extends Context.Service<
  DesktopConnectionCatalogStore,
  {
    readonly get: Effect.Effect<
      Option.Option<string>,
      | DesktopConnectionCatalogStoreReadError
      | DesktopConnectionCatalogStoreDocumentDecodeError
      | DesktopConnectionCatalogStoreDecodeError
      | DesktopConnectionCatalogStoreMigrationError
      | DesktopConnectionCatalogStoreProtectionError
    >;
    readonly set: (
      catalog: string,
    ) => Effect.Effect<
      boolean,
      DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
    >;
    readonly clear: Effect.Effect<void>;
  }
>()("@akeru/desktop/app/DesktopConnectionCatalogStore") {}

function decodeSecretBytes(
  catalogPath: string,
  encoded: string,
): Effect.Effect<Uint8Array, DesktopConnectionCatalogStoreDecodeError> {
  return Effect.fromResult(Encoding.decodeBase64(encoded)).pipe(
    Effect.mapError(
      (cause) =>
        new DesktopConnectionCatalogStoreDecodeError({
          resource: "encryptedCatalog",
          catalogPath,
          cause,
        }),
    ),
  );
}

export const make = Effect.gen(function* () {
  const environment = yield* DesktopEnvironment.DesktopEnvironment;
  const fileSystem = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
  const crypto = yield* Crypto.Crypto;
  const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
  const catalogPath = path.join(environment.stateDir, "connection-catalog.json");

  const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
    Effect.mapError(
      (cause) =>
        new DesktopConnectionCatalogStoreProtectionError({
          operation: "check-encryption-availability",
          catalogPath,
          cause,
        }),
    ),
  );

  const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
    catalog: string,
  ) {
    const encryptedCatalog = Encoding.encodeBase64(
      yield* safeStorage.encryptString(catalog).pipe(
        Effect.mapError(
          (cause) =>
            new DesktopConnectionCatalogStoreProtectionError({
              operation: "encrypt-catalog",
              catalogPath,
              cause,
            }),
        ),
      ),
    );

    const suffix = (yield* crypto.randomUUIDv4.pipe(
      Effect.mapError(
        (cause) =>
          new DesktopConnectionCatalogStoreWriteError({
            operation: "create-temporary-file-name",
            path: catalogPath,
            cause,
          }),
      ),
    )).replace(/-/g, "");

    yield* writeDocument({
      fileSystem,
      path,
      catalogPath,
      document: { version: 1, encryptedCatalog },
      suffix,
    });
  });

  const migrateLegacyCatalog = Effect.gen(function* () {
    const records = yield* savedEnvironments.getRegistry.pipe(
      Effect.mapError(
        (cause) =>
          new DesktopConnectionCatalogStoreMigrationError({
            operation: "read-legacy-registry",
            catalogPath,
            cause,
          }),
      ),
    );

    if (records.length === 0) {
      return Option.none<string>();
    }

    // A brand-new install has no catalog and no legacy records. Do not touch
    // Electron safe storage in that case: on macOS the availability check can
    // open the keychain prompt even though there is nothing to decrypt.
    if (!(yield* encryptionAvailable)) {
      return Option.none<string>();
    }

    const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);

    const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
      Effect.mapError(
        (cause) =>
          new DesktopConnectionCatalogStoreMigrationError({
            operation: "encode-catalog",
            catalogPath,
            cause,
          }),
      ),
    );

    yield* writeCatalog(encoded).pipe(
      Effect.mapError(
        (cause) =>
          new DesktopConnectionCatalogStoreMigrationError({
            operation: "persist-catalog",
            catalogPath,
            cause,
          }),
      ),
    );

    return Option.some(encoded);
  });

  return DesktopConnectionCatalogStore.of({
    get: Effect.gen(function* () {
      const document = yield* readDocument(fileSystem, catalogPath);

      if (Option.isNone(document)) {
        return yield* migrateLegacyCatalog;
      }

      if (!(yield* encryptionAvailable)) {
        return Option.none<string>();
      }

      const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
        Effect.flatMap((encryptedCatalog) =>
          safeStorage.decryptString(encryptedCatalog).pipe(
            Effect.mapError(
              (cause) =>
                new DesktopConnectionCatalogStoreProtectionError({
                  operation: "decrypt-catalog",
                  catalogPath,
                  cause,
                }),
            ),
          ),
        ),
      );

      return Option.some(decrypted);
    }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
    set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
      if (!(yield* encryptionAvailable)) {
        return false;
      }

      yield* writeCatalog(catalog);

      return true;
    }),
    clear: fileSystem.remove(catalogPath, { force: true }).pipe(
      Effect.catch((error) =>
        Effect.logWarning("Could not clear the desktop connection catalog.", {
          catalogPath,
          error,
        }),
      ),
      Effect.withSpan("desktop.connectionCatalogStore.clear"),
    ),
  });
});

export const layer = Layer.effect(DesktopConnectionCatalogStore, make);