55 lines
1.7 KiB
TypeScript
55 lines
1.7 KiB
TypeScript
import { BadRequestException } from '@nestjs/common';
|
|
import { isValid, parseISO } from 'date-fns';
|
|
|
|
export type Cursor = {
|
|
scope: string;
|
|
created_at: string;
|
|
id: string;
|
|
};
|
|
|
|
// Format check for the canonical API shape: `Date.prototype.toISOString()` with
|
|
// optional fractional seconds. Explicit ranges reject values such as 24:00:00.
|
|
// Calendar validity (2026-02-31, 2025-02-29, 2026-04-31) is checked by
|
|
// date-fns `parseISO`, which refuses impossible dates that the platform parser
|
|
// would silently roll over into another day.
|
|
const CURSOR_TIMESTAMP =
|
|
/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?Z$/u;
|
|
|
|
export function encodeCursor(cursor: Cursor): string {
|
|
return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');
|
|
}
|
|
|
|
export function decodeCursor(value: string, expectedScope: string): Cursor {
|
|
try {
|
|
const parsed: unknown = JSON.parse(
|
|
Buffer.from(value, 'base64url').toString('utf8'),
|
|
);
|
|
if (
|
|
typeof parsed !== 'object' ||
|
|
parsed === null ||
|
|
!('scope' in parsed) ||
|
|
!('created_at' in parsed) ||
|
|
!('id' in parsed) ||
|
|
typeof parsed.scope !== 'string' ||
|
|
typeof parsed.created_at !== 'string' ||
|
|
typeof parsed.id !== 'string' ||
|
|
parsed.scope !== expectedScope ||
|
|
!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(
|
|
parsed.id,
|
|
) ||
|
|
!CURSOR_TIMESTAMP.test(parsed.created_at)
|
|
)
|
|
throw new Error('invalid cursor');
|
|
const instant = parseISO(parsed.created_at);
|
|
if (!isValid(instant)) throw new Error('invalid cursor');
|
|
|
|
return {
|
|
scope: parsed.scope,
|
|
created_at: instant.toISOString(),
|
|
id: parsed.id,
|
|
};
|
|
} catch {
|
|
throw new BadRequestException('Invalid cursor');
|
|
}
|
|
}
|