Exemplos TypeScript · examples/access-client.ts

access-client.ts

typescript
/** Servidor somente. Sem dependências externas; requer fetch e AbortSignal.timeout. */
export type AccessIdentity = Readonly<{
  authenticated: true;
  organizationId: string;
  userId: string;
  roles: readonly string[];
  checkedAt: string;
}>;

export type DenialReason =
  | "unauthenticated"
  // HTTP 403: sem participação ativa na organização. Inclui conta suspensa e
  // também conta que ainda não foi adicionada por um administrador.
  | "suspended"
  | "role_missing"
  | "identity_mismatch"
  | "unavailable"
  | "invalid_response";

export class AccessDeniedError extends Error {
  readonly reason: DenialReason;
  constructor(reason: DenialReason) {
    // Não inclua a resposta do servidor, URL, token ou erro de transporte.
    super("Acesso negado.");
    this.name = "AccessDeniedError";
    this.reason = reason;
  }
}

/** Raiz HTTPS do Access, terminada em "/". Recusa credenciais, query e fragmento. */
function accessRoot(baseUrl: string): URL {
  const url = new URL(baseUrl);
  if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) {
    throw new Error("ACCESS_BASE_URL precisa ser uma URL HTTPS sem credenciais, query ou fragmento.");
  }
  url.pathname = url.pathname.replace(/\/+$/, "") + "/";
  return url;
}

export class AccessClient {
  readonly issuer: string;
  readonly organizationId: string;
  private readonly endpoint: string;
  private readonly request: typeof fetch;
  private readonly timeoutMs: number;

  constructor(options: { baseUrl: string; organizationId: string; fetch?: typeof fetch; timeoutMs?: number }) {
    if (typeof options.organizationId !== "string" || !options.organizationId.trim()) throw new Error("ACCESS_ORGANIZATION_ID é obrigatório.");
    this.organizationId = options.organizationId;
    const url = accessRoot(options.baseUrl);
    this.issuer = url.href.replace(/\/$/, "");
    const endpoint = new URL("api/v1/identity", url);
    endpoint.searchParams.set("organizationId", this.organizationId);
    this.endpoint = endpoint.href;
    this.request = options.fetch ?? globalThis.fetch;
    this.timeoutMs = options.timeoutMs ?? 5000;
    if (!Number.isInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 30000) {
      throw new Error("Timeout inválido.");
    }
  }

  async identity(sessionToken: string): Promise<AccessIdentity> {
    if (typeof sessionToken !== "string" || !sessionToken || sessionToken.length > 8192 || /\s/u.test(sessionToken)) {
      throw new AccessDeniedError("unauthenticated");
    }
    let response: Response;
    let body: unknown;
    try {
      response = await this.request(this.endpoint, {
        method: "GET",
        headers: { Authorization: `Bearer ${sessionToken}`, Accept: "application/json" },
        signal: AbortSignal.timeout(this.timeoutMs),
        redirect: "error",
        cache: "no-store",
      });
    } catch {
      throw new AccessDeniedError("unavailable");
    }
    if (response.status === 401) throw new AccessDeniedError("unauthenticated");
    if (response.status === 403) throw new AccessDeniedError("suspended");
    if (response.status !== 200) throw new AccessDeniedError("unavailable");
    try {
      body = await response.json();
    } catch {
      throw new AccessDeniedError("invalid_response");
    }
    if (!body || typeof body !== "object" || Array.isArray(body)) {
      throw new AccessDeniedError("invalid_response");
    }
    const value = body as Record<string, unknown>;
    if (
      value.authenticated !== true ||
      typeof value.organizationId !== "string" || !value.organizationId.trim() ||
      typeof value.userId !== "string" || !value.userId.trim() ||
      !Array.isArray(value.roles) ||
      !value.roles.every((r: unknown) => typeof r === "string" && r.length > 0) ||
      typeof value.checkedAt !== "string" || !Number.isFinite(Date.parse(value.checkedAt))
    ) {
      throw new AccessDeniedError("invalid_response");
    }
    if (value.organizationId !== this.organizationId) throw new AccessDeniedError("identity_mismatch");
    return Object.freeze({
      authenticated: true,
      organizationId: value.organizationId,
      userId: value.userId,
      roles: Object.freeze([...value.roles] as string[]),
      checkedAt: value.checkedAt,
    });
  }

  async requireRole(
    sessionToken: string,
    requiredRole: string,
    expectedUserId: string,
  ): Promise<AccessIdentity> {
    // Política e principal esperados vêm do servidor, nunca de input do modelo.
    if (!requiredRole || !requiredRole.trim() || !expectedUserId || !expectedUserId.trim()) {
      throw new AccessDeniedError("unauthenticated");
    }
    const identity = await this.identity(sessionToken); // sem cache de autorização
    if (identity.userId !== expectedUserId) throw new AccessDeniedError("identity_mismatch");
    if (!identity.roles.includes(requiredRole)) throw new AccessDeniedError("role_missing");
    return identity;
  }
}

