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

channel-access-client.ts

typescript
/** Somente servidor. Sender vem do webhook validado, nunca do modelo. */
import { AccessDeniedError, type AccessIdentity } from "./access-client.ts";

export type ChannelSender = Readonly<{ channel: string; workspace: string; subject: string }>;
export class ChannelAccessClient {
  readonly issuer: string;
  readonly organizationId: string;
  private base: URL;
  private key: string;
  private request: typeof fetch;
  constructor(options: { baseUrl: string; organizationId: string; integrationKey: string; fetch?: typeof fetch }) {
    if (typeof options.organizationId !== "string" || !options.organizationId.trim()) throw new Error("ACCESS_ORGANIZATION_ID é obrigatório.");
    this.organizationId = options.organizationId;
    this.base = new URL(options.baseUrl);
    if (this.base.protocol !== "https:" || this.base.username || this.base.password || this.base.search || this.base.hash || !["", "/"].includes(this.base.pathname)) {
      throw new Error("ACCESS_BASE_URL deve ser a raiz HTTPS do Access.");
    }
    if (!/^acc_channel_[A-Za-z0-9_-]{43}$/.test(options.integrationKey)) throw new Error("Chave de integração inválida.");
    this.issuer = this.base.origin;
    this.key = options.integrationKey;
    this.request = options.fetch ?? globalThis.fetch;
  }
  private async call(path: string, sender: ChannelSender, status: number): Promise<Record<string, unknown>> {
    if (!sender || !/^[a-z0-9_-]{1,40}$/.test(sender.channel) ||
        typeof sender.workspace !== "string" || !sender.workspace || sender.workspace.length > 200 ||
        typeof sender.subject !== "string" || !sender.subject || sender.subject.length > 200) {
      throw new AccessDeniedError("unauthenticated");
    }
    let response: Response;
    try {
      response = await this.request(new URL(path, this.base), {
        method: "POST", headers: { Authorization: `Bearer ${this.key}`, "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({ channel: sender.channel, workspace: sender.workspace, subject: sender.subject }),
        redirect: "error", cache: "no-store", credentials: "omit", signal: AbortSignal.timeout(5000),
      });
    } catch { throw new AccessDeniedError("unavailable"); }
    if (response.status === 401) throw new AccessDeniedError("unauthenticated");
    if (response.status === 403) throw new AccessDeniedError("suspended");
    if (response.status !== status) throw new AccessDeniedError("unavailable");
    try {
      const value: unknown = await response.json();
      if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
      return value as Record<string, unknown>;
    } catch { throw new AccessDeniedError("invalid_response"); }
  }
  async identity(sender: ChannelSender): Promise<AccessIdentity> {
    const value = await this.call("/api/v1/channels/identity", sender, 200);
    if (value.authenticated !== true || typeof value.userId !== "string" || !value.userId.trim() ||
        typeof value.organizationId !== "string" || !value.organizationId.trim() ||
        !Array.isArray(value.roles) || !value.roles.every(r => 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(sender: ChannelSender, role: string, expectedUserId: string): Promise<AccessIdentity> {
    if (!role?.trim() || !expectedUserId?.trim()) throw new AccessDeniedError("unauthenticated");
    const identity = await this.identity(sender);
    if (identity.userId !== expectedUserId) throw new AccessDeniedError("identity_mismatch");
    if (!identity.roles.includes(role)) throw new AccessDeniedError("role_missing");
    return identity;
  }
  async challenge(sender: ChannelSender): Promise<Readonly<{ verificationUrl: string; expiresAt: string }>> {
    const value = await this.call("/api/v1/channels/challenges", sender, 201);
    if (typeof value.verificationPath !== "string" || !/^\/connect-channel#code=[A-Za-z0-9_-]{43}$/.test(value.verificationPath) ||
        typeof value.expiresAt !== "string" || !Number.isFinite(Date.parse(value.expiresAt)) || Date.parse(value.expiresAt) <= Date.now()) {
      throw new AccessDeniedError("invalid_response");
    }
    return Object.freeze({ verificationUrl: new URL(value.verificationPath, this.base).href, expiresAt: value.expiresAt });
  }
}