All files / src/lib/functions middleware.ts

100% Statements 263/263
100% Branches 191/191
100% Functions 33/33
100% Lines 262/262

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836                                            23x 23x 23x 23x 23x 23x                               23x     12x 12x       12x 12x 12x               10x 10x 10x 9x       10x 1x 1x     9x 9x 7x         2x   2x       2x         1x       1x       1x     1x                                         354x 123x     231x 430x   231x 1x     230x 422x 74x     348x 244x     104x 90x     14x 13x     1x     230x       27x   27x           351x         27x   116x 116x 116x     99x       17x     17x     119x 119x           57x                       32x             26x 26x 24x     2x 1x 1x     1x             26x 26x 1x     25x                       25x 1x     24x 24x 24x       53x 2x 2x     51x     5x 1x     4x                                     38x 27x 27x               74x 74x 74x 61x 74x 74x   13x 13x       27x             27x 27x   27x   20x             20x 20x   20x   20x   14x           14x 14x       14x   13x               13x 13x                       13x 3x 3x     3x     10x 2x       2x     8x 8x 8x                                     37x 37x 37x 22x       37x 10x     10x   27x   37x 37x 1x 1x     26x 26x     37x       26x         26x 12x           26x   26x 1x     1x     25x 25x       37x       37x 18x 1x     1x         17x 17x 17x 1x       1x       16x           18x 8x         16x 16x           14x 7x     7x 5x   7x 6x   7x     2x 1x       16x   3x         3x           13x 8x             13x 13x           5x 3x     5x 2x       2x                   2x 2x 2x 2x   2x   2x         3x     8x       8x                 8x 8x 18x   18x 8x   8x 5x           15x                 39x 1x     38x   38x 39x 26x     12x         3x     3x 2x       10x       41x 2x     39x 26x     13x                                                       27x 27x               27x 25x 2x 1x           27x         27x 26x     27x           27x   27x 7x 7x         20x 1x       19x 19x   1x     18x         1x     17x       7x 1x     6x 2x     4x 4x         4x 3x 1x     2x 1x             2x           13x 13x             13x                 12x 3x 3x         9x   9x 1x     8x       30x 30x   3x 3x       23x                
import type { MiddlewareHandler } from "hono";
import {
  KickWebhookError,
  KickWebhookSignatureError,
  validateKickWebhook,
  type KickWebhookValidationResult,
} from "./validateWebhook";
import type { ErrorLogEntry } from "./errors/logError";
import type { Env } from "../config/env";
import { getDb, Prisma, type DbClient } from "../prisma";
import {
  OAuth2AuthorizationUrl,
  Routes,
  type RESTPostOAuth2RefreshTokenResult,
} from "kick-api-types/rest";
import type { AppVariables } from "../app/types";
 
export interface KickBroadcasterAuth {
  accountId: string;
  accessToken: string;
}
 
const TOKEN_REFRESH_THRESHOLD_MS = 60_000;
const LOG_PREFIX = "[kick-webhook-middleware]";
const ACCOUNT_CACHE_TTL_SECONDS = 60;
const ACCOUNT_CACHE_TTL_MS = ACCOUNT_CACHE_TTL_SECONDS * 1_000;
const ACCOUNT_CACHE_TAG_PREFIX = "account";
const ACCOUNT_CACHE_TAG_MAX_LENGTH = 64;
 
type AccountRecord = {
  id: string;
  accountId: string;
  accessToken: string | null;
  refreshToken: string | null;
  accessTokenExpiresAt: Date | null;
  refreshTokenExpiresAt: Date | null;
};
 
type CachedAccount = {
  value: AccountRecord;
  expiresAt: number;
};
 
const accountCache = new Map<string, CachedAccount>();
 
function getAccountCacheTag(accountId: string): string {
  const sanitized = accountId.replace(/[^0-9A-Za-z_]/g, "_");
  const maxIdLength = Math.max(
    1,
    ACCOUNT_CACHE_TAG_MAX_LENGTH - (ACCOUNT_CACHE_TAG_PREFIX.length + 1)
  );
  const trimmed = sanitized.slice(0, maxIdLength);
  const normalized = trimmed || "_";
  return `${ACCOUNT_CACHE_TAG_PREFIX}_${normalized}`;
}
 