export type AuthFailure = "invalid_credentials" | "rate_limited" | "unavailable" | "invalid_response";

export class AccessAuthError extends Error {
  readonly reason: AuthFailure;
  constructor(reason: AuthFailure) {
    // Sem detalhes do servidor: a mensagem pode chegar ao usuário ou a um log.
    super("Não foi possível autenticar no Access.");
    this.name = "AccessAuthError";
    this.reason = reason;
  }
}

type AuthRequestOptions = { baseUrl: string; fetch?: typeof fetch; timeoutMs?: number };

function authRequest(options: AuthRequestOptions, path: string, init: { headers?: Record<string, string>; body: unknown }) {
  const root = accessRoot(options.baseUrl);
  return (options.fetch ?? globalThis.fetch)(new URL(path, root).href, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      // O fetch do Node envia Sec-Fetch-Mode, e com ele o Access exige Origin nas
      // rotas de autenticação. Envie a origem do PRÓPRIO Access, nunca a do
      // navegador do usuário: qualquer outra origem recebe 403.
      Origin: root.origin,
      ...init.headers,
    },
    body: JSON.stringify(init.body),
    redirect: "error",
    cache: "no-store",
    credentials: "omit",
    signal: AbortSignal.timeout(options.timeoutMs ?? 5000),
  });
}

/**
 * Entra no Access a partir do SERVIDOR do aplicativo, nunca do navegador.
 * Devolve o token assinado do cabeçalho `set-auth-token`, o único aceito como
 * Bearer. O campo `token` do JSON não serve. Não registre a senha nem o token.
 */
export async function signInToAccess(
  options: AuthRequestOptions & { email: string; password: string },
): Promise<Readonly<{ token: string; userId: string }>> {
  let response: Response;
  try {
    response = await authRequest(options, "api/auth/sign-in/email", { body: { email: options.email, password: options.password } });
  } catch {
    throw new AccessAuthError("unavailable");
  }
  if (response.status === 400 || response.status === 401) throw new AccessAuthError("invalid_credentials");
  if (response.status === 429) throw new AccessAuthError("rate_limited");
  if (response.status !== 200) throw new AccessAuthError("unavailable");
  const token = response.headers.get("set-auth-token");
  let body: unknown;
  try {
    body = await response.json();
  } catch {
    throw new AccessAuthError("invalid_response");
  }
  const user = (body as { user?: { id?: unknown } } | null)?.user;
  if (!token || token.length > 8192 || /\s/u.test(token) || typeof user?.id !== "string" || !user.id) {
    throw new AccessAuthError("invalid_response");
  }
  return Object.freeze({ token, userId: user.id });
}

/**
 * Encerra a sessão no Access. Depois disso o token deixa de valer em
 * /api/v1/identity. Em caso de erro, bloqueie o uso local do token mesmo assim
 * e trate a revogação remota como pendente.
 */
export async function signOutFromAccess(options: AuthRequestOptions & { token: string }): Promise<void> {
  let response: Response;
  try {
    response = await authRequest(options, "api/auth/sign-out", { headers: { Authorization: `Bearer ${options.token}` }, body: {} });
  } catch {
    throw new AccessAuthError("unavailable");
  }
  if (response.status !== 200) throw new AccessAuthError("unavailable");
}

// ---------------------------------------------------------------------------
// Login pelo navegador. A pessoa digita a senha só no Access; o servidor do
// agente recebe uma sessão própria, restrita à identidade desta organização.
// ---------------------------------------------------------------------------

/**
 * `poll`: o servidor consulta até a confirmação. `code`: a pessoa cola o código.
 * `redirect`: o navegador volta à `redirectUri` com `?code=…` (ou
 * `?error=access_denied`); é o retorno que o login interativo do eve espera.
 */
export type BrowserLoginMode = "poll" | "code" | "redirect";

export type BrowserLoginStart = Readonly<{
  /** Segredo do servidor: guarde junto da sessão do aplicativo, nunca no navegador ou no modelo. */
  deviceCode: string;
  /** Link para a pessoa abrir. Montado com ACCESS_BASE_URL, nunca com o host de uma requisição. */
  verificationUrl: string;
  mode: BrowserLoginMode;
  expiresAt: string;
  /** Intervalo mínimo entre consultas, em segundos. */
  interval: number;
}>;

export type BrowserLoginResult =
  | Readonly<{ status: "pending"; interval: number }>
  | Readonly<{ status: "complete"; token: string; userId: string; organizationId: string; expiresAt: string }>;

