A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api): add operator pass pricing, schedule and entitlement
Hampusab1049d89ccc
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.ts b/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.tsnew file mode 100644index 000000000..cb9f6a65b--- /dev/null+++ b/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.ts@@ -0,0 +1,151 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {UserID} from '@app/api/BrandedTypes';+import type {OperatorPassRemovalRow, OperatorPassRow} from '@app/api/database/types/OperatorPassTypes';+import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';+import {Logger} from '@app/api/Logger';+import type {User} from '@app/api/models/User';+import type {OperatorPassRepository} from '@app/api/operator_pass/OperatorPassRepository';+import {operatorPassNow} from '@app/api/operator_pass/OperatorPassSchedule';+import {+ isOperatorPassBadgeHidden,+ isOperatorPassCountHidden,+ isOperatorPassTimestampHidden,+} from '@app/api/user/profile_badges/PremiumBadgeMasking';+import type {UserRepository} from '@app/api/user/repositories/UserRepository';+import {mapUserToPrivateResponse} from '@app/api/user/UserMappers';+import {+ OPERATOR_PASS_SOURCES,+ type OperatorPassSource,+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';+import type {UserPrivateResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';++export interface OperatorPassHolder {+ since: Date;+ source: OperatorPassSource;+ count: number;+}++export interface OperatorPassEntitlementState {+ pass: OperatorPassRow | null;+ removal: OperatorPassRemovalRow | null;+}++function parseOperatorPassSource(value: string): OperatorPassSource {+ return (OPERATOR_PASS_SOURCES as ReadonlyArray<string>).includes(value) ? (value as OperatorPassSource) : 'admin';+}++export function isOperatorPassRemovalActive(+ removal: OperatorPassRemovalRow | null,+ now: Date = operatorPassNow(),+): boolean {+ if (removal?.removal_state !== 'removed') {+ return false;+ }+ return removal.removed_until == null || removal.removed_until.getTime() > now.getTime();+}++export function isOperatorPassPermanentlyRemoved(removal: OperatorPassRemovalRow | null): boolean {+ return removal?.removal_state === 'removed' && removal.removed_until == null;+}++export function resolveOperatorPassHolder(+ state: OperatorPassEntitlementState,+ now: Date = operatorPassNow(),+): OperatorPassHolder | null {+ if (isOperatorPassRemovalActive(state.removal, now)) {+ return null;+ }+ const {pass} = state;+ if (!pass || pass.paused_at != null) {+ return null;+ }+ return {+ since: pass.granted_at,+ source: parseOperatorPassSource(pass.source),+ count: Math.max(1, pass.pass_count ?? 1),+ };+}++export function isOperatorPassEntitled(state: OperatorPassEntitlementState, now?: Date): boolean {+ return resolveOperatorPassHolder(state, now) !== null;+}++export async function loadOperatorPassEntitlementState(+ repository: OperatorPassRepository,+ userId: UserID,+): Promise<OperatorPassEntitlementState> {+ const [pass, removal] = await Promise.all([repository.findOperatorPass(userId), repository.findRemoval(userId)]);+ return {pass, removal};+}++export async function dispatchOperatorPassUserUpdate(+ deps: {repository: OperatorPassRepository; userRepository: UserRepository; gatewayService: IGatewayService},+ userId: UserID,+): Promise<void> {+ try {+ const [user, state] = await Promise.all([+ deps.userRepository.findUnique(userId),+ loadOperatorPassEntitlementState(deps.repository, userId),+ ]);+ if (!user) return;+ const data = {+ ...mapUserToPrivateResponse(user),+ ...operatorPassPrivateFields(user, resolveOperatorPassHolder(state)),+ };+ await deps.gatewayService.dispatchPresence({userId, event: 'USER_UPDATE', data});+ } catch (error) {+ Logger.warn({userId, error}, 'Failed to dispatch the Operator Pass user update');+ }+}++export function operatorPassPrivateFields(+ user: User,+ holder: OperatorPassHolder | null,+): Pick<+ UserPrivateResponse,+ | 'operator_pass_since'+ | 'operator_pass_badge_hidden'+ | 'operator_pass_badge_timestamp_hidden'+ | 'operator_pass_badge_count_hidden'+> {+ return {+ operator_pass_since: holder?.since.toISOString() ?? null,+ operator_pass_badge_hidden: isOperatorPassBadgeHidden(user.premiumFlags),+ operator_pass_badge_timestamp_hidden: isOperatorPassTimestampHidden(user.premiumFlags),+ operator_pass_badge_count_hidden: isOperatorPassCountHidden(user.premiumFlags),+ };+}++export function profileOperatorPassSince(params: {+ user: User;+ state: OperatorPassEntitlementState;+ viewerId: UserID;+ restrictProfile: boolean;+}): Date | null {+ const {user, state, viewerId, restrictProfile} = params;+ const isOwner = viewerId === user.id;+ if (user.isBot || (!isOwner && restrictProfile)) {+ return null;+ }+ const holder = resolveOperatorPassHolder(state);+ if (+ !holder ||+ (!isOwner && (isOperatorPassBadgeHidden(user.premiumFlags) || isOperatorPassTimestampHidden(user.premiumFlags)))+ ) {+ return null;+ }+ return holder.since;+}++export class OperatorPassEntitlementService {+ constructor(readonly repository: OperatorPassRepository) {}++ async loadState(userId: UserID): Promise<OperatorPassEntitlementState> {+ return loadOperatorPassEntitlementState(this.repository, userId);+ }++ async getHolder(user: User): Promise<OperatorPassHolder | null> {+ return resolveOperatorPassHolder(await this.loadState(user.id));+ }+}diff --git a/fluxer_api/src/api/operator_pass/OperatorPassPrices.ts b/fluxer_api/src/api/operator_pass/OperatorPassPrices.tsnew file mode 100644index 000000000..aab7a0c9a--- /dev/null+++ b/fluxer_api/src/api/operator_pass/OperatorPassPrices.ts@@ -0,0 +1,267 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ OPERATOR_PASS_CURRENCIES,+ OPERATOR_PASS_MAX_QUANTITY,+ type OperatorPassCurrency,+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';++export type OperatorPassPriceTable = Readonly<Record<OperatorPassCurrency, number>>;++export interface OperatorPassReleaseListWindow {+ cutoffAt: Date;+ publishBy: Date;+}++export type OperatorPassReleaseListTable = Readonly<Record<number, OperatorPassReleaseListWindow>>;++interface OperatorPassWithdrawalCountryRule {+ days: number;+ enabled: boolean;+}++export type OperatorPassWithdrawalCountryTable = Readonly<Record<string, OperatorPassWithdrawalCountryRule>>;++export const OPERATOR_PASS_WITHDRAWAL_RULE_VERSION = 'withdrawal-countries-2026-10-15';++const OPERATOR_PASS_DEFAULT_TRANSFER_LOCK_HOURS = 72;++const DEFAULT_WITHDRAWAL_COUNTRIES: OperatorPassWithdrawalCountryTable = {BR: {days: 7, enabled: true}};++const CURRENCY_WITHDRAWAL_COUNTRY: Readonly<Partial<Record<string, string>>> = {BRL: 'BR'};++export const OPERATOR_PASS_EARLY_BIRD_PRICES_MINOR: OperatorPassPriceTable = {+ USD: 19900,+ EUR: 19900,+ BRL: 102000,+ DKK: 149000,+ INR: 1910000,+ NOK: 215000,+ PLN: 76000,+ SEK: 225000,+ TRY: 971000,+};++function getOperatorPassStandardPriceEnvName(currency: OperatorPassCurrency): string {+ return `FLUXER_OPERATOR_PASS_STANDARD_PRICE_${currency}`;+}++export function parseOperatorPassStandardPrices(+ source: Partial<Record<string, number>> | undefined,+): OperatorPassPriceTable | null {+ const missing = OPERATOR_PASS_CURRENCIES.filter((currency) => source?.[currency.toLowerCase()] === undefined);+ if (missing.length === OPERATOR_PASS_CURRENCIES.length) {+ return null;+ }+ if (missing.length > 0) {+ throw new Error(+ `${missing.map(getOperatorPassStandardPriceEnvName).join(', ')} must be set, the standard price needs every currency or none`,+ );+ }+ const prices = {} as Record<OperatorPassCurrency, number>;+ for (const currency of OPERATOR_PASS_CURRENCIES) {+ const amount = source?.[currency.toLowerCase()];+ if (+ typeof amount !== 'number' ||+ !Number.isSafeInteger(amount) ||+ amount <= OPERATOR_PASS_EARLY_BIRD_PRICES_MINOR[currency]+ ) {+ throw new Error(+ `${getOperatorPassStandardPriceEnvName(currency)} must be a whole amount in minor units above the early bird price`,+ );+ }+ prices[currency] = amount;+ }+ return prices;+}++function defaultReleaseListWindow(year: number): OperatorPassReleaseListWindow {+ return {+ cutoffAt: new Date(Date.UTC(year + 1, 0, 1) - 1),+ publishBy: new Date(Date.UTC(year + 1, 3, 1) - 1),+ };+}++export function parseOperatorPassReleaseLists(source: string | undefined): OperatorPassReleaseListTable {+ const trimmed = (source ?? '').trim();+ if (trimmed.length === 0) {+ return {};+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ throw new Error(+ 'FLUXER_OPERATOR_PASS_RELEASE_LISTS must be JSON such as {"2026":{"cutoff":"2026-12-15T23:59:59Z"}}',+ );+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('FLUXER_OPERATOR_PASS_RELEASE_LISTS must be a JSON object keyed by year');+ }+ const table: Record<number, OperatorPassReleaseListWindow> = {};+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {+ const year = Number(key);+ if (!Number.isInteger(year) || year < 2026 || year > 9999) {+ throw new Error(`FLUXER_OPERATOR_PASS_RELEASE_LISTS has an invalid year ${key}`);+ }+ const entry = (value ?? {}) as {cutoff?: unknown; publish_by?: unknown};+ const fallback = defaultReleaseListWindow(year);+ const cutoffAt = typeof entry.cutoff === 'string' ? new Date(entry.cutoff) : fallback.cutoffAt;+ const publishBy = typeof entry.publish_by === 'string' ? new Date(entry.publish_by) : fallback.publishBy;+ if (Number.isNaN(cutoffAt.getTime()) || Number.isNaN(publishBy.getTime())) {+ throw new Error(`FLUXER_OPERATOR_PASS_RELEASE_LISTS has an invalid date for ${year}`);+ }+ if (cutoffAt.getTime() > fallback.cutoffAt.getTime()) {+ throw new Error(+ `FLUXER_OPERATOR_PASS_RELEASE_LISTS cutoff for ${year} must be no later than 31 December ${year}`,+ );+ }+ if (publishBy.getTime() > fallback.publishBy.getTime() || publishBy.getTime() < cutoffAt.getTime()) {+ throw new Error(+ `FLUXER_OPERATOR_PASS_RELEASE_LISTS publish_by for ${year} must be after the cutoff and no later than 31 March ${year + 1}`,+ );+ }+ table[year] = {cutoffAt, publishBy};+ }+ return table;+}++export function getOperatorPassReleaseListWindow(+ table: OperatorPassReleaseListTable,+ year: number,+): OperatorPassReleaseListWindow {+ return table[year] ?? defaultReleaseListWindow(year);+}++export function parseOperatorPassTransferLockHours(value: number | undefined): number {+ if (value === undefined) {+ return OPERATOR_PASS_DEFAULT_TRANSFER_LOCK_HOURS;+ }+ if (!Number.isInteger(value) || value < 0 || value > 24 * 90) {+ throw new Error('FLUXER_OPERATOR_PASS_TRANSFER_LOCK_HOURS must be a whole number of hours between 0 and 2160');+ }+ return value;+}++export function parseOperatorPassWithdrawalCountries(source: string | undefined): OperatorPassWithdrawalCountryTable {+ const trimmed = (source ?? '').trim();+ if (trimmed.length === 0) {+ return DEFAULT_WITHDRAWAL_COUNTRIES;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ throw new Error('FLUXER_OPERATOR_PASS_WITHDRAWAL_COUNTRIES must be JSON such as {"BR":{"days":7,"enabled":true}}');+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('FLUXER_OPERATOR_PASS_WITHDRAWAL_COUNTRIES must be a JSON object keyed by country code');+ }+ const table: Record<string, OperatorPassWithdrawalCountryRule> = {};+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {+ const country = key.trim().toUpperCase();+ const rule = (value ?? {}) as {days?: unknown; enabled?: unknown};+ if (+ !/^[A-Z]{2}$/u.test(country) ||+ typeof rule.days !== 'number' ||+ !Number.isInteger(rule.days) ||+ rule.days < 1 ||+ rule.days > 90+ ) {+ throw new Error(`FLUXER_OPERATOR_PASS_WITHDRAWAL_COUNTRIES has an invalid rule for ${key}`);+ }+ table[country] = {days: rule.days, enabled: rule.enabled !== false};+ }+ return table;+}++const OPERATOR_PASS_LOCALIZED_CURRENCIES: ReadonlyArray<OperatorPassCurrency> = OPERATOR_PASS_CURRENCIES.filter(+ (currency) => currency !== 'USD' && currency !== 'EUR',+);++export function resolveOperatorPassDisabledCurrencies(+ enabled: Partial<Record<string, boolean>> | undefined,+ stoppedCountries: ReadonlySet<string>,+): ReadonlySet<OperatorPassCurrency> {+ const disabled = new Set<OperatorPassCurrency>();+ for (const currency of OPERATOR_PASS_LOCALIZED_CURRENCIES) {+ const country = CURRENCY_WITHDRAWAL_COUNTRY[currency];+ if (enabled?.[currency.toLowerCase()] === false || (country !== undefined && stoppedCountries.has(country))) {+ disabled.add(currency);+ }+ }+ return disabled;+}++const OPERATOR_PASS_DEFAULT_MAX_QUANTITY = 25;++export function parseOperatorPassMaxQuantity(value: number | undefined): number {+ if (value === undefined) {+ return OPERATOR_PASS_DEFAULT_MAX_QUANTITY;+ }+ if (!Number.isInteger(value) || value < 1 || value > OPERATOR_PASS_MAX_QUANTITY) {+ throw new Error(`FLUXER_OPERATOR_PASS_MAX_QUANTITY must be a whole number from 1 to ${OPERATOR_PASS_MAX_QUANTITY}`);+ }+ return value;+}++export const OPERATOR_PASS_DEFAULT_WALL_TIER_MINIMUMS: ReadonlyArray<number> = [1, 2, 5, 10];++export function parseOperatorPassWallTiers(source: string | undefined): ReadonlyArray<number> {+ const trimmed = (source ?? '').trim();+ if (trimmed.length === 0) {+ return OPERATOR_PASS_DEFAULT_WALL_TIER_MINIMUMS;+ }+ const minimums = trimmed.split(',').map((value) => Number(value.trim()));+ const valid =+ minimums[0] === 1 &&+ minimums.every((value, index) => Number.isSafeInteger(value) && (index === 0 || value > minimums[index - 1]!));+ if (!valid) {+ throw new Error(+ 'FLUXER_OPERATOR_PASS_WALL_TIERS must be rising whole numbers of passes starting at 1, such as 1,2,5,10',+ );+ }+ return minimums;+}++export function getOperatorPassWallTier(count: number, minimums: ReadonlyArray<number>): number {+ let tier = 1;+ for (const [index, minimum] of minimums.entries()) {+ if (count >= minimum) tier = index + 1;+ }+ return tier;+}++export function parseOperatorPassStoppedCountries(source: string | undefined): ReadonlySet<string> {+ const countries = (source ?? '')+ .split(',')+ .map((value) => value.trim().toUpperCase())+ .filter((value) => value.length > 0);+ for (const country of countries) {+ if (!/^[A-Z]{2}$/u.test(country)) {+ throw new Error(`FLUXER_OPERATOR_PASS_STOPPED_COUNTRIES has an invalid country code ${country}`);+ }+ }+ return new Set(countries);+}++export interface OperatorPassWithdrawalRuleMatch {+ country: string;+ days: number;+}++export function resolveOperatorPassWithdrawalRule(+ table: OperatorPassWithdrawalCountryTable,+ countries: ReadonlyArray<string | null | undefined>,+ currency: string | null | undefined,+): OperatorPassWithdrawalRuleMatch | null {+ const candidates = [...countries, currency ? CURRENCY_WITHDRAWAL_COUNTRY[currency.toUpperCase()] : null];+ for (const candidate of candidates) {+ const country = candidate?.trim().toUpperCase();+ const rule = country ? table[country] : undefined;+ if (country && rule?.enabled) {+ return {country, days: rule.days};+ }+ }+ return null;+}diff --git a/fluxer_api/src/api/operator_pass/OperatorPassSchedule.ts b/fluxer_api/src/api/operator_pass/OperatorPassSchedule.tsnew file mode 100644index 000000000..07705a398--- /dev/null+++ b/fluxer_api/src/api/operator_pass/OperatorPassSchedule.ts@@ -0,0 +1,252 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createHmac, timingSafeEqual} from 'node:crypto';+import {Config} from '@app/api/Config';+import type {OperatorPassConfig} from '@app/api/config/APIConfig';+import {OPERATOR_PASS_EARLY_BIRD_PRICES_MINOR} from '@app/api/operator_pass/OperatorPassPrices';+import {deriveOperatorPassSecret, OPERATOR_PASS_QUOTE_SECRET_LABEL} from '@app/api/operator_pass/OperatorPassSecrets';+import {getEnvCurrencyPreferences} from '@app/api/utils/CurrencyUtils';+import {+ OPERATOR_PASS_CURRENCIES,+ OPERATOR_PASS_PHASES,+ type OperatorPassCurrency,+ type OperatorPassPhase,+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';+import {ms} from 'itty-time';++export type OperatorPassSchedule = Pick<+ OperatorPassConfig,+ 'saleOpensAt' | 'priceRisesAt' | 'graceMs' | 'clockOffsetMs' | 'standardPricesMinor'+>;++export type OperatorPassPricedPhase = Exclude<OperatorPassPhase, 'waitlist'>;++const STRIPE_CHECKOUT_MIN_EXPIRY_MS = ms('30 minutes');+const STRIPE_CHECKOUT_MAX_EXPIRY_MS = ms('24 hours');+const STRIPE_CHECKOUT_EXPIRY_MARGIN_MS = ms('1 minute');++const QUOTE_VERSION = 2;+const QUOTE_MAX_LENGTH = 1024;+const USER_ID_PATTERN = /^\d{1,20}$/u;++export function getOperatorPassSchedule(): OperatorPassSchedule {+ return Config.operatorPass;+}++export function operatorPassNow(+ schedule: OperatorPassSchedule = getOperatorPassSchedule(),+ realNowMs = Date.now(),+): Date {+ return new Date(realNowMs + schedule.clockOffsetMs);+}++export function getOperatorPassPhase(+ now: Date,+ schedule: OperatorPassSchedule = getOperatorPassSchedule(),+): OperatorPassPhase {+ const at = now.getTime();+ if (!schedule.saleOpensAt || !schedule.priceRisesAt || at < schedule.saleOpensAt.getTime()) {+ return 'waitlist';+ }+ if (at < schedule.priceRisesAt.getTime()) {+ return 'early_bird';+ }+ return 'standard';+}++function getOperatorPassPricedPhase(phase: OperatorPassPhase): OperatorPassPricedPhase {+ return phase === 'standard' ? 'standard' : 'early_bird';+}++export function getOperatorPassPriceMinor(+ phase: OperatorPassPhase,+ currency: OperatorPassCurrency,+ schedule: OperatorPassSchedule = getOperatorPassSchedule(),+): number {+ if (getOperatorPassPricedPhase(phase) === 'standard' && schedule.standardPricesMinor) {+ return schedule.standardPricesMinor[currency];+ }+ return OPERATOR_PASS_EARLY_BIRD_PRICES_MINOR[currency];+}++export function isOperatorPassCurrency(value: string): value is OperatorPassCurrency {+ return (OPERATOR_PASS_CURRENCIES as ReadonlyArray<string>).includes(value);+}++export function resolveOperatorPassCurrency(+ countryCode: string | null | undefined,+ disabled: ReadonlySet<OperatorPassCurrency> = Config.operatorPass.disabledCurrencies,+): OperatorPassCurrency {+ return (+ getEnvCurrencyPreferences(countryCode).find(+ (currency): currency is OperatorPassCurrency => isOperatorPassCurrency(currency) && !disabled.has(currency),+ ) ?? 'USD'+ );+}++export interface OperatorPassQuote {+ phase: OperatorPassPhase;+ currency: OperatorPassCurrency;+ amountMinor: number;+ issuedAtMs: number;+ userId: string | null;+}++function getQuoteSecret(): string {+ return deriveOperatorPassSecret(OPERATOR_PASS_QUOTE_SECRET_LABEL);+}++function signQuotePayload(payload: string, secret: string): string {+ return createHmac('sha256', secret).update(payload).digest('base64url');+}++export function signOperatorPassQuote(quote: OperatorPassQuote, secret: string = getQuoteSecret()): string {+ const payload = Buffer.from(+ JSON.stringify({+ v: QUOTE_VERSION,+ p: quote.phase,+ c: quote.currency,+ a: quote.amountMinor,+ t: quote.issuedAtMs,+ u: quote.userId,+ }),+ 'utf8',+ ).toString('base64url');+ return `${payload}.${signQuotePayload(payload, secret)}`;+}++export interface OperatorPassQuoteRequest {+ now: Date;+ phase: OperatorPassPhase;+ currency: OperatorPassCurrency;+ amountMinor: number;+ userId: string | null;+}++export function issueOperatorPassQuote(request: OperatorPassQuoteRequest, secret: string = getQuoteSecret()): string {+ return signOperatorPassQuote(+ {+ phase: request.phase,+ currency: request.currency,+ amountMinor: request.amountMinor,+ issuedAtMs: request.now.getTime(),+ userId: request.userId,+ },+ secret,+ );+}++function parseQuotePayload(payload: string): OperatorPassQuote | null {+ let decoded: unknown;+ try {+ decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ } catch {+ return null;+ }+ if (typeof decoded !== 'object' || decoded === null || Array.isArray(decoded)) {+ return null;+ }+ const {v, p, c, a, t, u} = decoded as Record<string, unknown>;+ if (v !== QUOTE_VERSION) return null;+ if (typeof p !== 'string' || !(OPERATOR_PASS_PHASES as ReadonlyArray<string>).includes(p)) return null;+ if (typeof c !== 'string' || !isOperatorPassCurrency(c)) return null;+ if (typeof a !== 'number' || !Number.isSafeInteger(a) || a <= 0) return null;+ if (typeof t !== 'number' || !Number.isSafeInteger(t) || t < 0) return null;+ if (u !== null && (typeof u !== 'string' || !USER_ID_PATTERN.test(u))) return null;+ return {phase: p as OperatorPassPhase, currency: c, amountMinor: a, issuedAtMs: t, userId: u};+}++export function verifyOperatorPassQuote(token: string, secret: string = getQuoteSecret()): OperatorPassQuote | null {+ if (token.length === 0 || token.length > QUOTE_MAX_LENGTH) {+ return null;+ }+ const parts = token.split('.');+ if (parts.length !== 2) {+ return null;+ }+ const [payload, signature] = parts;+ const expected = Buffer.from(signQuotePayload(payload, secret), 'utf8');+ const provided = Buffer.from(signature, 'utf8');+ if (expected.length !== provided.length || !timingSafeEqual(expected, provided)) {+ return null;+ }+ return parseQuotePayload(payload);+}++export interface OperatorPassCheckoutPriceInput {+ now: Date;+ schedule?: OperatorPassSchedule;+ currency: OperatorPassCurrency;+ userId: string | null;+ quote: string | null | undefined;+ secret?: string;+}++export interface OperatorPassCheckoutPrice {+ phase: OperatorPassPhase;+ pricedPhase: OperatorPassPricedPhase;+ amountMinor: number;+ quoteHonored: boolean;+ priceChanged: boolean;+}++function isQuoteHonored(+ quote: OperatorPassQuote,+ input: OperatorPassCheckoutPriceInput,+ schedule: OperatorPassSchedule,+ phase: OperatorPassPhase,+): boolean {+ if (!schedule.priceRisesAt) {+ return false;+ }+ const risesAt = schedule.priceRisesAt.getTime();+ return (+ phase === 'standard' &&+ quote.phase === 'early_bird' &&+ quote.issuedAtMs < risesAt &&+ input.now.getTime() < risesAt + schedule.graceMs &&+ quote.currency === input.currency &&+ quote.amountMinor === OPERATOR_PASS_EARLY_BIRD_PRICES_MINOR[input.currency]+ );+}++export function resolveOperatorPassCheckoutPrice(input: OperatorPassCheckoutPriceInput): OperatorPassCheckoutPrice {+ const schedule = input.schedule ?? getOperatorPassSchedule();+ const phase = getOperatorPassPhase(input.now, schedule);+ const verified = input.quote ? verifyOperatorPassQuote(input.quote, input.secret) : null;+ const quote = verified && (verified.userId === null || verified.userId === input.userId) ? verified : null;+ if (quote && isQuoteHonored(quote, input, schedule, phase)) {+ return {+ phase,+ pricedPhase: 'early_bird',+ amountMinor: OPERATOR_PASS_EARLY_BIRD_PRICES_MINOR[input.currency],+ quoteHonored: true,+ priceChanged: false,+ };+ }+ const amountMinor = getOperatorPassPriceMinor(phase, input.currency, schedule);+ return {+ phase,+ pricedPhase: getOperatorPassPricedPhase(phase),+ amountMinor,+ quoteHonored: false,+ priceChanged: quote !== null && (quote.currency !== input.currency || quote.amountMinor !== amountMinor),+ };+}++export function getOperatorPassSessionExpiresAt(+ pricedPhase: OperatorPassPricedPhase,+ now: Date,+ schedule: OperatorPassSchedule = getOperatorPassSchedule(),+ realNowMs = Date.now(),+): number | undefined {+ if (pricedPhase !== 'early_bird' || !schedule.priceRisesAt) {+ return undefined;+ }+ const untilGraceEndMs = schedule.priceRisesAt.getTime() + schedule.graceMs - now.getTime();+ const lifetimeMs = Math.min(+ STRIPE_CHECKOUT_MAX_EXPIRY_MS - STRIPE_CHECKOUT_EXPIRY_MARGIN_MS,+ Math.max(STRIPE_CHECKOUT_MIN_EXPIRY_MS + STRIPE_CHECKOUT_EXPIRY_MARGIN_MS, untilGraceEndMs),+ );+ return Math.floor((realNowMs + lifetimeMs) / 1000);+}