Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

18.1 KB
Raw Blame
// No answer ever carries a password, a 2FA key or the token: a saved secret is only ever replaced.
import { LOGIN_FIELD_MAX, loginPlace, normalizeLoginHost, type BitwardenCredentials, type BitwardenSecretsCredentials, type BitwardenSecretsStatus, type BitwardenStatus, type LoginBots, type LoginSummary, type OnePasswordStatus } from "../../shared/logins.ts";
import { parseAccessToken } from "../host/bitwarden-secrets-api.ts";
import { bitwardenServerUrl } from "../host/bitwarden-vault.ts";
import type { LoginPatch, NewLogin } from "../vault-store.ts";
import { parseTotpKey, type TotpKey } from "../totp.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";

export interface LoginRouteDeps {
  list(): LoginSummary[];
  create(input: NewLogin): LoginSummary;
  update(id: string, patch: LoginPatch): LoginSummary | null | "taken";
  remove(id: string): boolean;
  botExists(id: string): boolean;
  onePassword: {
    status(): OnePasswordStatus;
    list(): LoginSummary[];
    connect(token: string): Promise<OnePasswordStatus>;
    refresh(): Promise<OnePasswordStatus>;
    disconnect(): OnePasswordStatus;
    /** Null for a vault the token does not read. */
    grant(vaultId: string, bots: LoginBots): OnePasswordStatus | null;
    /** Bots for one item (`<vault id>:<item id>`) ahead of its vault's; null hands it back. False for an item the token does not
     * read, null when 1Password could not be read just now. */
    grantItem(item: string, bots: LoginBots | null): Promise<boolean | null>;
    /** Every item's own bots at once (what My Cloud keeps of another computer's choices); an item left out goes back to its vault's,
     * unless `keep` leaves the items not named as they are. */
    setItemGrants(grants: Record<string, LoginBots>, keep?: boolean): void;
  };
  /** Absent where Bitwarden is not offered. */
  bitwarden?: {
    status(): BitwardenStatus;
    list(): LoginSummary[];
    /** Rejects with words for the person when Bitwarden refuses them; nothing is kept then. */
    connect(credentials: BitwardenCredentials): Promise<BitwardenStatus>;
    refresh(): Promise<BitwardenStatus>;
    disconnect(): Promise<BitwardenStatus>;
  };
  /** Absent where Bitwarden Secrets Manager is not offered. */
  bitwardenSecrets?: {
    status(): BitwardenSecretsStatus;
    list(): LoginSummary[];
    /** Rejects with words for the person when Bitwarden refuses the token; nothing is kept then. */
    connect(credentials: BitwardenSecretsCredentials): Promise<BitwardenSecretsStatus>;
    refresh(): Promise<BitwardenSecretsStatus>;
    disconnect(): BitwardenSecretsStatus;
  };
}

const BITWARDEN = "/api/logins/bitwarden";

/** What an admin pastes to connect Bitwarden, checked; a message for the first thing that is not right. */
export function parseBitwardenCredentials(body: unknown): { ok: true; value: BitwardenCredentials } | { ok: false; error: string } {
  const field = (name: string) => (body && typeof body === "object" && typeof (body as Record<string, unknown>)[name] === "string" ? ((body as Record<string, string>)[name]).trim() : "");
  const serverUrl = bitwardenServerUrl(field("serverUrl"));
  if (!serverUrl) return { ok: false, error: LOGIN_ERRORS.bitwardenServer };
  const clientId = field("clientId"), clientSecret = field("clientSecret");
  if (!/^user\.[\w-]{1,100}$/u.test(clientId)) return { ok: false, error: LOGIN_ERRORS.bitwardenClientId };
  if (!clientSecret || clientSecret.length > 256 || /\s/u.test(clientSecret)) return { ok: false, error: LOGIN_ERRORS.bitwardenClientSecret };
  const password = body && typeof body === "object" && typeof (body as Record<string, unknown>).password === "string" ? (body as Record<string, string>).password : "";
  if (!password || password.length > 1024) return { ok: false, error: LOGIN_ERRORS.bitwardenPassword };
  return { ok: true, value: { serverUrl, clientId, clientSecret, password } };
}

/** What an admin pastes to connect Bitwarden Secrets Manager, checked; a message for the first thing that is not right. */
export function parseBitwardenSecretsCredentials(body: unknown): { ok: true; value: BitwardenSecretsCredentials } | { ok: false; error: string } {
  const field = (name: string) => (body && typeof body === "object" && typeof (body as Record<string, unknown>)[name] === "string" ? ((body as Record<string, string>)[name]).trim() : "");
  const serverUrl = bitwardenServerUrl(field("serverUrl"));
  if (!serverUrl) return { ok: false, error: LOGIN_ERRORS.bitwardenServer };
  const accessToken = field("accessToken");
  if (!parseAccessToken(accessToken)) return { ok: false, error: LOGIN_ERRORS.bitwardenAccessToken };
  return { ok: true, value: { serverUrl, accessToken } };
}