export type BrowserLoginFailure =
  | "forbidden" // 403: a pessoa recusou, ou a conta não tem participação ativa nesta organização
  | "expired" // 410: pedido expirado, já usado, bloqueado por tentativas ou integração revogada
  | "invalid_code" // 400 com código: código de confirmação incorreto; a pessoa pode tentar de novo
  | "misconfigured" // 400 sem código, 401: chave da integração errada/revogada ou chamada inválida
  | "rate_limited"
  | "unavailable"
  | "invalid_response";

export class BrowserLoginError extends Error {
  readonly reason: BrowserLoginFailure;
  constructor(reason: BrowserLoginFailure) {
    // Sem resposta do servidor, chave, deviceCode ou token na mensagem.
    super("Não foi possível concluir o login pelo navegador.");
    this.name = "BrowserLoginError";
    this.reason = reason;
  }
}

type BrowserLoginOptions = {
  baseUrl: string;
  organizationId: string;
  /** Chave da integração (acc_channel_…), criada em Integração → Integrações. Só no servidor. */
  integrationKey: string;
  fetch?: typeof fetch;
  timeoutMs?: number;
};

const INTEGRATION_KEY = /^acc_channel_[A-Za-z0-9_-]{43}$/;
const DEVICE_CODE = /^acc_device_[A-Za-z0-9_-]{43}$/;
const VERIFICATION_PATH = /^\/agent-login#code=[A-Za-z0-9_-]{43}$/;

async function integrationPost(options: BrowserLoginOptions, path: string, body: unknown) {
  if (typeof options.organizationId !== "string" || !options.organizationId.trim()) throw new Error("ACCESS_ORGANIZATION_ID é obrigatório.");
  if (!INTEGRATION_KEY.test(options.integrationKey ?? "")) throw new Error("ACCESS_CHANNEL_KEY ausente ou em formato inválido.");
  const root = accessRoot(options.baseUrl);
  let response: Response;
  try {
    // Chamada de servidor: sem Origin e sem cookie, ou o Access responde 403.
    response = await (options.fetch ?? globalThis.fetch)(new URL(path, root).href, {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json", Authorization: `Bearer ${options.integrationKey}` },
      body: JSON.stringify(body),
      redirect: "error",
      cache: "no-store",
      credentials: "omit",
      signal: AbortSignal.timeout(options.timeoutMs ?? 5000),
    });
  } catch {
    throw new BrowserLoginError("unavailable");
  }
  let value: unknown = null;
  if (response.status === 200 || response.status === 201 || response.status === 202) {
    try {
      value = await response.json();
    } catch {
      throw new BrowserLoginError("invalid_response");
    }
    if (!value || typeof value !== "object" || Array.isArray(value)) throw new BrowserLoginError("invalid_response");
  }
  return { root, status: response.status, body: value as Record<string, unknown> | null };
}

const isoDate = (value: unknown): value is string => typeof value === "string" && Number.isFinite(Date.parse(value));
const interval = (value: unknown): value is number => Number.isInteger(value) && (value as number) >= 1 && (value as number) <= 60;

/** URL de retorno do modo redirect: HTTPS, ou HTTP só em localhost (`eve dev`). */
function redirectUriOf(value: unknown): string {
  const LOOPBACK = ["localhost", "127.0.0.1", "[::1]"];
  if (typeof value !== "string" || value.length > 2048 || value.includes("#") || !URL.canParse(value)) {
    throw new Error("redirectUri precisa ser uma URL absoluta sem fragmento.");
  }
  const url = new URL(value);
  if (url.username || url.password || !(url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.includes(url.hostname)))) {
    throw new Error("redirectUri precisa ser HTTPS (ou HTTP em localhost), sem credenciais.");
  }
  return url.href;
}

/**
 * Inicia o login quando o canal responde 401 (sem sessão Access válida).
 * Devolva à pessoa só `verificationUrl`; guarde `deviceCode` no servidor.
 * `poll`: o servidor consulta até a pessoa confirmar. `code`: a pessoa cola no
 * login do aplicativo o código exibido pelo Access, o que prova que quem
 * confirmou é quem está diante do agente. `redirect`: informe `redirectUri`
 * (o `callbackUrl` do eve); o código chega nela e você conclui com
 * `completeBrowserLogin({ deviceCode, code })`.
 */
