import { createHmac, timingSafeEqual } from 'node:crypto';

// Short-lived, job-scoped token authorizing a browser terminal connection.
// Minted server-side by the Next app (which has verified job ownership) and
// verified here so the browser never sees the shared worker secret. Format:
//   `${expiresAtMs}.${jobId}.${hmacSha256Hex}`
const signature = (payload: string, secret: string) =>
  createHmac('sha256', secret).update(payload).digest('hex');

export const verifyTerminalToken = (
  token: string,
  jobId: string,
  secret: string,
): boolean => {
  if (!token || !secret) return false;
  const parts = token.split('.');
  if (parts.length !== 3) return false;
  const [expRaw, tokenJobId, provided] = parts;
  if (tokenJobId !== jobId) return false;
  const exp = Number.parseInt(expRaw ?? '', 10);
  if (!Number.isFinite(exp) || Date.now() > exp) return false;
  const expected = signature(`${expRaw}.${tokenJobId}`, secret);
  const providedBuf = Buffer.from(provided ?? '', 'hex');
  const expectedBuf = Buffer.from(expected, 'hex');
  return (
    providedBuf.length === expectedBuf.length &&
    timingSafeEqual(providedBuf, expectedBuf)
  );
};