async function invalidateAccountCache(
  db: DbClient,
  accountId: string,
  steps?: StepLogger
): Promise<void> {
  const cacheTag = getAccountCacheTag(accountId);
  const removed = accountCache.delete(accountId);
  if (removed) {
    steps?.note("Cleared local account cache", {
      broadcasterAccountId: accountId,
    });
  }
  if (!db.$accelerate?.invalidate) {
    steps?.note("Accelerate invalidate unavailable", { cacheTag });
    return;
  }
 
  try {
    await db.$accelerate.invalidate({ tags: [cacheTag] });
    steps?.note("Invalidated account cache", {
      broadcasterAccountId: accountId,
      cacheTag,
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    const maybeCode =
      typeof error === "object" && error !== null && "code" in error
        ? (error as { code?: string }).code
        : undefined;
 
    if (
      (error instanceof Prisma.PrismaClientKnownRequestError ||
        maybeCode === "P6003") &&
      maybeCode === "P6003"
    ) {
      steps?.note("Accelerate invalidate rate limited", {
        broadcasterAccountId: accountId,
        cacheTag,
      });
      console.warn("Accelerate cache invalidation rate limited", {
        broadcasterAccountId: accountId,
        cacheTag,
      });
      return;
    }
 
    console.warn("Failed to invalidate account cache", {
      broadcasterAccountId: accountId,
      cacheTag,
      error: errorMessage,
    });
  }
}
 
type StepHandle = {
  id: number;
  label: string;
};
 
type StepLogger = {
  start: (label: string, meta?: Record<string, unknown>) => StepHandle;
  success: (handle: StepHandle, meta?: Record<string, unknown>) => void;
  fail: (handle: StepHandle, error: unknown) => void;
  note: (label: string, meta?: Record<string, unknown>) => void;
};
 
export function formatStepMeta(meta?: Record<string, unknown>): string {
  if (!meta) {
    return "";
  }
 
  const entries = Object.entries(meta).filter(
    ([, value]) => value !== undefined
  );
  if (entries.length === 0) {
    return "";
  }
 
  const formatted = entries.map(([key, value]) => {
    if (value === null) {
      return `${key}=null`;
    }
 
    if (typeof value === "string") {
      return `${key}="${value}"`;
    }
 
    if (typeof value === "number" || typeof value === "boolean") {
      return `${key}=${String(value)}`;
    }
 
    if (value instanceof Date) {
      return `${key}="${value.toISOString()}"`;
    }
 
    return `${key}=${JSON.stringify(value)}`;
  });
 
  return ` ${formatted.join(" ")}`;
}
 
function createStepLogger(prefix: string): StepLogger {
  let counter = 1;
 
  const write = (
    symbol: string,
    handle: StepHandle,
    meta?: Record<string, unknown>,
    level: "log" | "error" = "log"
  ) => {
    console[level](
      `${prefix} #${handle.id} ${symbol} ${handle.label}${formatStepMeta(meta)}`
    );
  };
 
  return {
    start: (label, meta) => {
      const handle = { id: counter++, label } satisfies StepHandle;
      write("▶", handle, meta);
      return handle;
    },
    success: (handle, meta) => {
      write("✓", handle, meta);
    },
    fail: (handle, error) => {
      const meta: Record<string, unknown> =
        error instanceof Error
          ? { name: error.name, message: error.message }
          : { error };
      write("✗", handle, meta, "error");
    },
    note: (label, meta) => {
      const handle = { id: counter++, label } satisfies StepHandle;
      write("•", handle, meta);
    },
  };
}
 
function cloneAccountRecord(account: AccountRecord): AccountRecord {
  return {
    ...account,
    accessTokenExpiresAt: account.accessTokenExpiresAt
      ? new Date(account.accessTokenExpiresAt)
      : null,
    refreshTokenExpiresAt: account.refreshTokenExpiresAt
      ? new Date(account.refreshTokenExpiresAt)
      : null,
  };
}
 
function storeAccountInCache(account: AccountRecord): void {
  accountCache.set(account.accountId, {
    value: cloneAccountRecord(account),
    expiresAt: Date.now() + ACCOUNT_CACHE_TTL_MS,
  });
}
 
function getCachedAccount(accountId: string): AccountRecord | null {
  const cached = accountCache.get(accountId);
  if (!cached) {
    return null;
  }
 
  if (cached.expiresAt <= Date.now()) {
    accountCache.delete(accountId);
    return null;
  }
 
  return cloneAccountRecord(cached.value);
}
 
async function fetchAccountWithCache(
  db: DbClient,
  accountId: string
): Promise<{ account: AccountRecord | null; fromCache: boolean }> {
  const cached = getCachedAccount(accountId);
  if (cached) {
    return { account: cached, fromCache: true };
  }
 
  const record = await db.account.findFirst({
    where: { accountId },
    select: {
      id: true,
      accountId: true,
      accessToken: true,
      refreshToken: true,
      accessTokenExpiresAt: true,
      refreshTokenExpiresAt: true,
    },
  });
 
  if (!record) {
    return { account: null, fromCache: false };
  }
 
  const account = cloneAccountRecord(record as AccountRecord);
  storeAccountInCache(account);
  return { account, fromCache: false };
}
 
function clearAccountCacheEntries(accountId?: string): void {
  if (typeof accountId === "string") {
    accountCache.delete(accountId);
    return;
  }
 
  accountCache.clear();
}
function isInvalidGrantError(error: unknown): boolean {
  if (!(error instanceof Error)) {
    return false;
  }
 
  return error.message.toLowerCase().includes("invalid_grant");
}
 
/**
 * Creates a Hono middleware that validates Kick webhook requests, persists
 * validation failures, and enriches the context with the parsed webhook payload
 * and broadcaster authentication state.
 */
export function createKickWebhookValidationMiddleware<
  Environment extends {
    Bindings: Env;
    Variables: AppVariables;
  }
>(
  recordError: (
    env: Environment["Bindings"],
    entry: ErrorLogEntry
  ) => Promise<void>
): MiddlewareHandler<Environment> {
  return async (c, next) => {
    const steps = createStepLogger(LOG_PREFIX);
    const runStep = async <T>(
      label: string,
      action: () => Promise<T>,
      options: {
        startMeta?: Record<string, unknown>;
        completeMeta?: (result: T) => Record<string, unknown> | undefined;
      } = {}
    ): Promise<T> => {
      const handle = steps.start(label, options.startMeta);
      try {
        const result = await action();
        const successMeta = options.completeMeta?.(result);
        steps.success(handle, successMeta);
        return result;
      } catch (error) {
        steps.fail(handle, error);
        throw error;
      }
    };
 
    steps.note("Webhook received", {
      path: c.req.path,
      method: c.req.method,
      eventType: c.req.header("Kick-Event-Type") ?? null,
      messageId: c.req.header("Kick-Event-Message-Id") ?? null,
    });
 
    try {
      const result = await runStep(
        "Validate Kick webhook",
        () => validateKickWebhook(c.req.raw),
        {
          completeMeta: (payload) => ({
            knownType: payload.knownType,
            eventType: payload.eventType,
            messageId: payload.messageId,
          }),
        }
      );
      c.set("kickWebhook", result);
      steps.note("Webhook payload stored", { eventType: result.eventType });
 
      const broadcasterAuth = await runStep(
        "Resolve broadcaster auth",
        () => resolveBroadcasterAuth<Environment>(c, result, steps),
        {
          completeMeta: (auth) => ({
            accountId: auth?.accountId ?? null,
            hasAccessToken: Boolean(auth?.accessToken),
          }),
        }
      );
      c.set("kickBroadcasterAuth", broadcasterAuth);
      steps.note("Broadcaster auth stored", {
        registered: Boolean(broadcasterAuth),
      });
 
      await runStep("Invoke downstream handlers", () => next());
    } catch (error) {
      steps.note("Preparing failure context", {
        error:
          error instanceof Error
            ? `${error.name}: ${error.message}`
            : String(error),
        path: c.req.path,
      });
 
      await runStep("Record webhook failure", () =>
        recordError(c.env, {
          message:
            error instanceof Error ? error.message : "Unknown webhook error",
          status: error instanceof KickWebhookError ? error.status : 500,
          context: {
            path: c.req.path,
            eventType: c.req.header("Kick-Event-Type"),
            messageId: c.req.header("Kick-Event-Message-Id"),
          },
        })
      );
 
      if (error instanceof KickWebhookSignatureError) {
        console.warn("Rejected Kick webhook", { reason: error.message });
        steps.note("Responding with signature failure", {
          status: error.status,
        });
        return c.json({ error: "Unauthorized" }, error.status);
      }
 
      if (error instanceof KickWebhookError) {
        steps.note("Responding with webhook error", {
          status: error.status,
          reason: error.message,
        });
        return c.json({ error: error.message }, error.status);
      }
 
      console.error("Unexpected webhook failure", error);
      steps.note("Responding with unexpected error", { status: 500 });
      return c.json({ error: "Internal Server Error" }, 500);
    }
  };
}
 
/**
 * Resolves the broadcaster account associated with a validated webhook payload,
 * refreshing the access token when necessary.
 */
async function resolveBroadcasterAuth<
  Environment extends {
    Bindings: Env;
    Variables: AppVariables;
  }
>(
  c: Parameters<MiddlewareHandler<Environment>>[0],
  result: KickWebhookValidationResult,
  steps?: StepLogger
): Promise<KickBroadcasterAuth | null> {
  const idStep = steps?.start("Extract broadcaster account id");
  const broadcasterAccountId = extractBroadcasterAccountId(result);
  if (steps && idStep) {
    steps.success(idStep, {
      broadcasterAccountId: broadcasterAccountId ?? null,
    });
  }
  if (!broadcasterAccountId) {
    steps?.note("Broadcaster account id missing", {
      eventType: result.eventType,
    });
    return null;
  }
  steps?.note("Resolving broadcaster account", { broadcasterAccountId });
 
  const databaseUrl = c.env.DATABASE_URL;
  if (!databaseUrl) {
    steps?.note("Database binding missing");
    throw new Error("Missing DATABASE_URL binding");
  }
 
  const db = getDb(databaseUrl);
  const lookupStep = steps?.start("Lookup broadcaster account", {
    broadcasterAccountId,
  });
  const { account: fetchedAccount, fromCache } = await fetchAccountWithCache(
    db,
    broadcasterAccountId
  );
  console.log(
    "[account-lookup-result]",
    JSON.stringify({ account: fetchedAccount, fromCache })
  );
 
  if (steps && lookupStep) {
    steps.success(lookupStep, {
      found: Boolean(fetchedAccount),
      cacheHit: fromCache,
    });
  }
 
  let account = fetchedAccount;
 
  if (!account) {
    steps?.note("Broadcaster account not registered", {
      broadcasterAccountId,
    });
    return null;
  }
 
  const now = Date.now();
  const accessTokenExpiresAt = account.accessTokenExpiresAt
    ? new Date(account.accessTokenExpiresAt).getTime()
    : null;
  const shouldRefresh =
    !account.accessToken ||
    !accessTokenExpiresAt ||
    accessTokenExpiresAt - now <= TOKEN_REFRESH_THRESHOLD_MS;
 
  if (shouldRefresh) {
    if (!account.refreshToken) {
      steps?.note("Missing refresh token for broadcaster", {
        broadcasterAccountId,
      });
      throw new Error(
        `Kick broadcaster account ${account.accountId} is missing a refresh token`
      );
    }
 
    const clientId = c.env.KICK_CLIENT_ID;
    const clientSecret = c.env.KICK_CLIENT_SECRET;
    if (!clientId || !clientSecret) {
      steps?.note("Missing Kick OAuth client credentials", {
        hasClientId: Boolean(clientId),
        hasClientSecret: Boolean(clientSecret),
      });
      throw new Error("Missing Kick OAuth client credentials");
    }
 
    const expiresAtMeta =
      account.accessTokenExpiresAt == null
        ? null
        : account.accessTokenExpiresAt;
 
    let validationStep: StepHandle | undefined;
    let introspection: TokenIntrospectionResult | undefined;
    if (steps) {
      validationStep = steps.start("Validate refresh token", {
        broadcasterAccountId,
      });
    }
 
    try {
      introspection = await validateRefreshToken({
        refreshToken: account.refreshToken,
        clientId,
        clientSecret,
      });
 
      if (steps && validationStep) {
        const meta: Record<string, unknown> = {
          active: introspection.active,
        };
        if (typeof introspection.exp === "number") {
          meta.expiresAt = new Date(introspection.exp * 1000);
        }
        if (typeof introspection.token_type === "string") {
          meta.tokenType = introspection.token_type;
        }
        steps.success(validationStep, meta);
      }
    } catch (error) {
      if (steps && validationStep) {
        steps.fail(validationStep, error);
      }
    }
 
    if (introspection && !introspection.active) {
      const reason =
        typeof introspection.error_description === "string"
          ? introspection.error_description
          : typeof introspection.error === "string"
          ? introspection.error
          : "inactive";
      throw new Error(
        `Kick refresh token for account ${account.accountId} is not active (${reason})`
      );
    }
 
    let refreshStep: StepHandle | undefined;
    if (steps) {
      refreshStep = steps.start("Refresh broadcaster access token", {
        broadcasterAccountId,
        expiresAt: expiresAtMeta,
      });
    }
 
    let refreshed: RESTPostOAuth2RefreshTokenResult;
    try {
      refreshed = await refreshAccessToken({
        refreshToken: account.refreshToken,
        clientId,
        clientSecret,
      });
    } catch (error) {
      if (steps && refreshStep) {
        steps.fail(refreshStep, error);
      }
 
      if (isInvalidGrantError(error)) {
        steps?.note("Clearing invalid broadcaster tokens", {
          broadcasterAccountId,
        });
 
        await db.account.update({
          where: { id: account.id },
          data: {
            accessToken: null,
            accessTokenExpiresAt: null,
            refreshToken: null,
            refreshTokenExpiresAt: null,
          },
        });
 
        account.accessToken = null;
        account.refreshToken = null;
        account.accessTokenExpiresAt = null;
        account.refreshTokenExpiresAt = null;
 
        await invalidateAccountCache(db, account.accountId, steps);
 
        throw new Error(
          `Kick refresh token for account ${account.accountId} is invalid or expired`
        );
      }
 
      throw error;
    }
 
    const refreshedExpiresAt = new Date(
      Date.now() + refreshed.expires_in * 1000
    );
 
    await db.account.update({
      where: { id: account.id },
      data: {
        accessToken: refreshed.access_token,
        accessTokenExpiresAt: refreshedExpiresAt,
        refreshToken: refreshed.refresh_token ?? account.refreshToken,
      },
    });
 
    account.accessToken = refreshed.access_token;
    account.refreshToken = refreshed.refresh_token ?? account.refreshToken;
    account.accessTokenExpiresAt = refreshedExpiresAt;
 
    await invalidateAccountCache(db, account.accountId, steps);
    storeAccountInCache(account);
 
    if (steps && refreshStep) {
      steps.success(refreshStep, {
        expiresAt: refreshedExpiresAt,
      });
    }
  }
 
  return {
    accountId: account.accountId,
    accessToken: account.accessToken!,
  };
}
 
function extractBroadcasterAccountId(
  result: KickWebhookValidationResult
): string | null {
  if (!result.knownType) {
    return null;
  }
 
  const payload = result.payload;
 
  const broadcasterCandidate = normalizeAccountId(payload.broadcaster?.user_id);
  if (broadcasterCandidate) {
    return broadcasterCandidate;
  }
 
  if (
    typeof payload === "object" &&
    payload !== null &&
    "broadcaster_user_id" in payload
  ) {
    const candidate = normalizeAccountId(
      (payload as { broadcaster_user_id?: unknown }).broadcaster_user_id
    );
    if (candidate) {
      return candidate;
    }
  }
 
  return null;
}
 
function normalizeAccountId(value: unknown): string | null {
  if (typeof value === "number" && Number.isFinite(value)) {
    return String(value);
  }
 
  if (typeof value === "string" && value.trim().length > 0) {
    return value;
  }
 
  return null;
}
 
interface RefreshOptions {
  refreshToken: string;
  clientId: string;
  clientSecret: string;
}
 
type RefreshTokenValidationOptions = RefreshOptions & {
  tokenTypeHint?: "access_token" | "refresh_token";
};
 
type TokenIntrospectionResult = {
  active: boolean;
  scope?: string;
  token_type?: string;
  exp?: number;
  client_id?: string;
  sub?: string;
  error?: string;
  error_description?: string;
  [key: string]: unknown;
};
 
async function validateRefreshToken(
  options: RefreshTokenValidationOptions
): Promise<TokenIntrospectionResult> {
  const url = `${OAuth2AuthorizationUrl}${Routes.TokenIntrospect()}`;
  const params = new URLSearchParams({
    token: options.refreshToken,
    token_type_hint: options.tokenTypeHint ?? "refresh_token",
    client_id: options.clientId,
    client_secret: options.clientSecret,
  });
 
  let encodedCredentials: string | undefined;
  if (typeof btoa === "function") {
    encodedCredentials = btoa(`${options.clientId}:${options.clientSecret}`);
  } else if (typeof Buffer !== "undefined") {
    encodedCredentials = Buffer.from(
      `${options.clientId}:${options.clientSecret}`,
      "utf8"
    ).toString("base64");
  }
 
  const headers: Record<string, string> = {
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json",
  };
 
  if (encodedCredentials) {
    headers.Authorization = `Basic ${encodedCredentials}`;
  }
 
  const response = await fetch(url, {
    method: "POST",
    headers,
    body: params.toString(),
  });
 
  const rawBody = await safeReadBody(response);
 
  if (!response.ok) {
    const detail = extractKickErrorDetail(rawBody);
    throw new Error(
      `Kick token introspection failed (${response.status}): ${detail}`
    );
  }
 
  if (!rawBody || rawBody === "<no response body>") {
    throw new Error("Kick token introspection returned an empty response");
  }
 
  let parsed: unknown;
  try {
    parsed = JSON.parse(rawBody) as TokenIntrospectionResult;
  } catch {
    throw new Error("Kick token introspection returned malformed JSON");
  }
 
  if (
    typeof parsed !== "object" ||
    parsed === null ||
    typeof (parsed as TokenIntrospectionResult).active !== "boolean"
  ) {
    throw new Error("Kick token introspection returned unexpected payload");
  }
 
  return parsed as TokenIntrospectionResult;
}
 
function extractKickErrorDetail(raw: string): string {
  if (!raw) {
    return "<empty response body>";
  }
 
  if (raw === "<no response body>") {
    return raw;
  }
 
  try {
    const parsed = JSON.parse(raw) as {
      error?: unknown;
      error_description?: unknown;
    };
 
    if (typeof parsed === "object" && parsed !== null) {
      if (typeof parsed.error_description === "string") {
        return parsed.error_description;
      }
 
      if (typeof parsed.error === "string") {
        return parsed.error;
      }
    }
  } catch {
    // fall through to raw output
  }
 
  return raw;
}
 
async function refreshAccessToken(
  options: RefreshOptions
): Promise<RESTPostOAuth2RefreshTokenResult> {
  const url = `${OAuth2AuthorizationUrl}${Routes.OAuthRefresh()}`;
  const params = new URLSearchParams({
    grant_type: "refresh_token",
    client_id: options.clientId,
    client_secret: options.clientSecret,
    refresh_token: options.refreshToken,
  });
 
  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    body: params.toString(),
  });
 
  if (!response.ok) {
    const detail = await safeReadBody(response);
    throw new Error(
      `Failed to refresh Kick access token (${response.status}): ${detail}`
    );
  }
 
  const data = (await response.json()) as RESTPostOAuth2RefreshTokenResult;
 
  if (!data?.access_token) {
    throw new Error("Kick refresh response did not include an access_token");
  }
 
  return data;
}
 
async function safeReadBody(response: Response): Promise<string> {
  try {
    return await response.text();
  } catch (error) {
    console.error("Failed to read Kick refresh response body", error);
    return "<no response body>";
  }
}
 
export const __test = {
  resolveBroadcasterAuth,
  refreshAccessToken,
  validateRefreshToken,
  extractBroadcasterAccountId,
  getAccountCacheTag,
  clearAccountCacheEntries,
} as const;