export async function startBrowserLogin(
  options: BrowserLoginOptions & ({ mode: "poll" | "code"; redirectUri?: undefined } | { mode: "redirect"; redirectUri: string }),
): Promise<BrowserLoginStart> {
  if (options.mode !== "poll" && options.mode !== "code" && options.mode !== "redirect") {
    throw new Error("mode deve ser \"poll\", \"code\" ou \"redirect\".");
  }
  if (options.mode !== "redirect" && options.redirectUri !== undefined) throw new Error("redirectUri só vale no modo redirect.");
  const request = options.mode === "redirect"
    ? { mode: options.mode, redirectUri: redirectUriOf(options.redirectUri) }
    : { mode: options.mode };
  const { root, status, body } = await integrationPost(options, "api/v1/agent-logins", request);
  if (status === 400 || status === 401 || status === 403) throw new BrowserLoginError("misconfigured");
  if (status === 429) throw new BrowserLoginError("rate_limited");
  if (status !== 201 || !body) throw new BrowserLoginError("unavailable");
  if (
    typeof body.deviceCode !== "string" || !DEVICE_CODE.test(body.deviceCode) ||
    typeof body.verificationPath !== "string" || !VERIFICATION_PATH.test(body.verificationPath) ||
    body.mode !== options.mode || !isoDate(body.expiresAt) || !interval(body.interval)
  ) throw new BrowserLoginError("invalid_response");
  return Object.freeze({
    deviceCode: body.deviceCode,
    verificationUrl: new URL(body.verificationPath, root).href,
    mode: options.mode,
    expiresAt: body.expiresAt,
    interval: body.interval,
  });
}

/**
 * Consulta (modo poll) ou conclui com o código colado pela pessoa (modo code) ou
 * recebido na URL de retorno (modo redirect).
 * Concluído, o token vale como o `set-auth-token` do login por senha: guarde-o
 * no cofre e use-o como Bearer em /api/v1/identity. Funciona uma única vez.
 */
export async function completeBrowserLogin(
  options: BrowserLoginOptions & { deviceCode: string; code?: string },
): Promise<BrowserLoginResult> {
  if (!DEVICE_CODE.test(options.deviceCode ?? "")) throw new BrowserLoginError("expired");
  const code = options.code?.trim();
  if (options.code !== undefined && (!code || code.length > 20 || !/^[A-Za-z0-9 -]+$/.test(code))) {
    throw new BrowserLoginError("invalid_code"); // não gasta uma tentativa com texto que não pode ser código
  }
  const { status, body } = await integrationPost(options, "api/v1/agent-logins/token", code ? { deviceCode: options.deviceCode, code } : { deviceCode: options.deviceCode });
  if (status === 202 && body) {
    if (body.status !== "pending" || !interval(body.interval)) throw new BrowserLoginError("invalid_response");
    return Object.freeze({ status: "pending", interval: body.interval });
  }
  if (status === 400) throw new BrowserLoginError(code ? "invalid_code" : "misconfigured");
  if (status === 401) throw new BrowserLoginError("misconfigured");
  if (status === 403) throw new BrowserLoginError("forbidden");
  if (status === 410) throw new BrowserLoginError("expired");
  if (status === 429) throw new BrowserLoginError("rate_limited");
  if (status !== 200 || !body) throw new BrowserLoginError("unavailable");
  if (
    typeof body.token !== "string" || !body.token || body.token.length > 8192 || /\s/u.test(body.token) ||
    typeof body.userId !== "string" || !body.userId.trim() || !isoDate(body.expiresAt)
  ) throw new BrowserLoginError("invalid_response");
  // A chave determina a organização; confira mesmo assim antes de guardar o token.
  if (body.organizationId !== options.organizationId) throw new BrowserLoginError("invalid_response");
  return Object.freeze({ status: "complete", token: body.token, userId: body.userId, organizationId: body.organizationId, expiresAt: body.expiresAt });
}

/**
 * Espera a confirmação no modo poll (CLI, TUI ou um worker do servidor).
 * Respeita o intervalo, o limite de 429 e a expiração; cancele com `signal`.
 */
export async function waitForBrowserLogin(
  options: BrowserLoginOptions & Pick<BrowserLoginStart, "deviceCode" | "expiresAt" | "interval"> & {
    signal?: AbortSignal;
    sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
  },
): Promise<Extract<BrowserLoginResult, { status: "complete" }>> {
  const sleep = options.sleep ?? ((ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => { clearTimeout(timer); reject(new BrowserLoginError("expired")); }, { once: true });
  }));
  let seconds = options.interval;
  const deadline = Date.parse(options.expiresAt);
  for (;;) {
    if (options.signal?.aborted || Date.now() >= deadline) throw new BrowserLoginError("expired");
    await sleep(seconds * 1000, options.signal);
    try {
      const result = await completeBrowserLogin(options);
      if (result.status === "complete") return result;
      seconds = Math.max(seconds, result.interval);
    } catch (error) {
      if (!(error instanceof BrowserLoginError) || (error.reason !== "rate_limited" && error.reason !== "unavailable")) throw error;
      seconds = Math.min(seconds * 2, 60); // recua diante de 429 ou falha transitória
    }
  }
}