119 lines
4.3 KiB
TypeScript
119 lines
4.3 KiB
TypeScript
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
|
|
import { loadRequiredWebConfig } from "@hivegrid/config";
|
|
|
|
const STATE_TTL_MS = 10 * 60 * 1_000;
|
|
const MAX_FUTURE_SKEW_MS = 30_000;
|
|
const MAX_STATE_LENGTH = 4_096;
|
|
const PAYLOAD_VERSION = "v1";
|
|
|
|
export interface AircallOAuthStatePayload {
|
|
readonly tenantId: string;
|
|
readonly tenantSlug: string;
|
|
readonly userId: string;
|
|
readonly connectionId: string;
|
|
readonly nonce: string;
|
|
/** Epoch milliseconds. */
|
|
readonly createdAt: number;
|
|
}
|
|
|
|
export type VerifyAircallOAuthStateResult =
|
|
| { readonly ok: true; readonly payload: AircallOAuthStatePayload }
|
|
| { readonly ok: false; readonly reason: "malformed" | "bad-signature" | "expired" };
|
|
|
|
type StateOptions = {
|
|
readonly now?: () => number;
|
|
readonly nonce?: () => string;
|
|
readonly secret?: string;
|
|
};
|
|
|
|
/** Sign tenant, initiating user and the reserved Aircall slot for ten minutes. */
|
|
export function signAircallOAuthState(
|
|
input: Pick<AircallOAuthStatePayload, "tenantId" | "tenantSlug" | "userId" | "connectionId">,
|
|
options: StateOptions = {}
|
|
): string {
|
|
const payload: AircallOAuthStatePayload = {
|
|
...input,
|
|
nonce: options.nonce ? options.nonce() : randomBytes(24).toString("base64url"),
|
|
createdAt: options.now ? options.now() : Date.now(),
|
|
};
|
|
if (!isValidPayload(payload)) {
|
|
throw new Error("Aircall OAuth state input is invalid");
|
|
}
|
|
const body = Buffer.from(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }), "utf8").toString("base64url");
|
|
return `${body}.${sign(body, stateSecret(options.secret))}`;
|
|
}
|
|
|
|
export function verifyAircallOAuthState(state: string, options: Pick<StateOptions, "now" | "secret"> = {}): VerifyAircallOAuthStateResult {
|
|
if (!state || state.length > MAX_STATE_LENGTH) return { ok: false, reason: "malformed" };
|
|
const separator = state.lastIndexOf(".");
|
|
if (separator <= 0 || separator === state.length - 1) return { ok: false, reason: "malformed" };
|
|
|
|
const body = state.slice(0, separator);
|
|
const receivedSignature = state.slice(separator + 1);
|
|
let expectedSignature: string;
|
|
try {
|
|
expectedSignature = sign(body, stateSecret(options.secret));
|
|
} catch {
|
|
return { ok: false, reason: "malformed" };
|
|
}
|
|
const received = Buffer.from(receivedSignature, "utf8");
|
|
const expected = Buffer.from(expectedSignature, "utf8");
|
|
if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
|
|
return { ok: false, reason: "bad-signature" };
|
|
}
|
|
|
|
let decoded: { readonly v?: unknown; readonly p?: unknown };
|
|
try {
|
|
decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8")) as { readonly v?: unknown; readonly p?: unknown };
|
|
} catch {
|
|
return { ok: false, reason: "malformed" };
|
|
}
|
|
if (decoded.v !== PAYLOAD_VERSION || !isValidPayload(decoded.p)) {
|
|
return { ok: false, reason: "malformed" };
|
|
}
|
|
|
|
const now = options.now ? options.now() : Date.now();
|
|
const age = now - decoded.p.createdAt;
|
|
const tooOld = age > STATE_TTL_MS;
|
|
const tooFarInFuture = age < -MAX_FUTURE_SKEW_MS;
|
|
if (tooOld || tooFarInFuture) {
|
|
return { ok: false, reason: "expired" };
|
|
}
|
|
return { ok: true, payload: decoded.p };
|
|
}
|
|
|
|
function stateSecret(override?: string): string {
|
|
if (override) return override;
|
|
const config = loadRequiredWebConfig();
|
|
const secret = config.cryptoSecret || config.sessionSecret;
|
|
if (!secret) throw new Error("Aircall OAuth state secret is missing");
|
|
return secret;
|
|
}
|
|
|
|
function sign(body: string, secret: string): string {
|
|
return createHmac("sha256", secret).update(body).digest("base64url");
|
|
}
|
|
|
|
function isValidPayload(value: unknown): value is AircallOAuthStatePayload {
|
|
if (!isRecord(value)) return false;
|
|
return (
|
|
boundedString(value.tenantId, 256) &&
|
|
boundedString(value.tenantSlug, 256) &&
|
|
boundedString(value.userId, 256) &&
|
|
boundedString(value.connectionId, 256) &&
|
|
boundedString(value.nonce, 256) &&
|
|
typeof value.createdAt === "number" &&
|
|
Number.isSafeInteger(value.createdAt) &&
|
|
value.createdAt >= 0
|
|
);
|
|
}
|
|
|
|
function boundedString(value: unknown, maxLength: number): value is string {
|
|
return typeof value === "string" && value.length > 0 && value.length <= maxLength;
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|