Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(api): defer birth date, block and undo underage closures

Hampus018ee3d432f1
diff --git a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts b/fluxer_api/src/api/admin/services/AdminUserProfileService.ts
index 150bd68fc..428aa760c 100644
--- a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts
+++ b/fluxer_api/src/api/admin/services/AdminUserProfileService.ts
@@ -3,6 +3,7 @@
import type {ApiContext} from '@app/api/ApiContext';
import {mapUserToAdminResponse} from '@app/api/admin/models/UserTypes';
import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService';
+import {confirmEmailOwnership} from '@app/api/auth/EmailOwnership';
import {createUserID, type UserID} from '@app/api/BrandedTypes';
import type {EnforcementDecisionRow} from '@app/api/database/types/EnforcementTypes';
import type {EnforcementActor} from '@app/api/enforcement/EnforcementActor';
@@ -11,21 +12,27 @@ import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository'
import {GuildMemberSearchIndexService} from '@app/api/guild/services/member/GuildMemberSearchIndexService';
import type {DiscriminatorService} from '@app/api/infrastructure/DiscriminatorService';
import type {EntityAssetService, PreparedAssetUpload} from '@app/api/infrastructure/EntityAssetService';
+import {getEmailDeliveryState} from '@app/api/instance/AccountsConfigCache';
import {Logger} from '@app/api/Logger';
-import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import {getInstanceConfigRepository, getKVAccountDeletionQueue} from '@app/api/middleware/ServiceSingletons';
import type {User} from '@app/api/models/User';
import {enqueueStripeCustomerEmailSync} from '@app/api/stripe/StripeCustomer';
import {
type PartialUserChangePropagationDeps,
propagateUserUpdate,
} from '@app/api/user/services/PartialUserChangePropagation';
+import {clearPendingDeletion} from '@app/api/user/services/PendingDeletionCoordinator';
import {assertNoDiscriminatorChange, reserveUsername, type UsernameReservation} from '@app/api/user/UniqueUsernames';
import {USERNAME_MODE_DISCRIMINATOR} from '@app/api/user/UserTag';
+import {BELOW_MINIMUM_AGE_TRAIT, DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
+import {EmailDeliveryStates} from '@fluxer/constants/src/AccountConfigConstants';
+import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {isPlausibleDateOfBirth} from '@fluxer/constants/src/RegionalMinimumAge';
+import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {AccessDeniedError} from '@fluxer/errors/src/domains/core/AccessDeniedError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {TagAlreadyTakenError} from '@fluxer/errors/src/domains/user/TagAlreadyTakenError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {
AdminUserClearFieldsRequest,
ChangeDobRequest,
@@ -36,7 +43,6 @@ import type {
UserProfileField,
VerifyUserEmailRequest,
} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';
-import {types} from 'cassandra-driver';
interface AdminUserProfileServiceDeps {
apiContext: ApiContext;
@@ -59,6 +65,15 @@ function profileValues(user: User, fields: ReadonlyArray<UserProfileField>): Map
return new Map(fields.flatMap((field) => (current[field] ? [[field, current[field]] as const] : [])));
}
+function isPlausibleAdminDateOfBirth(value: string): boolean {
+ const [year, month, day] = value.split('-').map(Number);
+ const now = new Date();
+ return isPlausibleDateOfBirth(
+ {year: year!, month: month!, day: day!},
+ {year: now.getUTCFullYear(), month: now.getUTCMonth() + 1, day: now.getUTCDate()},
+ );
+}
+
export class AdminUserProfileService {
private readonly searchIndexService: GuildMemberSearchIndexService;
@@ -217,12 +232,9 @@ export class AdminUserProfileService {
if (!user) {
throw new UnknownUserError();
}
- const updatedUser = await userRepository.patchUpsert(
- userId,
- {email_verified: true, email_bounced: false},
- user.toRow(),
- );
+ const updatedUser = await confirmEmailOwnership(this.deps.apiContext, user);
await propagateUserUpdate(userUpdateDeps, user, updatedUser);
+ await enqueueStripeCustomerEmailSync(this.deps.apiContext.services.worker, user, updatedUser);
await auditService.createAuditLog({
adminUserId,
targetType: 'user',
@@ -331,7 +343,7 @@ export class AdminUserProfileService {
userId,
{
email: data.email,
- email_verified: false,
+ email_verified: getEmailDeliveryState() !== EmailDeliveryStates.ON,
},
user.toRow(),
);
@@ -386,13 +398,27 @@ export class AdminUserProfileService {
if (!user) {
throw new UnknownUserError();
}
- const updatedUser = await userRepository.patchUpsert(
+ const traits = user.traits;
+ traits.delete(DOB_DEFERRED_TRAIT);
+ const clearedBelowMinimumAge = traits.delete(BELOW_MINIMUM_AGE_TRAIT);
+ let updatedUser = await userRepository.patchUpsert(
userId,
{
date_of_birth: types.LocalDate.fromString(data.date_of_birth),
+ traits: traits.size > 0 ? traits : null,
},
user.toRow(),
);
+ if (clearedBelowMinimumAge && updatedUser.deletionReasonCode === DeletionReasons.BELOW_MINIMUM_AGE) {
+ updatedUser = await userRepository.updateDeletionSchedule(updatedUser, {
+ flags: updatedUser.flags & ~UserFlags.DELETED,
+ pending_deletion_at: null,
+ deletion_reason_code: null,
+ deletion_public_reason: null,
+ deletion_audit_log_reason: null,
+ });
+ await clearPendingDeletion({userId, deletionQueue: getKVAccountDeletionQueue()});
+ }
await propagateUserUpdate(userUpdateDeps, user, updatedUser);
await auditService.createAuditLog({
adminUserId,
@@ -403,6 +429,8 @@ export class AdminUserProfileService {
metadata: new Map([
['old_dob', user.dateOfBirth ?? 'null'],
['new_dob', data.date_of_birth],
+ ['cleared_below_minimum_age', clearedBelowMinimumAge ? 'true' : 'false'],
+ ['outside_plausible_range', isPlausibleAdminDateOfBirth(data.date_of_birth) ? 'false' : 'true'],
]),
});
return {
diff --git a/fluxer_api/src/api/auth/AuthSession.ts b/fluxer_api/src/api/auth/AuthSession.ts
index 2d863492d..e84ae2398 100644
--- a/fluxer_api/src/api/auth/AuthSession.ts
+++ b/fluxer_api/src/api/auth/AuthSession.ts
@@ -13,15 +13,16 @@ import {Logger} from '@app/api/Logger';
import {getKVAccountDeletionQueue} from '@app/api/middleware/ServiceSingletons';
import type {AuthSession} from '@app/api/models/AuthSession';
import type {User} from '@app/api/models/User';
+import {BELOW_MINIMUM_AGE_TRAIT} from '@app/api/user/UserTraits';
import {lookupGeoip} from '@app/api/utils/IpUtils';
import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';
import {isFluxerNativeUserAgent, parseReportedClientOs} from '@app/api/utils/SessionClientIdentity';
+import {AccountBelowMinimumAgeError} from '@fluxer/errors/src/domains/auth/AccountBelowMinimumAgeError';
import {BotUserAuthSessionCreationDeniedError} from '@fluxer/errors/src/domains/auth/BotUserAuthSessionCreationDeniedError';
import {RegistrationPendingApprovalError} from '@fluxer/errors/src/domains/auth/RegistrationPendingApprovalError';
import {RegistrationRejectedError} from '@fluxer/errors/src/domains/auth/RegistrationRejectedError';
import {SessionTokenMismatchError} from '@fluxer/errors/src/domains/auth/SessionTokenMismatchError';
import {InvalidTokenError} from '@fluxer/errors/src/domains/core/InvalidTokenError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
import type {AuthSessionResponse} from '@fluxer/schema/src/domains/auth/AuthSchemas';
export interface SessionOrigin {
@@ -82,9 +83,10 @@ export async function createAuthSession(
user = await AuthUtility.assertSignInAllowed(ctx, user);
if (user.traits.has(REGISTRATION_PENDING_APPROVAL_TRAIT)) throw new RegistrationPendingApprovalError();
if (user.traits.has(REGISTRATION_REJECTED_TRAIT)) throw new RegistrationRejectedError();
+ if (user.traits.has(BELOW_MINIMUM_AGE_TRAIT)) throw new AccountBelowMinimumAgeError();
user = await AuthUtility.reactivateOnSignIn(ctx, user, getKVAccountDeletionQueue());
const now = new Date();
- const token = await AuthUtility.generateAuthToken(ctx);
+ const token = await AuthUtility.generateAuthToken();
let clientCountry: string | null = null;
try {
const geoip = await lookupGeoip(origin.ip);
diff --git a/fluxer_api/src/api/auth/AuthUtility.ts b/fluxer_api/src/api/auth/AuthUtility.ts
index 10dbff5c4..3f64a7b00 100644
--- a/fluxer_api/src/api/auth/AuthUtility.ts
+++ b/fluxer_api/src/api/auth/AuthUtility.ts
@@ -10,6 +10,7 @@ import {clearExpiredSuspension} from '@app/api/enforcement/SuspensionState';
import type {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
import {Logger} from '@app/api/Logger';
import type {User} from '@app/api/models/User';
+import {followOperatorPassWallStanding} from '@app/api/operator_pass/OperatorPassWallStanding';
import {isAccountClosed, isSignInRefused} from '@app/api/user/UserHelpers';
import * as AgeUtils from '@app/api/utils/AgeUtils';
import * as RandomUtils from '@app/api/utils/RandomUtils';
@@ -39,7 +40,7 @@ function base62Encode(buffer: Uint8Array): string {
return encoded;
}
-export async function generateAuthToken(_ctx: ApiContext): Promise<string> {
+export async function generateAuthToken(): Promise<string> {
const bytes = await randomBytesAsync(27);
let token = base62Encode(new Uint8Array(bytes));
if (token.length < 36) {
@@ -51,7 +52,7 @@ export async function generateAuthToken(_ctx: ApiContext): Promise<string> {
return `flx_${token}`;
}
-export function generateBackupCodes(_ctx: ApiContext): Array<string> {
+export function generateBackupCodes(): Array<string> {
return Array.from({length: 10}, () => {
return `${RandomUtils.randomString(4).toLowerCase()}-${RandomUtils.randomString(4).toLowerCase()}`;
});
@@ -61,12 +62,12 @@ export function getTokenIdHash(_ctx: ApiContext, token: string): Uint8Array {
return new Uint8Array(crypto.createHash('sha256').update(token).digest());
}
-export function validateAge(_ctx: ApiContext, {dateOfBirth, minAge}: ValidateAgeParams): boolean {
+export function validateAge({dateOfBirth, minAge}: ValidateAgeParams): boolean {
const birthDate = new Date(dateOfBirth);
const age = AgeUtils.calculateAge({
- year: birthDate.getFullYear(),
- month: birthDate.getMonth() + 1,
- day: birthDate.getDate(),
+ year: birthDate.getUTCFullYear(),
+ month: birthDate.getUTCMonth() + 1,
+ day: birthDate.getUTCDate(),
});
return age >= minAge;
}
@@ -139,5 +140,6 @@ export async function reactivateOnSignIn(
await deletionQueue.removeFromQueue(currentUser.id);
Logger.info({userId: currentUser.id}, 'Auto-cancelled deletion on sign-in');
}
+ await followOperatorPassWallStanding(user, currentUser);
return currentUser;
}
diff --git a/fluxer_api/src/api/instance/DateOfBirthCollectionCache.ts b/fluxer_api/src/api/instance/DateOfBirthCollectionCache.ts
index d037f8189..6f48c309a 100644
--- a/fluxer_api/src/api/instance/DateOfBirthCollectionCache.ts
+++ b/fluxer_api/src/api/instance/DateOfBirthCollectionCache.ts
@@ -1,17 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {Config} from '@app/api/Config';
+import {getDateOfBirthPolicy} from '@app/api/instance/AccountsConfigCache';
+import {collectsDateOfBirth} from '@fluxer/constants/src/AccountConfigConstants';
-let cachedCollectDateOfBirth: boolean | null = null;
-
-export function getDefaultDateOfBirthCollection(): boolean {
+export function getLegacyDateOfBirthCollectionDefault(): boolean {
return !Config.instance.selfHosted;
}
export function instanceCollectsDateOfBirth(): boolean {
- return cachedCollectDateOfBirth ?? getDefaultDateOfBirthCollection();
-}
-
-export function setCachedDateOfBirthCollection(collect: boolean): void {
- cachedCollectDateOfBirth = collect;
+ return collectsDateOfBirth(getDateOfBirthPolicy());
}
diff --git a/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.ts b/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.ts
new file mode 100644
index 000000000..f5480b00e
--- /dev/null
+++ b/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.ts
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {isDateOfBirthEnforced} from '@app/api/user/DateOfBirth';
+import {stripApiPrefix} from '@app/api/utils/RequestPathUtils';
+import {DateOfBirthRequiredError} from '@fluxer/errors/src/domains/auth/DateOfBirthRequiredError';
+import {createMiddleware} from 'hono/factory';
+
+const DATE_OF_BIRTH_EXEMPT_PREFIXES: ReadonlyArray<string> = ['/auth/', '/admin/', '/test/', '/users/@me/sudo/'];
+
+export const DATE_OF_BIRTH_ALLOWLIST: ReadonlyArray<{method: string; path: RegExp}> = [
+ {method: 'GET', path: /^\/users\/@me$/},
+ {method: 'PUT', path: /^\/users\/@me\/date-of-birth$/},
+ {method: 'GET', path: /^\/users\/@me\/settings$/},
+ {method: 'POST', path: /^\/users\/@me\/delete$/},
+ {method: 'POST', path: /^\/users\/@me\/disable$/},
+ {method: 'POST', path: /^\/users\/@me\/terms-acceptance$/},
+ {method: 'GET', path: /^\/users\/@me\/harvest(\/[^/]+)*$/},
+ {method: 'POST', path: /^\/users\/@me\/harvest(\/[^/]+)*$/},
+ {method: 'GET', path: /^\/experiments$/},
+ {method: 'GET', path: /^\/gateway\/bot$/},
+];
+
+export function isDateOfBirthAllowedRoute(method: string, path: string): boolean {
+ if (DATE_OF_BIRTH_EXEMPT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
+ return DATE_OF_BIRTH_ALLOWLIST.some((entry) => entry.method === method && entry.path.test(path));
+}
+
+export const DateOfBirthGateMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
+ const user = ctx.get('user');
+ if (
+ user &&
+ ctx.get('authTokenType') !== 'bot' &&
+ ctx.get('authTokenType') !== 'admin_api_key' &&
+ isDateOfBirthEnforced(user) &&
+ !isDateOfBirthAllowedRoute(ctx.req.method, stripApiPrefix(ctx.req.path))
+ ) {
+ throw new DateOfBirthRequiredError();
+ }
+ await next();
+});
diff --git a/fluxer_api/src/api/user/DateOfBirth.ts b/fluxer_api/src/api/user/DateOfBirth.ts
new file mode 100644
index 000000000..1c1c3b023
--- /dev/null
+++ b/fluxer_api/src/api/user/DateOfBirth.ts
@@ -0,0 +1,191 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {ApiContext} from '@app/api/ApiContext';
+import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';
+import type {AgeBand} from '@app/api/infrastructure/activity/Contract.generated';
+import {usesUniqueUsernames} from '@app/api/instance/AccountIdentityModeCache';
+import {getDateOfBirthPolicy} from '@app/api/instance/AccountsConfigCache';
+import {instanceCollectsDateOfBirth} from '@app/api/instance/DateOfBirthCollectionCache';
+import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
+import {getDiscriminatorService, getKVAccountDeletionQueue} from '@app/api/middleware/ServiceSingletons';
+import type {User} from '@app/api/models/User';
+import {UserSettings} from '@app/api/models/UserSettings';
+import {scheduleSystemDeletion} from '@app/api/user/AccountCleanup';
+import type {TierContext} from '@app/api/user/AccountTier';
+import {executeEntries, type GuildEntryDeps, takePendingEntries} from '@app/api/user/GuildEntry';
+import {deriveAvailableUsername} from '@app/api/user/UniqueUsernames';
+import {mapUserSettingsToResponse, mapUserToPrivateResponse} from '@app/api/user/UserMappers';
+import {USERNAME_MODE_DISCRIMINATOR} from '@app/api/user/UserTag';
+import {BELOW_MINIMUM_AGE_TRAIT, DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
+import {calculateAge, parseDateOfBirth} from '@app/api/utils/AgeUtils';
+import {lookupGeoip} from '@app/api/utils/IpUtils';
+import {generateRandomUsername} from '@app/api/utils/UsernameGenerator';
+import {DateOfBirthPolicies} from '@fluxer/constants/src/AccountConfigConstants';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {getRegionalMinimumAge} from '@fluxer/constants/src/RegionalMinimumAge';
+import {SensitiveMediaFilterLevel} from '@fluxer/constants/src/UserConstants';
+import {AccountBelowMinimumAgeError} from '@fluxer/errors/src/domains/auth/AccountBelowMinimumAgeError';
+import {DateOfBirthAlreadySetError} from '@fluxer/errors/src/domains/auth/DateOfBirthAlreadySetError';
+import {NotFoundError} from '@fluxer/errors/src/domains/core/NotFoundError';
+import type {DateOfBirthUpdateResponse} from '@fluxer/schema/src/domains/user/AccountSchemas';
+
+const UNDERAGE_DELETION_DELAY_MS = 72 * 3600 * 1000;
+const ADULT_AGE = 18;
+
+type DateOfBirthUser = Pick<User, 'isBot' | 'isSystem' | 'dateOfBirth'> & {traits: ReadonlySet<string>};
+
+export function isDateOfBirthMissing(user: DateOfBirthUser): boolean {
+ return (
+ instanceCollectsDateOfBirth() &&
+ user.dateOfBirth === null &&
+ !user.isBot &&
+ !user.isSystem &&
+ !user.traits.has(BELOW_MINIMUM_AGE_TRAIT)
+ );
+}
+
+export function isDateOfBirthEnforced(user: DateOfBirthUser): boolean {
+ if (!isDateOfBirthMissing(user)) return false;
+ switch (getDateOfBirthPolicy()) {
+ case DateOfBirthPolicies.OFF:
+ case DateOfBirthPolicies.ASK:
+ return false;
+ case DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS:
+ return user.traits.has(DOB_DEFERRED_TRAIT);
+ case DateOfBirthPolicies.REQUIRE_ALL:
+ return true;
+ }
+}
+
+function settingsForAge(settings: UserSettings, adult: boolean): UserSettings | null {
+ const teen = UserSettings.getDefaultUserSettings({userId: settings.userId, locale: settings.locale, isAdult: false});
+ const adultDefaults = UserSettings.getDefaultUserSettings({
+ userId: settings.userId,
+ locale: settings.locale,
+ isAdult: true,
+ });
+ const [from, to] = adult ? [teen, adultDefaults] : [adultDefaults, teen];
+ const row = settings.toRow();
+ let changed = false;
+ for (const key of ['explicit_content_filter', 'friend_source_flags', 'sensitive_content_friend_dm_filter'] as const) {
+ if (row[key] === from[key] && row[key] !== to[key]) {
+ Object.assign(row, {[key]: to[key]});
+ changed = true;
+ }
+ }
+ if (!adult) {
+ for (const key of [
+ 'sensitive_content_friend_dm_filter',
+ 'sensitive_content_non_friend_dm_filter',
+ 'sensitive_content_guild_filter',
+ ] as const) {
+ if (row[key] === SensitiveMediaFilterLevel.SHOW) {
+ Object.assign(row, {[key]: teen[key]});
+ changed = true;
+ }
+ }
+ }
+ return changed ? new UserSettings(row) : null;
+}
+
+async function releaseUsername(ctx: ApiContext, user: User): Promise<{username: string; discriminator: number}> {
+ const base = generateRandomUsername();
+ if (usesUniqueUsernames()) {
+ return {
+ username: await deriveAvailableUsername(ctx.services.users, base),
+ discriminator: USERNAME_MODE_DISCRIMINATOR,
+ };
+ }
+ const result = await getDiscriminatorService().generateDiscriminator({username: base});
+ return result.available && result.discriminator !== -1
+ ? {username: base, discriminator: result.discriminator}
+ : {username: user.username, discriminator: user.discriminator};
+}
+
+function emitDateOfBirthSet(userId: User['id'], result: AgeBand): void {
+ void emitActivity('date_of_birth_set', userId.toString(), {user_id: userId.toString(), result});
+}
+
+async function handleUnderage(ctx: ApiContext, user: User): Promise<never> {
+ const traits = user.traits;
+ traits.delete(DOB_DEFERRED_TRAIT);
+ traits.add(BELOW_MINIMUM_AGE_TRAIT);
+ const released = await releaseUsername(ctx, user);
+ const updated = await ctx.services.users.patchUpsert(
+ user.id,
+ {traits, date_of_birth: null, username: released.username, discriminator: released.discriminator},
+ user.toRow(),
+ );
+ await scheduleSystemDeletion(
+ {users: ctx.services.users, gateway: ctx.services.gateway, deletionQueue: getKVAccountDeletionQueue()},
+ updated,
+ {
+ reasonCode: DeletionReasons.BELOW_MINIMUM_AGE,
+ delayMs: UNDERAGE_DELETION_DELAY_MS,
+ cancelledBySignIn: false,
+ endSessions: true,
+ },
+ );
+ emitDateOfBirthSet(user.id, 'underage');
+ throw new AccountBelowMinimumAgeError();
+}
+
+export async function setDateOfBirth(
+ ctx: ApiContext,
+ deps: GuildEntryDeps,
+ params: {
+ user: User;
+ dateOfBirth: string;
+ clientIp: string;
+ tierContext: TierContext;
+ requestCache: RequestCache;
+ },
+): Promise<DateOfBirthUpdateResponse> {
+ const {user} = params;
+ if (!instanceCollectsDateOfBirth()) {
+ throw new NotFoundError({code: APIErrorCodes.NOT_FOUND});
+ }
+ if (user.dateOfBirth !== null) throw new DateOfBirthAlreadySetError();
+ const dateOfBirth = parseDateOfBirth(params.dateOfBirth);
+ const geoip = await lookupGeoip(params.clientIp);
+ const age = calculateAge(params.dateOfBirth);
+ if (age < getRegionalMinimumAge(geoip.countryCode)) {
+ return await handleUnderage(ctx, user);
+ }
+ const traits = user.traits;
+ traits.delete(DOB_DEFERRED_TRAIT);
+ const updated = await ctx.services.users.patchUpsert(
+ user.id,
+ {date_of_birth: dateOfBirth, traits: traits.size > 0 ? traits : null},
+ user.toRow(),
+ );
+ const adult = age >= ADULT_AGE;
+ const settings = await ctx.services.users.findSettings(user.id);
+ const adjusted = settings ? settingsForAge(settings, adult) : null;
+ if (adjusted) {
+ const saved = await ctx.services.users.upsertSettings(adjusted.toRow());
+ await ctx.services.gateway.dispatchPresence({
+ userId: user.id,
+ event: 'USER_SETTINGS_UPDATE',
+ data: mapUserSettingsToResponse({settings: saved}),
+ });
+ }
+ await ctx.services.gateway.dispatchPresence({
+ userId: user.id,
+ event: 'USER_UPDATE',
+ data: mapUserToPrivateResponse(updated),
+ });
+ for (const guildId of await ctx.services.users.getUserGuildIds(user.id)) {
+ await ctx.services.gateway.joinGuild({userId: user.id, guildId});
+ }
+ emitDateOfBirthSet(user.id, adult ? 'adult' : 'teen');
+ const entry = await executeEntries(deps, {
+ user: updated,
+ entries: await takePendingEntries(ctx.services.kv, user.id),
+ tierContext: params.tierContext,
+ requestCache: params.requestCache,
+ ip: params.clientIp,
+ });
+ return {user: mapUserToPrivateResponse(updated), entry};
+}
diff --git a/fluxer_api/src/api/user/ProfileVisibility.ts b/fluxer_api/src/api/user/ProfileVisibility.ts
index 6765cfa87..dde6dac9a 100644
--- a/fluxer_api/src/api/user/ProfileVisibility.ts
+++ b/fluxer_api/src/api/user/ProfileVisibility.ts
@@ -20,6 +20,8 @@ const NON_ENFORCEMENT_DELETION_REASONS: ReadonlySet<number> = new Set([
DeletionReasons.USER_REQUESTED,
DeletionReasons.OTHER,
DeletionReasons.INACTIVITY,
+ DeletionReasons.BELOW_MINIMUM_AGE,
+ DeletionReasons.UNCLAIMED_ACCOUNT_ABANDONED,
]);
export function isEnforcementDeletionReason(code: number | null): boolean {
diff --git a/fluxer_api/src/api/user/tests/DateOfBirthStep.test.ts b/fluxer_api/src/api/user/tests/DateOfBirthStep.test.ts
new file mode 100644
index 000000000..b71874d6d
--- /dev/null
+++ b/fluxer_api/src/api/user/tests/DateOfBirthStep.test.ts
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {registerControllers} from '@app/api/app/ControllerRegistry';
+import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
+import {Config} from '@app/api/Config';
+import {createChannelInvite, createGuild} from '@app/api/message/tests/MessageTestUtils';
+import {DATE_OF_BIRTH_ALLOWLIST, isDateOfBirthAllowedRoute} from '@app/api/middleware/DateOfBirthGateMiddleware';
+import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {DateOfBirthPolicies} from '@fluxer/constants/src/AccountConfigConstants';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {SensitiveMediaFilterLevel, UserFlags} from '@fluxer/constants/src/UserConstants';
+import {Hono} from 'hono';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+interface RegisterBody {
+ token: string;
+ user_id: string;
+ entry?: {guild_id: string; mode: string} | null;
+}
+
+interface DateOfBirthBody {
+ user: {date_of_birth_required: boolean; nsfw_allowed: boolean};
+ entry: {guild_id: string; mode: string} | null;
+}
+
+function yearsAgo(years: number): string {
+ const date = new Date();
+ date.setUTCFullYear(date.getUTCFullYear() - years);
+ date.setUTCDate(date.getUTCDate() - 1);
+ return date.toISOString().slice(0, 10);
+}
+
+describe('Date of birth step', () => {
+ let harness: ApiTestHarness;
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ async function registerWithoutBirthday(body: Record<string, unknown> = {}): Promise<RegisterBody> {
+ return await createBuilderWithoutAuth<RegisterBody>(harness)
+ .post('/auth/register')
+ .body({username: 'birthdayless', consent: true, ...body})
+ .execute();
+ }
+
+ function setBirthday(token: string, dateOfBirth: string) {
+ return createBuilder<DateOfBirthBody>(harness, token)
+ .put('/users/@me/date-of-birth')
+ .body({date_of_birth: dateOfBirth});
+ }
+
+ it('blocks everything but the allowed routes until a date of birth is set', async () => {
+ const account = await registerWithoutBirthday();
+ await createBuilder(harness, account.token)
+ .get('/users/@me/guilds')
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.DATE_OF_BIRTH_REQUIRED)
+ .execute();
+ await createBuilder(harness, account.token)
+ .patch('/users/@me')
+ .body({global_name: 'Too Early'})
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.DATE_OF_BIRTH_REQUIRED)
+ .execute();
+ await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.OK).execute();
+ await createBuilder(harness, account.token).get('/users/@me/settings').expect(HTTP_STATUS.OK).execute();
+ await createBuilder(harness, account.token).get('/experiments').expect(HTTP_STATUS.OK).execute();
+ });
+
+ it('sets an adult date once, upgrades untouched defaults and opens the app', async () => {
+ const account = await registerWithoutBirthday();
+ const result = await setBirthday(account.token, yearsAgo(30)).execute();
+ expect(result.user).toMatchObject({date_of_birth_required: false, nsfw_allowed: true});
+ const settings = await createBuilder<{sensitive_content_friend_dm_filter: number}>(harness, account.token)
+ .get('/users/@me/settings')
+ .execute();
+ expect(settings.sensitive_content_friend_dm_filter).toBe(SensitiveMediaFilterLevel.SHOW);
+ await createBuilder(harness, account.token).get('/users/@me/guilds').expect(HTTP_STATUS.OK).execute();
+ await setBirthday(account.token, yearsAgo(31))
+ .expect(HTTP_STATUS.CONFLICT, APIErrorCodes.DATE_OF_BIRTH_ALREADY_SET)
+ .execute();
+ });
+
+ it('keeps teen defaults for a teen', async () => {
+ const account = await registerWithoutBirthday();
+ const result = await setBirthday(account.token, yearsAgo(15)).execute();
+ expect(result.user).toMatchObject({date_of_birth_required: false, nsfw_allowed: false});
+ const settings = await createBuilder<{sensitive_content_friend_dm_filter: number}>(harness, account.token)
+ .get('/users/@me/settings')
+ .execute();
+ expect(settings.sensitive_content_friend_dm_filter).toBe(SensitiveMediaFilterLevel.BLUR);
+ });
+
+ it('clamps adult content settings when an account without a date turns out to be a teen', async () => {
+ const legacy = await createTestAccount(harness);
+ const legacyUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(legacy.userId)));
+ await getUserRepository().patchUpsert(legacyUser.id, {date_of_birth: null}, legacyUser.toRow());
+ await setBirthday(legacy.token, yearsAgo(15)).execute();
+ const settings = await createBuilder<{
+ sensitive_content_friend_dm_filter: number;
+ sensitive_content_non_friend_dm_filter: number;
+ }>(harness, legacy.token)
+ .get('/users/@me/settings')
+ .execute();
+ expect(settings.sensitive_content_friend_dm_filter).toBe(SensitiveMediaFilterLevel.BLUR);
+ expect(settings.sensitive_content_non_friend_dm_filter).toBe(SensitiveMediaFilterLevel.BLOCK);
+ });
+
+ it('refuses dates that are malformed, impossible, today, in the future or more than 120 years back', async () => {
+ const account = await registerWithoutBirthday();
+ const today = new Date().toISOString().slice(0, 10);
+ for (const value of [
+ '2000-02-30',
+ '1800-01-01',
+ yearsAgo(142),
+ yearsAgo(120),
+ today,
+ `${new Date().getUTCFullYear() + 1}-01-01`,
+ ]) {
+ await setBirthday(account.token, value).expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY').execute();
+ }
+ });
+
+ it('accepts someone who turns 120 today', async () => {
+ const account = await registerWithoutBirthday();
+ const date = new Date();
+ date.setUTCFullYear(date.getUTCFullYear() - 120);
+ await setBirthday(account.token, date.toISOString().slice(0, 10)).expect(HTTP_STATUS.OK).execute();
+ });
+
+ it('refuses an implausible date at registration too', async () => {
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/register')
+ .body({username: 'ancient', consent: true, date_of_birth: yearsAgo(142)})
+ .expect(HTTP_STATUS.BAD_REQUEST, 'INVALID_FORM_BODY')
+ .execute();
+ });
+
+ it('closes an account below the minimum age and keeps no date', async () => {
+ const account = await registerWithoutBirthday();
+ await setBirthday(account.token, yearsAgo(9))
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.ACCOUNT_BELOW_MINIMUM_AGE)
+ .execute();
+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.user_id)));
+ expect(user.dateOfBirth).toBeNull();
+ expect(user.traits.has('below_minimum_age')).toBe(true);
+ expect(user.username).not.toBe('birthdayless');
+ expect(user.deletionReasonCode).toBe(DeletionReasons.BELOW_MINIMUM_AGE);
+ const remainingMs = user.pendingDeletionAt!.getTime() - Date.now();
+ expect(remainingMs).toBeGreaterThan(71 * 3600 * 1000);
+ expect(remainingMs).toBeLessThanOrEqual(72 * 3600 * 1000);
+ await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
+ });
+
+ async function correctBirthday(userId: string): Promise<void> {
+ const staff = await setUserACLs(harness, await createTestAccount(harness), [AdminACLs.WILDCARD]);
+ await createBuilder(harness, staff.token)
+ .patch(`/admin/users/${userId}/date-of-birth`)
+ .body({date_of_birth: yearsAgo(30)})
+ .execute();
+ }
+
+ it('a corrected date of birth cancels the under-age deletion', async () => {
+ const account = await registerWithoutBirthday();
+ await setBirthday(account.token, yearsAgo(9))
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.ACCOUNT_BELOW_MINIMUM_AGE)
+ .execute();
+ await correctBirthday(account.user_id);
+ const user = await getUserRepository().findUniqueAssert(createUserID(BigInt(account.user_id)));
+ expect(user.traits.has('below_minimum_age')).toBe(false);
+ expect(user.flags & UserFlags.DELETED).toBe(0n);
+ expect(user.pendingDeletionAt).toBeNull();
+ });
+
+ it('enforces only for accounts created without a date until every account is required', async () => {
+ const legacy = await createTestAccount(harness);
+ const legacyUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(legacy.userId)));
+ await getUserRepository().patchUpsert(legacyUser.id, {date_of_birth: null}, legacyUser.toRow());
+ await createBuilder(harness, legacy.token).get('/users/@me/guilds').expect(HTTP_STATUS.OK).execute();
+ const me = await createBuilder<{date_of_birth_required: boolean}>(harness, legacy.token)
+ .get('/users/@me')
+ .execute();
+ expect(me.date_of_birth_required).toBe(true);
+ await getInstanceConfigRepository().updateAccountsConfig({date_of_birth: DateOfBirthPolicies.REQUIRE_ALL});
+ await createBuilder(harness, legacy.token)
+ .get('/users/@me/guilds')
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.DATE_OF_BIRTH_REQUIRED)
+ .execute();
+ await getInstanceConfigRepository().updateAccountsConfig({date_of_birth: DateOfBirthPolicies.ASK});
+ const fresh = await registerWithoutBirthday();
+ await createBuilder(harness, fresh.token).get('/users/@me/guilds').expect(HTTP_STATUS.OK).execute();
+ const freshMe = await createBuilder<{date_of_birth_required: boolean}>(harness, fresh.token)
+ .get('/users/@me')
+ .execute();
+ expect(freshMe.date_of_birth_required).toBe(true);
+ });
+
+ it('starts the gateway session without guilds until the date is set', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({date_of_birth: DateOfBirthPolicies.REQUIRE_ALL});
+ const legacy = await createTestAccount(harness);
+ await createGuild(harness, legacy.token, 'Before the step');
+ const legacyUser = await getUserRepository().findUniqueAssert(createUserID(BigInt(legacy.userId)));
+ await getUserRepository().patchUpsert(legacyUser.id, {date_of_birth: null}, legacyUser.toRow());
+ const ready = await createBuilder<{data: {guilds: Array<unknown>}}>(harness, '')
+ .post('/test/rpc-session-init')
+ .body({type: 'session', token: legacy.token, version: 1, ip: '127.0.0.1'})
+ .execute();
+ expect(ready.data.guilds).toEqual([]);
+ await setBirthday(legacy.token, yearsAgo(25)).execute();
+ const after = await createBuilder<{data: {guilds: Array<unknown>}}>(harness, '')
+ .post('/test/rpc-session-init')
+ .body({type: 'session', token: legacy.token, version: 1, ip: '127.0.0.1'})
+ .execute();
+ expect(after.data.guilds).toHaveLength(1);
+ });
+
+ it('runs the invite from sign-up after the date of birth, once', async () => {
+ const owner = await createTestAccount(harness);
+ const guild = await createGuild(harness, owner.token, 'Welcome');
+ const invite = await createChannelInvite(harness, owner.token, guild.system_channel_id!);
+ const account = await registerWithoutBirthday({invite_code: invite.code});
+ expect(account.entry ?? null).toBeNull();
+ const result = await setBirthday(account.token, yearsAgo(20)).execute();
+ expect(result.entry).toEqual({guild_id: guild.id, mode: 'member'});
+ const guilds = await createBuilder<Array<{id: string}>>(harness, account.token).get('/users/@me/guilds').execute();
+ expect(guilds.map((entry) => entry.id)).toContain(guild.id);
+ });
+
+ it('runs the invite at registration for older apps that send a date of birth', async () => {
+ const owner = await createTestAccount(harness);
+ const guild = await createGuild(harness, owner.token, 'Old app welcome');
+ const invite = await createChannelInvite(harness, owner.token, guild.system_channel_id!);
+ const account = await registerWithoutBirthday({invite_code: invite.code, date_of_birth: yearsAgo(22)});
+ expect(account.entry).toEqual({guild_id: guild.id, mode: 'member'});
+ });
+
+ it('answers not found where the instance does not collect a date of birth', async () => {
+ const account = await createTestAccount(harness);
+ await getInstanceConfigRepository().updateAccountsConfig({date_of_birth: DateOfBirthPolicies.OFF});
+ await setBirthday(account.token, yearsAgo(20)).expect(HTTP_STATUS.NOT_FOUND).execute();
+ });
+});
+
+describe('Date of birth gate route coverage', () => {
+ function registeredRoutes(): Array<{method: string; path: string}> {
+ const app = new Hono<HonoEnv>();
+ registerControllers(app, Config);
+ const seen = new Set<string>();
+ return app.routes
+ .filter((route) => route.method !== 'ALL')
+ .filter((route) => {
+ const key = `${route.method} ${route.path}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ })
+ .map((route) => ({method: route.method, path: route.path}));
+ }
+
+ it('points every allowlist entry at a registered route', () => {
+ const routes = registeredRoutes();
+ for (const entry of DATE_OF_BIRTH_ALLOWLIST) {
+ const matched = routes.some((route) => route.method === entry.method && entry.path.test(route.path));
+ expect(matched, `${entry.method} ${entry.path}`).toBe(true);
+ }
+ });
+
+ it('lets a person without a date of birth reach only the reviewed routes outside sign-in and tooling', () => {
+ const reachable = registeredRoutes()
+ .filter((route) => !/^\/(auth|admin|test)\//.test(route.path))
+ .filter((route) => isDateOfBirthAllowedRoute(route.method, route.path.replace(/:[a-z_]+/g, 'x')))
+ .map((route) => `${route.method} ${route.path}`)
+ .sort();
+ expect(reachable).toEqual(
+ [
+ 'GET /experiments',
+ 'GET /gateway/bot',
+ 'GET /users/@me',
+ 'GET /users/@me/harvest/:harvestId',
+ 'GET /users/@me/harvest/:harvestId/download',
+ 'GET /users/@me/harvest/latest',
+ 'GET /users/@me/settings',
+ 'GET /users/@me/sudo/mfa-methods',
+ 'POST /users/@me/delete',
+ 'POST /users/@me/disable',
+ 'POST /users/@me/harvest',
+ 'POST /users/@me/harvest/filtered',
+ 'POST /users/@me/sudo/email-code',
+ 'POST /users/@me/sudo/webauthn/authentication-options',
+ 'POST /users/@me/terms-acceptance',
+ 'PUT /users/@me/date-of-birth',
+ ].sort(),
+ );
+ });
+});
diff --git a/fluxer_api/src/api/user/tests/UserSettingsSensitiveContentFilter.test.ts b/fluxer_api/src/api/user/tests/UserSettingsSensitiveContentFilter.test.ts
index b621ef11c..83c7564b4 100644
--- a/fluxer_api/src/api/user/tests/UserSettingsSensitiveContentFilter.test.ts
+++ b/fluxer_api/src/api/user/tests/UserSettingsSensitiveContentFilter.test.ts
@@ -6,6 +6,7 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {fetchUserSettings, updateUserSettings} from '@app/api/user/tests/UserTestUtils';
+import {DateOfBirthPolicies} from '@fluxer/constants/src/AccountConfigConstants';
import {SensitiveMediaFilterLevel} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
@@ -87,8 +88,8 @@ describe('User Settings - Sensitive Content Filters', () => {
});
test('allows an account without a birth date to relax every filter when none is collected', async () => {
const repository = getInstanceConfigRepository();
- const previous = (await repository.getAppPublicConfig()).registration.collect_date_of_birth;
- await repository.setAppPublicConfig({registration: {collect_date_of_birth: false}});
+ const previous = (await repository.getAccountsConfig()).date_of_birth;
+ await repository.updateAccountsConfig({date_of_birth: DateOfBirthPolicies.OFF});
try {
const account = await createTestAccount(harness);
const {json} = await updateUserSettings(harness, account.token, {
@@ -100,7 +101,7 @@ describe('User Settings - Sensitive Content Filters', () => {
expect(json.sensitive_content_non_friend_dm_filter).toBe(SensitiveMediaFilterLevel.SHOW);
expect(json.sensitive_content_guild_filter).toBe(SensitiveMediaFilterLevel.SHOW);
} finally {
- await repository.setAppPublicConfig({registration: {collect_date_of_birth: previous}});
+ await repository.updateAccountsConfig({date_of_birth: previous});
}
});
});
diff --git a/fluxer_api/src/api/utils/AgeUtils.test.ts b/fluxer_api/src/api/utils/AgeUtils.test.ts
index 843d8276a..e6a4b7997 100644
--- a/fluxer_api/src/api/utils/AgeUtils.test.ts
+++ b/fluxer_api/src/api/utils/AgeUtils.test.ts
@@ -1,44 +1,120 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {setCachedDateOfBirthCollection} from '@app/api/instance/DateOfBirthCollectionCache';
-import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';
-import {afterEach, describe, expect, it} from 'vitest';
+import {getCachedAccountsConfig, setCachedAccountsConfig} from '@app/api/instance/AccountsConfigCache';
+import {calculateAge, canUserAccessNsfwContent, parseDateOfBirth} from '@app/api/utils/AgeUtils';
+import {DateOfBirthPolicies, type DateOfBirthPolicy} from '@fluxer/constants/src/AccountConfigConstants';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+
+function setDateOfBirthPolicy(dateOfBirth: DateOfBirthPolicy): void {
+ setCachedAccountsConfig({
+ ...getCachedAccountsConfig(),
+ date_of_birth: dateOfBirth,
+ });
+}
const ADULT_DATE_OF_BIRTH = '1990-01-01';
const MINOR_DATE_OF_BIRTH = '2020-01-01';
describe('canUserAccessNsfwContent', () => {
afterEach(() => {
- setCachedDateOfBirthCollection(true);
+ setCachedAccountsConfig(null);
});
it('allows a bot whatever the instance collects', () => {
- setCachedDateOfBirthCollection(true);
+ setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);
expect(canUserAccessNsfwContent({isBot: true, dateOfBirth: null})).toBe(true);
});
it('allows an adult when the instance collects a date of birth', () => {
- setCachedDateOfBirthCollection(true);
+ setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);
expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: ADULT_DATE_OF_BIRTH})).toBe(true);
});
it('blocks a minor when the instance collects a date of birth', () => {
- setCachedDateOfBirthCollection(true);
+ setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);
expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH})).toBe(false);
});
it('blocks a missing date of birth when the instance collects one', () => {
- setCachedDateOfBirthCollection(true);
+ setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);
expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null})).toBe(false);
});
it('allows a missing date of birth when the instance collects none', () => {
- setCachedDateOfBirthCollection(false);
+ setDateOfBirthPolicy(DateOfBirthPolicies.OFF);
expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null})).toBe(true);
});
it('allows an account with a minor date of birth when the instance collects none', () => {
- setCachedDateOfBirthCollection(false);
+ setDateOfBirthPolicy(DateOfBirthPolicies.OFF);
expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH})).toBe(true);
});
});
+
+describe('parseDateOfBirth', () => {
+ const at = (iso: string) => new Date(`${iso}T12:00:00Z`);
+ const accepts = (value: string, today: string) => expect(parseDateOfBirth(value, at(today)).toString()).toBe(value);
+ const refuses = (value: string, today: string) => expect(() => parseDateOfBirth(value, at(today))).toThrow();
+
+ it('accepts someone exactly 120 today and refuses one day older', () => {
+ accepts('1906-10-10', '2026-10-10');
+ refuses('1906-10-09', '2026-10-10');
+ refuses('1884-01-01', '2026-10-10');
+ });
+
+ it('refuses today, the future and impossible dates', () => {
+ refuses('2026-10-10', '2026-10-10');
+ refuses('2026-10-11', '2026-10-10');
+ refuses('2030-01-01', '2026-10-10');
+ refuses('2000-02-30', '2026-10-10');
+ refuses('2001-02-29', '2026-10-10');
+ refuses('2000-13-01', '2026-10-10');
+ refuses('2000-1-01', '2026-10-10');
+ accepts('2026-10-09', '2026-10-10');
+ });
+
+ it('handles leap-day birthdays and leap-day boundaries', () => {
+ accepts('2000-02-29', '2026-10-10');
+ accepts('1904-02-29', '2024-02-29');
+ refuses('1904-02-28', '2024-02-29');
+ accepts('1905-03-01', '2025-03-01');
+ refuses('1905-02-28', '2025-03-01');
+ });
+});
+
+describe('calculateAge', () => {
+ const at = (iso: string) => new Date(`${iso}T12:00:00Z`);
+
+ it('turns the minimum age on the birthday, not a day before', () => {
+ expect(calculateAge('2013-10-11', at('2026-10-10'))).toBe(12);
+ expect(calculateAge('2013-10-10', at('2026-10-10'))).toBe(13);
+ });
+
+ it('counts a leap-day birthday as reached on March 1 in other years', () => {
+ expect(calculateAge('2012-02-29', at('2025-02-28'))).toBe(12);
+ expect(calculateAge('2012-02-29', at('2025-03-01'))).toBe(13);
+ expect(calculateAge('2012-02-29', at('2024-02-29'))).toBe(12);
+ });
+
+ describe('on a server outside UTC', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('reads the UTC date just after UTC midnight in a zone behind UTC', () => {
+ vi.stubEnv('TZ', 'America/Los_Angeles');
+ const now = new Date('2026-10-10T00:30:00Z');
+ expect(now.getDate()).toBe(9);
+ expect(calculateAge('2013-10-10', now)).toBe(13);
+ expect(calculateAge('2013-10-11', now)).toBe(12);
+ });
+
+ it('does not let a birthday that is only local pass just before UTC midnight', () => {
+ vi.stubEnv('TZ', 'Europe/Stockholm');
+ const now = new Date('2026-10-09T23:30:00Z');
+ expect(now.getDate()).toBe(10);
+ expect(calculateAge('2013-10-10', now)).toBe(12);
+ expect(calculateAge({year: 2013, month: 10, day: 9}, now)).toBe(13);
+ });
+ });
+});
diff --git a/fluxer_api/src/api/utils/AgeUtils.ts b/fluxer_api/src/api/utils/AgeUtils.ts
index 41353f4d1..cb6968df1 100644
--- a/fluxer_api/src/api/utils/AgeUtils.ts
+++ b/fluxer_api/src/api/utils/AgeUtils.ts
@@ -1,6 +1,19 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {instanceCollectsDateOfBirth} from '@app/api/instance/DateOfBirthCollectionCache';
+import {isPlausibleDateOfBirth} from '@fluxer/constants/src/RegionalMinimumAge';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+
+export function parseDateOfBirth(value: string, now: Date = new Date()): types.LocalDate {
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
+ const birth = match ? {year: Number(match[1]), month: Number(match[2]), day: Number(match[3])} : null;
+ const today = {year: now.getUTCFullYear(), month: now.getUTCMonth() + 1, day: now.getUTCDate()};
+ if (birth === null || !isPlausibleDateOfBirth(birth, today)) {
+ throw InputValidationError.fromCode('date_of_birth', ValidationErrorCodes.INVALID_DATE_OF_BIRTH_FORMAT);
+ }
+ return new types.LocalDate(birth.year, birth.month, birth.day);
+}
export function calculateAge(
dateOfBirth:
@@ -10,18 +23,18 @@ export function calculateAge(
day: number;
}
| string,
+ today: Date = new Date(),
): number {
- const today = new Date();
- let birthDate: Date;
+ let birth: {year: number; month: number; day: number};
if (typeof dateOfBirth === 'string') {
const [year, month, day] = dateOfBirth.split('-').map(Number);
- birthDate = new Date(year, month - 1, day);
+ birth = {year, month, day};
} else {
- birthDate = new Date(dateOfBirth.year, dateOfBirth.month - 1, dateOfBirth.day);
+ birth = dateOfBirth;
}
- const age = today.getFullYear() - birthDate.getFullYear();
- const monthDiff = today.getMonth() - birthDate.getMonth();
- const dayDiff = today.getDate() - birthDate.getDate();
+ const age = today.getUTCFullYear() - birth.year;
+ const monthDiff = today.getUTCMonth() + 1 - birth.month;
+ const dayDiff = today.getUTCDate() - birth.day;
return monthDiff < 0 || (monthDiff === 0 && dayDiff < 0) ? age - 1 : age;
}