const BITWARDEN_SECRETS = "/api/logins/bitwarden-secrets";

async function bitwardenSecretsRoute({ req, res, path, method, json, readBody }: RouteContext, deps: LoginRouteDeps["bitwardenSecrets"]): Promise<void> {
  if (!deps) return json(res, 404, { error: "not found" });
  if (path === `${BITWARDEN_SECRETS}/refresh` && method === "POST") return json(res, 200, { bitwardenSecrets: await deps.refresh() });
  if (path === BITWARDEN_SECRETS && method === "DELETE") return json(res, 200, { bitwardenSecrets: deps.disconnect() });
  if (path !== BITWARDEN_SECRETS || method !== "POST") return json(res, 405, { error: "method not allowed" });
  const parsed = parseBitwardenSecretsCredentials(await readBody(req, 16_384));
  if (!parsed.ok) return json(res, 400, { error: parsed.error });
  try { return json(res, 200, { bitwardenSecrets: await deps.connect(parsed.value) }); }
  catch (error) { return json(res, 400, { error: error instanceof Error && error.message ? error.message : LOGIN_ERRORS.bitwardenAccessToken }); }
}

const ONE_PASSWORD = "/api/logins/1password";
const VAULT = /^\/api\/logins\/1password\/vaults\/([\w-]{1,128})$/u;
const ITEMS = "/api/logins/1password/items";
const ITEM = /^\/api\/logins\/1password\/items\/([\w-]{1,128})\/([\w-]{1,128})$/u;
const ITEM_KEY = /^[\w-]{1,128}:[\w-]{1,128}$/u;
const UNREAD = "1Password could not be read just now. Try again in a moment.";

const ID = /^[\w-]{1,128}$/u;

export const LOGIN_ERRORS = {
  site: "Enter the address of the login page, such as accounts.example.com.",
  password: "Enter the password.",
  long: `Usernames and passwords can be at most ${LOGIN_FIELD_MAX} characters.`,
  totp: "That 2FA key is not valid. Paste the setup key (letters A–Z and digits 2–7) or the otpauth:// address from the site's QR code.",
  bots: "Choose every bot, or bots that exist.",
  token: "Paste a 1Password service account token. It starts with ops_.",
  notServiceAccount: "That is not a 1Password service account token: those start with ops_. Make one in 1Password under Developer → Service accounts. A Connect token, an account password or a Secret Key does not work here.",
  exactHost: "exactHost must be true or false.",
  readOnly: "This login is in 1Password. Change or remove it there.",
  taken: "A login with this username is already saved for that site. Change or delete that one instead.",
  bitwardenReadOnly: "This login is in Bitwarden. Change or remove it there.",
  bitwardenServer: "Enter the Bitwarden server's address, starting with https://, such as https://vault.bitwarden.com.",
  bitwardenClientId: "Paste the account's client_id from Bitwarden's Account settings → Security → Keys → View API key. It starts with user.",
  bitwardenClientSecret: "Paste the account's client_secret from the same place, on its own.",
  bitwardenPassword: "Enter the account's master password.",
  bitwardenSecretsReadOnly: "This login is in Bitwarden Secrets Manager. Change or remove it there.",
  bitwardenAccessToken: "Paste a machine account's access token from Bitwarden Secrets Manager → Machine accounts → Access tokens. It starts with 0.",
} as const;

type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };

/** Absent leaves it; "" or null clears it. */
export function parseTotpField(value: unknown): Parsed<TotpKey | null | undefined> {
  if (value === undefined) return { ok: true, value: undefined };
  if (value === null || (typeof value === "string" && !value.trim())) return { ok: true, value: null };
  const key = parseTotpKey(value);
  return key ? { ok: true, value: key } : { ok: false, error: LOGIN_ERRORS.totp };
}

export function parseLoginFields(body: Record<string, unknown>, options: { passwordRequired: boolean }): Parsed<{ username?: string; password?: string }> {
  const username = body.username;
  const password = body.password;
  if (username !== undefined && typeof username !== "string") return { ok: false, error: "username must be text" };
  if (password !== undefined && typeof password !== "string") return { ok: false, error: LOGIN_ERRORS.password };
  if (options.passwordRequired && !password) return { ok: false, error: LOGIN_ERRORS.password };
  if (password !== undefined && !password) return { ok: false, error: LOGIN_ERRORS.password };
  if ((username?.length ?? 0) > LOGIN_FIELD_MAX || (password?.length ?? 0) > LOGIN_FIELD_MAX) return { ok: false, error: LOGIN_ERRORS.long };
  return { ok: true, value: { ...(username === undefined ? {} : { username: username.trim() }), ...(password === undefined ? {} : { password }) } };
}

