58 lines · 2.2 KB
import { env } from "cloudflare:workers";
import { all } from "./db";
import { forgetScope } from "./scoped-db/locators";

const ID_PATTERN = /^[0-9a-z]{20}$/;

/**
 * Credentials minted after the AccountState move carry their account id: `<prefix>_<accountId>_<secret>`.
 * Returns the embedded id, or null for older tokens (resolve those through a locator).
 */
export function embeddedAccountId(token: string, prefix: string): string | null {
  if (!token.startsWith(`${prefix}_`)) return null;
  const parts = token.slice(prefix.length + 1).split("_");
  if (parts.length !== 2) return null;
  return ID_PATTERN.test(parts[0]) ? parts[0] : null;
}

export function accountToken(prefix: string, accountId: string, secretHex: string): string {
  return `${prefix}_${accountId}_${secretHex}`;
}

/** Every account (user or organization) in the directory, for sweeps and fan-out. */
export async function allAccountIds(): Promise<string[]> {
  return (await all<{ id: string }>("SELECT id FROM accounts")).map((row) => row.id);
}

/** Every user account, for sweeps over user-only tables (sessions, credentials). */
export async function allUserIds(): Promise<string[]> {
  return (await all<{ id: string }>("SELECT account_id AS id FROM users")).map((row) => row.id);
}

/** Wipes the account's AccountState and every locator pointing into it. */
export async function dropAccountState(accountId: string): Promise<void> {
  try {
    const stub = env.ACCOUNT_STATE.get(env.ACCOUNT_STATE.idFromName(accountId)) as unknown as {
      destroy(): Promise<void>;
    };
    await stub.destroy();
  } catch (error) {
    console.error("AccountState destroy failed", accountId, error);