Exemplos TypeScript · examples/eve-channel-access.ts

eve-channel-access.ts

typescript
/** Ponte entre um canal eve com webhook verificado (Telegram, Slack…) e o Access.
 * Copie para agent/lib/ junto de access-client.ts e channel-access-client.ts.
 * Somente servidor. Confira os tipos na versão INSTALADA do eve.
 */
import { AccessDeniedError, type AccessIdentity } from "./access-client.ts";
import type { ChannelAccessClient, ChannelSender } from "./channel-access-client.ts";

// Atributos de sessão do eve aceitam apenas string ou lista de strings.
type AuthAttributes = Readonly<Record<string, string | readonly string[]>>;
export type ChannelCaller = Readonly<{
  authenticator: string;
  principalType: string;
  principalId: string;
  issuer?: string;
  attributes: AuthAttributes;
}> | null;

const AUTHENTICATOR = "access-channel";

/**
 * O `auth` que o onMessage do canal devolve para um remetente vinculado: o
 * principal passa a ser a conta Access (`user`), não o ID da plataforma. O eve
 * substitui `auth.current` a cada mensagem, então chame isto em toda mensagem.
 */
export function channelUserAuth(
  client: ChannelAccessClient,
  sender: ChannelSender,
  identity: AccessIdentity,
  platformAttributes: AuthAttributes = {},
) {
  return {
    authenticator: AUTHENTICATOR,
    issuer: client.issuer,
    principalType: "user",
    principalId: identity.userId,
    attributes: {
      ...platformAttributes,
      accessOrganizationId: identity.organizationId,
      accessChannel: sender.channel,
      accessWorkspace: sender.workspace,
      accessSubject: sender.subject,
    },
  };
}

/**
 * Use em cada ferramenta sensível, imediatamente antes do efeito, com
 * `ctx.session.auth.current`. Consulta o Access de novo (sem cache) e confere
 * que o remetente continua vinculado à mesma conta, na organização configurada.
 */
export async function requireChannelRole(
  client: ChannelAccessClient,
  current: ChannelCaller,
  requiredRole: string,
): Promise<AccessIdentity> {
  const a = current?.attributes;
  if (
    !current || !a || current.authenticator !== AUTHENTICATOR || current.principalType !== "user" ||
    current.issuer !== client.issuer || a.accessOrganizationId !== client.organizationId ||
    typeof a.accessChannel !== "string" || typeof a.accessWorkspace !== "string" || typeof a.accessSubject !== "string"
  ) throw new AccessDeniedError("unauthenticated");
  const sender: ChannelSender = { channel: a.accessChannel, workspace: a.accessWorkspace, subject: a.accessSubject };
  return client.requireRole(sender, requiredRole, current.principalId);
}