export function parseBots(value: unknown, exists: (id: string) => boolean): Parsed<LoginBots | undefined> {
  if (value === undefined) return { ok: true, value: undefined };
  if (value === "all") return { ok: true, value: "all" };
  if (!Array.isArray(value) || value.length > 500 || !value.every((id) => typeof id === "string" && ID.test(id) && exists(id))) {
    return { ok: false, error: LOGIN_ERRORS.bots };
  }
  return { ok: true, value: [...new Set(value as string[])] };
}

export function isJson(req: { headers: Record<string, string | string[] | undefined> }): boolean {
  return String(req.headers["content-type"] ?? "").split(";", 1)[0]!.trim().toLowerCase() === "application/json";
}

export function createLoginRoutes(deps: LoginRouteDeps): RouteHandler {
  return async (ctx) => {
    const { req, res, path, method, json, readBody } = ctx;
    if (path !== "/api/logins" && !path.startsWith("/api/logins/")) return PASS;
    res.setHeader("cache-control", "no-store");
    if (path === "/api/logins" && method === "GET") {
      return json(res, 200, { logins: [...deps.list(), ...deps.onePassword.list(), ...(deps.bitwarden?.list() ?? []), ...(deps.bitwardenSecrets?.list() ?? [])],
        onePassword: deps.onePassword.status(), ...(deps.bitwarden ? { bitwarden: deps.bitwarden.status() } : {}),
        ...(deps.bitwardenSecrets ? { bitwardenSecrets: deps.bitwardenSecrets.status() } : {}) });
    }
    // JSON only, so a form posted from another local page cannot add or change one.
    if (method !== "GET" && method !== "DELETE" && !isJson(req)) return json(res, 415, { error: "content-type must be application/json" });
    // 1Password's own paths, ahead of the /api/logins/:id pattern they would match.
    if (path === ONE_PASSWORD && method === "POST") {
      const body = await readBody(req, 16_384);
      const token = body && typeof body === "object" && typeof body.token === "string" ? body.token.trim() : "";
      if (!token || token.length > 8192 || /\s/u.test(token)) return json(res, 400, { error: LOGIN_ERRORS.token });
      if (!token.startsWith("ops_")) return json(res, 400, { error: LOGIN_ERRORS.notServiceAccount });
      try { return json(res, 200, { onePassword: await deps.onePassword.connect(token) }); }
      catch (error) { return json(res, 400, { error: error instanceof Error && error.message ? error.message : LOGIN_ERRORS.token }); }
    }
    if (path === `${ONE_PASSWORD}/refresh` && method === "POST") return json(res, 200, { onePassword: await deps.onePassword.refresh() });
    if (path === BITWARDEN_SECRETS || path.startsWith(`${BITWARDEN_SECRETS}/`)) return bitwardenSecretsRoute(ctx, deps.bitwardenSecrets);
    if (path === BITWARDEN || path.startsWith(`${BITWARDEN}/`)) {
      if (!deps.bitwarden) return json(res, 404, { error: "not found" });
      if (path === `${BITWARDEN}/refresh` && method === "POST") return json(res, 200, { bitwarden: await deps.bitwarden.refresh() });
      if (path === BITWARDEN && method === "DELETE") return json(res, 200, { bitwarden: await deps.bitwarden.disconnect() });
      if (path !== BITWARDEN || method !== "POST") return json(res, 405, { error: "method not allowed" });
      const parsed = parseBitwardenCredentials(await readBody(req, 16_384));
      if (!parsed.ok) return json(res, 400, { error: parsed.error });
      try { return json(res, 200, { bitwarden: await deps.bitwarden.connect(parsed.value) }); }
      catch (error) { return json(res, 400, { error: error instanceof Error && error.message ? error.message : LOGIN_ERRORS.bitwardenPassword }); }
    }
    if (path === ONE_PASSWORD && method === "DELETE") return json(res, 200, { onePassword: deps.onePassword.disconnect() });
    const vault = VAULT.exec(path);
    if (vault && method === "PATCH") {
      const body = await readBody(req, 16_384);
      const bots = parseBots(body && typeof body === "object" ? body.bots : undefined, deps.botExists);
      if (!bots.ok || bots.value === undefined) return json(res, 400, { error: bots.ok ? LOGIN_ERRORS.bots : bots.error });
      const status = deps.onePassword.grant(vault[1]!, bots.value);
      return status ? json(res, 200, { onePassword: status }) : json(res, 404, { error: "no such vault" });
    }
    const item = ITEM.exec(path);
    if (item && method === "PATCH") {
      const body = await readBody(req, 16_384);
      const value = body && typeof body === "object" ? body.bots : undefined;
      const bots = value === null ? { ok: true as const, value: null } : parseBots(value, deps.botExists);
      if (!bots.ok || bots.value === undefined) return json(res, 400, { error: bots.ok ? LOGIN_ERRORS.bots : bots.error });
      const granted = await deps.onePassword.grantItem(`${item[1]!}:${item[2]!}`, bots.value);
      if (granted === null) return json(res, 503, { error: UNREAD });
      if (!granted) return json(res, 404, { error: "no such item" });
      return json(res, 200, { logins: deps.onePassword.list(), onePassword: deps.onePassword.status() });
    }
    if (path === ITEMS && method === "PUT") {
      const body = await readBody(req, 262_144);
      const items = body && typeof body === "object" ? body.items : undefined;
      if (!items || typeof items !== "object" || Array.isArray(items)) return json(res, 400, { error: "send items as an object of item ids to bots" });
      const grants: Record<string, LoginBots> = {};
      for (const [key, value] of Object.entries(items)) {
        const bots = parseBots(value, deps.botExists);
        if (!ITEM_KEY.test(key) || !bots.ok || bots.value === undefined) return json(res, 400, { error: bots.ok ? LOGIN_ERRORS.bots : bots.error });
        grants[key] = bots.value;
      }
      deps.onePassword.setItemGrants(grants, body.keep === true);
      return json(res, 200, { items: Object.keys(grants).length });
    }
    if (path === ONE_PASSWORD || path.startsWith(`${ONE_PASSWORD}/`)) return json(res, 405, { error: "method not allowed" });
    if (path === "/api/logins" && method === "POST") {
      const body = await readBody(req, 16_384);
      if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "send the login as a JSON object" });
      const host = normalizeLoginHost(body.site);
      if (!host) return json(res, 400, { error: LOGIN_ERRORS.site });
      const fields = parseLoginFields(body, { passwordRequired: true });
      if (!fields.ok) return json(res, 400, { error: fields.error });
      const totp = parseTotpField(body.totp);
      if (!totp.ok) return json(res, 400, { error: totp.error });
      const bots = parseBots(body.bots ?? "all", deps.botExists);
      if (!bots.ok) return json(res, 400, { error: bots.error });
      if (body.exactHost !== undefined && typeof body.exactHost !== "boolean") return json(res, 400, { error: LOGIN_ERRORS.exactHost });
      const login = deps.create({
        ...loginPlace(host, [], body.exactHost === true), username: fields.value.username ?? "", password: fields.value.password!,
        totp: totp.value ?? null, source: "settings", bots: bots.value ?? "all",
      });
      return json(res, 201, { login });
    }
    const id = path.slice("/api/logins/".length);
    if (/^1password(?::|%3a)/iu.test(id)) return json(res, 409, { error: LOGIN_ERRORS.readOnly });
    if (/^bitwarden(?::|%3a)/iu.test(id)) return json(res, 409, { error: LOGIN_ERRORS.bitwardenReadOnly });
    if (/^bitwarden-secrets(?::|%3a)/iu.test(id)) return json(res, 409, { error: LOGIN_ERRORS.bitwardenSecretsReadOnly });
    if (!ID.test(id)) return json(res, 404, { error: "no such login" });
    if (method === "DELETE") {
      return deps.remove(id) ? json(res, 200, { ok: true }) : json(res, 404, { error: "no such login" });
    }
    if (method !== "PATCH") return json(res, 405, { error: "method not allowed" });
    const body = await readBody(req, 16_384);
    if (!body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "send the change as a JSON object" });
    const fields = parseLoginFields(body, { passwordRequired: false });
    if (!fields.ok) return json(res, 400, { error: fields.error });
    const totp = parseTotpField(body.totp);
    if (!totp.ok) return json(res, 400, { error: totp.error });
    const bots = parseBots(body.bots, deps.botExists);
    if (!bots.ok) return json(res, 400, { error: bots.error });
    if (body.exactHost !== undefined && typeof body.exactHost !== "boolean") return json(res, 400, { error: LOGIN_ERRORS.exactHost });
    const site = body.site === undefined ? undefined : normalizeLoginHost(body.site);
    if (site === null) return json(res, 400, { error: LOGIN_ERRORS.site });
    const login = deps.update(id, {
      ...(site === undefined ? {} : { site }),
      ...fields.value,
      ...(totp.value === undefined ? {} : { totp: totp.value }),
      ...(bots.value === undefined ? {} : { bots: bots.value }),
      ...(body.exactHost === undefined ? {} : { exactHost: body.exactHost }),
    });
    if (login === "taken") return json(res, 409, { error: LOGIN_ERRORS.taken });
    return login ? json(res, 200, { login }) : json(res, 404, { error: "no such login" });
  };
}