Exemplos TypeScript · examples/eve-access.ts

eve-access.ts

typescript
/** Exemplo para copiar junto de access-client.ts para agent/lib/.
 * Confira as interfaces na versão INSTALADA do eve antes de usar.
 * O cofre e a ACL das sessões eve são responsabilidades do aplicativo.
 */
import type { AuthFn } from "eve/channels/auth";
import { ForbiddenError, UnauthenticatedError } from "eve/channels/auth";
import { AccessClient, AccessDeniedError } from "./access-client.ts";

type Subject = { issuer: string; organizationId: string; userId: string };
export interface AccessCredentialVault {
  // Ref opaca aleatória, não o token. Cifre em repouso, aplique TTL e revogação.
  put(input: Subject & { token: string }): Promise<string>;
  // Deve conferir issuer, organizationId E userId antes de ler a referência.
  get(input: Subject & { ref: string }): Promise<string | null>;
}

type CurrentCaller = {
  authenticator: string;
  principalType: string;
  principalId: string;
  issuer?: string;
  attributes?: Record<string, unknown>;
} | null;

export function createAccessBridge(client: AccessClient, vault: AccessCredentialVault) {
  const authenticate: AuthFn<Request> = async request => {
    const match = /^Bearer ([^\s]+)$/i.exec(request.headers.get("authorization") ?? "");
    if (!match) throw new UnauthenticatedError({ message: "Entre na sua conta." });
    try {
      const identity = await client.identity(match[1]);
      const ref = await vault.put({ issuer: client.issuer, organizationId: identity.organizationId, userId: identity.userId, token: match[1] });
      if (!ref) throw new Error("Cofre indisponível.");
      return {
        authenticator: "access",
        issuer: client.issuer,
        principalType: "user",
        principalId: identity.userId,
        attributes: { accessCredentialRef: ref, accessOrganizationId: identity.organizationId }, // nunca coloque o token aqui
      };
    } catch (error) {
      if (error instanceof AccessDeniedError) {
        if (error.reason === "unauthenticated") {
          throw new UnauthenticatedError({ message: "Entre novamente na sua conta." });
        }
        if (error.reason === "suspended") {
          // Conta nova ainda não adicionada, removida ou suspensa nesta organização.
          throw new ForbiddenError({ message: "Sem acesso nesta organização. Peça a um administrador do Access para incluir seu e-mail." });
        }
      }
      // Falha explícita, sem cair em outro autenticador e sem vazar credenciais.
      throw new Error("Não foi possível validar o acesso.");
    }
  };

  async function requireRole(current: CurrentCaller, requiredRole: string) {
    if (
      !current || current.authenticator !== "access" ||
      current.principalType !== "user" || current.issuer !== client.issuer ||
      current.attributes?.accessOrganizationId !== client.organizationId ||
      typeof current.attributes?.accessCredentialRef !== "string"
    ) throw new AccessDeniedError("unauthenticated");
    let token: string | null;
    try {
      token = await vault.get({
        issuer: client.issuer, organizationId: client.organizationId, userId: current.principalId,
        ref: current.attributes.accessCredentialRef,
      });
    } catch {
      throw new AccessDeniedError("unavailable");
    }
    if (!token) throw new AccessDeniedError("unauthenticated");
    return client.requireRole(token, requiredRole, current.principalId);
  }

  return { authenticate, requireRole };
}