A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat: verify iOS age ranges with App Attest (#3866)
Hampusc90db9349b6b
diff --git a/Cargo.lock b/Cargo.lockindex a107f1ff2..e92f7f83f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1904,18 +1904,22 @@ name = "fluxer-users"version = "0.1.0"dependencies = ["anyhow",+ "base64 0.23.1","chrono",+ "ciborium","fluxer-svc","fluxer_common","futures","hmac","moka",+ "ring","scylla","serde","serde_json","sha2 0.11.1","tokio","tracing",+ "x509-cert",][[package]]diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.jsonindex afe69d17d..eb323a988 100644--- a/fluxer_admin/openapi-admin.json+++ b/fluxer_admin/openapi-admin.json@@ -26963,6 +26963,13 @@"ACLS_MUST_BE_NON_EMPTY","ADMIN_API_KEY_NOT_FOUND","ALREADY_FRIENDS",+ "APP_ATTEST_NOT_AVAILABLE",+ "APP_ATTEST_KEY_NOT_REGISTERED",+ "APP_ATTEST_KEY_IN_USE",+ "APP_ATTEST_CHALLENGE_INVALID",+ "APP_ATTEST_ATTESTATION_INVALID",+ "APP_ATTEST_ASSERTION_INVALID",+ "APP_ATTEST_REQUEST_INVALID","BOTS_CANNOT_CREATE_GUILDS","BOTS_CANNOT_SEND_FRIEND_REQUESTS","BOT_ALREADY_IN_GUILD",@@ -27339,6 +27346,13 @@"ACLs must be non-empty.","Admin API key wasn't found.","You're already friends with this user.",+ "Age checks from the app aren't available on this instance.",+ "This device key isn't registered with your account.",+ "This device key is already registered to another account.",+ "This check has expired or was already used. Try again.",+ "We couldn't confirm this device key.",+ "We couldn't confirm this age check from your device.",+ "This age check request isn't valid.","Bots can't create communities.","Bots can't send friend requests.","This bot is already in the community.",diff --git a/fluxer_api/src/api/Tables.ts b/fluxer_api/src/api/Tables.tsindex 13d441aa4..22337ee25 100644--- a/fluxer_api/src/api/Tables.ts+++ b/fluxer_api/src/api/Tables.ts@@ -1125,6 +1125,34 @@ export const WebAuthnCredentialLookup = defineTable<columns: ['credential_id', 'user_id'],primaryKey: ['credential_id'],});+export const AppAttestKeys = defineTable<+ {+ user_id: UserID;+ key_id: string;+ public_key: Buffer;+ environment: string;+ app_id: string;+ counter: bigint;+ created_at: Date;+ last_used_at: Date | null;+ },+ 'user_id' | 'key_id'+>({+ name: 'app_attest_keys',+ columns: ['user_id', 'key_id', 'public_key', 'environment', 'app_id', 'counter', 'created_at', 'last_used_at'],+ primaryKey: ['user_id', 'key_id'],+});+export const AppAttestKeyLookup = defineTable<+ {+ key_id: string;+ user_id: UserID;+ },+ 'key_id'+>({+ name: 'app_attest_key_lookup',+ columns: ['key_id', 'user_id'],+ primaryKey: ['key_id'],+});export const IpAuthorizationTokens = defineTable<IpAuthorizationTokenRow, 'token_' | 'user_id'>({name: 'ip_authorization_tokens',columns: IP_AUTHORIZATION_TOKEN_COLUMNS,diff --git a/fluxer_api/src/api/database/types/UserTypes.ts b/fluxer_api/src/api/database/types/UserTypes.tsindex da01ff28f..ce44b3946 100644--- a/fluxer_api/src/api/database/types/UserTypes.ts+++ b/fluxer_api/src/api/database/types/UserTypes.ts@@ -87,6 +87,8 @@ export interface UserRow {premium_onboarding_dismissed_at: Date | null;mention_flags?: MentionReplyPreference | null;last_voice_activity_sharing_change_at: Date | null;+ attested_age_floor?: string | null;+ age_attested_at?: Date | null;version: number;}@@ -155,6 +157,8 @@ export const USER_COLUMNS = ['premium_onboarding_dismissed_at','mention_flags','last_voice_activity_sharing_change_at',+ 'attested_age_floor',+ 'age_attested_at','version',] as const satisfies ReadonlyArray<keyof UserRow>;export const EMPTY_USER_ROW: UserRow = {@@ -222,6 +226,8 @@ export const EMPTY_USER_ROW: UserRow = {premium_onboarding_dismissed_at: null,mention_flags: null,last_voice_activity_sharing_change_at: null,+ attested_age_floor: null,+ age_attested_at: null,version: 1,};diff --git a/fluxer_api/src/api/infrastructure/UsersServiceClient.ts b/fluxer_api/src/api/infrastructure/UsersServiceClient.tsindex 087250628..bbabc5426 100644--- a/fluxer_api/src/api/infrastructure/UsersServiceClient.ts+++ b/fluxer_api/src/api/infrastructure/UsersServiceClient.ts@@ -9,6 +9,11 @@ import {awaitAll} from '@app/api/utils/ConcurrencyUtils';import {readOptionalEnv, readOptionalIntegerEnv, requireIntegerInRange} from '@app/api/utils/IntegerOptions';import {isJsonRecord} from '@app/api/utils/JsonBoundaryUtils';import {compareText} from '@app/api/utils/StringComparison';+import {+ type AppAttestChallengePurpose,+ type AttestedAgeFloor,+ isAttestedAgeFloor,+} from '@fluxer/constants/src/AgeAssuranceConstants';import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';import type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';import {NatsConnectionManager} from '@pkgs/nats/src/NatsConnectionManager';@@ -21,6 +26,46 @@ const MAX_REQUEST_TIMEOUT_MS = 2_147_483_647;export interface IUsersServiceClient {getUserPartialResponses(userIds: Array<UserID>): Promise<Map<UserID, UserPartialResponse>>;invalidateUserCache(userId: UserID): Promise<void>;+ appAttestCreateChallenge(+ userId: UserID,+ purpose: AppAttestChallengePurpose,+ ): Promise<AppAttestOutcome<AppAttestChallengeIssued>>;+ appAttestRegisterKey(params: {+ userId: UserID;+ keyId: string;+ attestationBase64: string;+ challenge: string;+ }): Promise<AppAttestOutcome<true>>;+ appAttestSubmitAge(params: {+ userId: UserID;+ keyId: string;+ assertionBase64: string;+ clientDataBase64: string;+ }): Promise<AppAttestOutcome<AppAttestAgeAccepted>>;+}++const APP_ATTEST_REJECTION_CODES = [+ 'not_configured',+ 'invalid_request',+ 'invalid_challenge',+ 'invalid_attestation',+ 'key_in_use',+ 'unknown_key',+ 'invalid_assertion',+] as const;++export type AppAttestRejectionCode = (typeof APP_ATTEST_REJECTION_CODES)[number];++export type AppAttestOutcome<T> = {ok: true; value: T} | {ok: false; code: AppAttestRejectionCode};++export interface AppAttestChallengeIssued {+ challenge: string;+ expires_at: string;+}++export interface AppAttestAgeAccepted {+ age_floor: AttestedAgeFloor;+ attested_at: string;}type PendingUserPartials = Promise<Map<UserID, UserPartialResponse>>;@@ -34,6 +79,25 @@ type UsersServiceRequest =| {op: 'Invalidate';user_id: string;+ }+ | {+ op: 'AppAttestCreateChallenge';+ user_id: string;+ purpose: AppAttestChallengePurpose;+ }+ | {+ op: 'AppAttestRegisterKey';+ user_id: string;+ key_id: string;+ attestation_base64: string;+ challenge: string;+ }+ | {+ op: 'AppAttestSubmitAge';+ user_id: string;+ key_id: string;+ assertion_base64: string;+ client_data_base64: string;};interface UserPartialsResponse {@@ -50,6 +114,32 @@ function isUserPartialsResponse(value: unknown): value is UserPartialsResponse {);}+function isAppAttestRejectionCode(value: unknown): value is AppAttestRejectionCode {+ return typeof value === 'string' && (APP_ATTEST_REJECTION_CODES as ReadonlyArray<string>).includes(value);+}++function rejectedCode(value: unknown): AppAttestRejectionCode | null {+ if (!isJsonRecord(value) || !isJsonRecord(value.AppAttestRejected)) return null;+ const code = value.AppAttestRejected.code;+ return isAppAttestRejectionCode(code) ? code : null;+}++function acceptChallenge(value: unknown): AppAttestChallengeIssued | null {+ if (!isJsonRecord(value) || !isJsonRecord(value.AppAttestChallenge)) return null;+ const {challenge, expires_at} = value.AppAttestChallenge;+ return typeof challenge === 'string' && typeof expires_at === 'string' ? {challenge, expires_at} : null;+}++function acceptKeyRegistered(value: unknown): true | null {+ return value === 'AppAttestKeyRegistered' ? true : null;+}++function acceptAge(value: unknown): AppAttestAgeAccepted | null {+ if (!isJsonRecord(value) || !isJsonRecord(value.AppAttestAgeAccepted)) return null;+ const {age_floor, attested_at} = value.AppAttestAgeAccepted;+ return isAttestedAgeFloor(age_floor) && typeof attested_at === 'string' ? {age_floor, attested_at} : null;+}+export class NatsUsersServiceClient implements IUsersServiceClient {private readonly inflightPartials = new Map<UserID, PendingUserPartials>();@@ -156,6 +246,67 @@ export class NatsUsersServiceClient implements IUsersServiceClient {}}+ async appAttestCreateChallenge(+ userId: UserID,+ purpose: AppAttestChallengePurpose,+ ): Promise<AppAttestOutcome<AppAttestChallengeIssued>> {+ return this.appAttestRequest(+ {op: 'AppAttestCreateChallenge', user_id: userId.toString(), purpose},+ acceptChallenge,+ );+ }++ async appAttestRegisterKey(params: {+ userId: UserID;+ keyId: string;+ attestationBase64: string;+ challenge: string;+ }): Promise<AppAttestOutcome<true>> {+ return this.appAttestRequest(+ {+ op: 'AppAttestRegisterKey',+ user_id: params.userId.toString(),+ key_id: params.keyId,+ attestation_base64: params.attestationBase64,+ challenge: params.challenge,+ },+ acceptKeyRegistered,+ );+ }++ async appAttestSubmitAge(params: {+ userId: UserID;+ keyId: string;+ assertionBase64: string;+ clientDataBase64: string;+ }): Promise<AppAttestOutcome<AppAttestAgeAccepted>> {+ return this.appAttestRequest(+ {+ op: 'AppAttestSubmitAge',+ user_id: params.userId.toString(),+ key_id: params.keyId,+ assertion_base64: params.assertionBase64,+ client_data_base64: params.clientDataBase64,+ },+ acceptAge,+ );+ }++ private async appAttestRequest<T>(+ payload: UsersServiceRequest,+ accept: (value: unknown) => T | null,+ ): Promise<AppAttestOutcome<T>> {+ const reply = await this.request(+ payload,+ (value): value is unknown => rejectedCode(value) !== null || accept(value) !== null,+ );+ const code = rejectedCode(reply);+ if (code !== null) return {ok: false, code};+ const accepted = accept(reply);+ if (accepted === null) throw new Error('[users-service] invalid App Attest response payload');+ return {ok: true, value: accepted};+ }+private async request<T>(payload: UsersServiceRequest, responseGuard: (value: unknown) => value is T): Promise<T> {try {return await requestSvcJson(this.connectionManager, this.subject, payload, {diff --git a/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.ts b/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.tsindex f5480b00e..f8be09a14 100644--- a/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.ts+++ b/fluxer_api/src/api/middleware/DateOfBirthGateMiddleware.ts@@ -15,6 +15,8 @@ export const DATE_OF_BIRTH_ALLOWLIST: ReadonlyArray<{method: string; path: RegEx{method: 'POST', path: /^\/users\/@me\/delete$/},{method: 'POST', path: /^\/users\/@me\/disable$/},{method: 'POST', path: /^\/users\/@me\/terms-acceptance$/},+ {method: 'POST', path: /^\/users\/@me\/app-attest\/(challenge|keys)$/},+ {method: 'POST', path: /^\/users\/@me\/age-assurance$/},{method: 'GET', path: /^\/users\/@me\/harvest(\/[^/]+)*$/},{method: 'POST', path: /^\/users\/@me\/harvest(\/[^/]+)*$/},{method: 'GET', path: /^\/experiments$/},diff --git a/fluxer_api/src/api/models/User.ts b/fluxer_api/src/api/models/User.tsindex f6741ef5c..a017e666a 100644--- a/fluxer_api/src/api/models/User.ts+++ b/fluxer_api/src/api/models/User.ts@@ -4,6 +4,7 @@ import type {UserID} from '@app/api/BrandedTypes';import {LocalDate} from '@app/api/database/LocalDate';import type {UserRow} from '@app/api/database/types/UserTypes';import {checkIsPremium, getEffectivePremiumUntil} from '@app/api/user/UserHelpers';+import {type AttestedAgeFloor, isAttestedAgeFloor} from '@fluxer/constants/src/AgeAssuranceConstants';import {isProfileBadgeKey, type ProfileBadgeKey} from '@fluxer/constants/src/BadgeConstants';import {extractPremiumFlagsFromLegacyUserFlags,@@ -79,6 +80,8 @@ export class User {readonly premiumOnboardingDismissedAt: Date | null;readonly mentionFlags: MentionReplyPreference;readonly lastVoiceActivitySharingChangeAt: Date | null;+ readonly attestedAgeFloor: AttestedAgeFloor | null;+ readonly ageAttestedAt: Date | null;readonly version: number;constructor(row: UserRow) {@@ -150,6 +153,8 @@ export class User {this.premiumOnboardingDismissedAt = row.premium_onboarding_dismissed_at ?? null;this.mentionFlags = row.mention_flags ?? 0;this.lastVoiceActivitySharingChangeAt = row.last_voice_activity_sharing_change_at ?? null;+ this.attestedAgeFloor = isAttestedAgeFloor(row.attested_age_floor) ? row.attested_age_floor : null;+ this.ageAttestedAt = row.age_attested_at ?? null;this.version = row.version;}@@ -231,6 +236,8 @@ export class User {premium_onboarding_dismissed_at: this.premiumOnboardingDismissedAt,mention_flags: this.mentionFlags,last_voice_activity_sharing_change_at: this.lastVoiceActivitySharingChangeAt,+ attested_age_floor: this.attestedAgeFloor,+ age_attested_at: this.ageAttestedAt,version: this.version,};}diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.jsonindex 84741ff7e..085f0ec27 100644--- a/fluxer_api/src/api/openapi/openapi.json+++ b/fluxer_api/src/api/openapi/openapi.json@@ -17834,6 +17834,190 @@}}},+ "/users/@me/age-assurance": {+ "post": {+ "operationId": "submit_age_assurance",+ "summary": "Submit attested age floor",+ "tags": ["Users"],+ "responses": {+ "200": {+ "description": "Success",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AgeAssuranceSubmitResponse"}}}+ },+ "400": {+ "description": "Bad Request - The request was malformed or contained invalid data",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "401": {+ "description": "Unauthorized - Authentication is required or the token is invalid",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "403": {+ "description": "Forbidden - You do not have permission to perform this action",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "404": {+ "description": "Not Found - The requested resource was not found",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "429": {+ "description": "Too Many Requests - You are being rate limited",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},+ "headers": {+ "Retry-After": {+ "description": "Number of seconds to wait before retrying (only on 429)",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Limit": {+ "description": "The number of requests that can be made in the current window",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Remaining": {+ "description": "The number of remaining requests that can be made",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Reset": {+ "description": "Unix timestamp when the rate limit resets",+ "schema": {"type": "integer"}+ }+ }+ },+ "500": {+ "description": "Internal Server Error - An unexpected error occurred",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ }+ },+ "description": "Submits the age floor the device reported, signed by a registered App Attest key. client_data holds the exact JSON bytes the app signed, with the challenge from a challenge with purpose assert and the age_floor. The newest accepted floor replaces the stored one. The stored floor decides the age of the account in place of its date of birth: adult makes age-restricted content available, and minor or under_minimum makes it unavailable. An adult or minor floor also counts as a date of birth for routes that need one. Returns APP_ATTEST_KEY_NOT_REGISTERED when the key is unknown, in which case the app should register a new key. Returns APP_ATTEST_NOT_AVAILABLE with status 404 when this instance does not accept App Attest.",+ "security": [{"sessionToken": []}],+ "requestBody": {+ "required": true,+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AgeAssuranceSubmitRequest"}}}+ }+ }+ },+ "/users/@me/app-attest/challenge": {+ "post": {+ "operationId": "create_app_attest_challenge",+ "summary": "Create App Attest challenge",+ "tags": ["Users"],+ "responses": {+ "200": {+ "description": "Success",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AppAttestChallengeResponse"}}}+ },+ "400": {+ "description": "Bad Request - The request was malformed or contained invalid data",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "401": {+ "description": "Unauthorized - Authentication is required or the token is invalid",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "403": {+ "description": "Forbidden - You do not have permission to perform this action",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "404": {+ "description": "Not Found - The requested resource was not found",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "429": {+ "description": "Too Many Requests - You are being rate limited",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},+ "headers": {+ "Retry-After": {+ "description": "Number of seconds to wait before retrying (only on 429)",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Limit": {+ "description": "The number of requests that can be made in the current window",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Remaining": {+ "description": "The number of remaining requests that can be made",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Reset": {+ "description": "Unix timestamp when the rate limit resets",+ "schema": {"type": "integer"}+ }+ }+ },+ "500": {+ "description": "Internal Server Error - An unexpected error occurred",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ }+ },+ "description": "Creates a single use challenge for the iOS app, valid for 5 minutes. Use purpose attest before registering a new App Attest key, and purpose assert before submitting an age floor. Returns APP_ATTEST_NOT_AVAILABLE with status 404 when this instance does not accept App Attest.",+ "security": [{"sessionToken": []}],+ "requestBody": {+ "required": true,+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AppAttestChallengeRequest"}}}+ }+ }+ },+ "/users/@me/app-attest/keys": {+ "post": {+ "operationId": "register_app_attest_key",+ "summary": "Register App Attest key",+ "tags": ["Users"],+ "responses": {+ "204": {"description": "No Content"},+ "400": {+ "description": "Bad Request - The request was malformed or contained invalid data",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "401": {+ "description": "Unauthorized - Authentication is required or the token is invalid",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "403": {+ "description": "Forbidden - You do not have permission to perform this action",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "404": {+ "description": "Not Found - The requested resource was not found",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "409": {+ "description": "Conflict - The request conflicts with the current state of the resource",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "429": {+ "description": "Too Many Requests - You are being rate limited",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},+ "headers": {+ "Retry-After": {+ "description": "Number of seconds to wait before retrying (only on 429)",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Limit": {+ "description": "The number of requests that can be made in the current window",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Remaining": {+ "description": "The number of remaining requests that can be made",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Reset": {+ "description": "Unix timestamp when the rate limit resets",+ "schema": {"type": "integer"}+ }+ }+ },+ "500": {+ "description": "Internal Server Error - An unexpected error occurred",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ }+ },+ "description": "Registers an App Attest key for the current user. The attestation must be made with clientDataHash set to the SHA-256 of the UTF-8 challenge string from a challenge with purpose attest. The server keeps the key id, public key, environment, App ID and counter, and does not keep the attestation itself. Registering the same key again for the same user succeeds and changes nothing. Returns APP_ATTEST_NOT_AVAILABLE with status 404 when this instance does not accept App Attest.",+ "security": [{"sessionToken": []}],+ "requestBody": {+ "required": true,+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AppAttestKeyRegisterRequest"}}}+ }+ }+ },"/users/@me/applications": {"get": {"operationId": "list_user_applications",@@ -31655,6 +31839,90 @@"items": {"$ref": "#/components/schemas/BillingDocumentResponse"}},"ApplicationListResponse": {"type": "array", "items": {"$ref": "#/components/schemas/ApplicationResponse"}},+ "AppAttestKeyRegisterRequest": {+ "type": "object",+ "properties": {+ "key_id": {+ "type": "string",+ "minLength": 44,+ "maxLength": 44,+ "description": "App Attest key identifier from DCAppAttestService, 32 bytes as standard base64"+ },+ "attestation": {+ "type": "string",+ "minLength": 4,+ "maxLength": 21848,+ "description": "Attestation object from DCAppAttestService.attestKey as standard base64"+ },+ "challenge": {+ "type": "string",+ "minLength": 43,+ "maxLength": 43,+ "description": "Challenge from the challenge endpoint, 32 bytes as unpadded base64url"+ }+ },+ "required": ["key_id", "attestation", "challenge"]+ },+ "AppAttestChallengeRequest": {+ "type": "object",+ "properties": {+ "purpose": {+ "description": "What the challenge will be used for",+ "x-enumNames": ["ATTEST", "ASSERT"],+ "x-enumDescriptions": [+ "Challenge for registering a new App Attest key",+ "Challenge for an assertion signed by a registered key"+ ],+ "enum": ["attest", "assert"],+ "type": "string"+ }+ },+ "required": ["purpose"]+ },+ "AppAttestChallengeResponse": {+ "type": "object",+ "properties": {+ "challenge": {"type": "string", "description": "Single use challenge, 32 bytes as unpadded base64url"},+ "expires_at": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$",+ "description": "When the challenge stops working"+ }+ },+ "required": ["challenge", "expires_at"],+ "additionalProperties": false+ },+ "AgeAssuranceSubmitRequest": {+ "type": "object",+ "properties": {+ "key_id": {+ "type": "string",+ "minLength": 44,+ "maxLength": 44,+ "description": "App Attest key identifier from DCAppAttestService, 32 bytes as standard base64"+ },+ "assertion": {+ "type": "string",+ "minLength": 4,+ "maxLength": 5464,+ "description": "Assertion from DCAppAttestService.generateAssertion as standard base64"+ },+ "client_data": {+ "type": "string",+ "minLength": 4,+ "maxLength": 1368,+ "description": "The exact UTF-8 JSON bytes the app signed, as standard base64. The JSON holds challenge and age_floor"+ }+ },+ "required": ["key_id", "assertion", "client_data"]+ },+ "AgeAssuranceSubmitResponse": {+ "type": "object",+ "properties": {"age_floor": {"$ref": "#/components/schemas/AttestedAgeFloorSchema"}},+ "required": ["age_floor"],+ "additionalProperties": false+ },"UserUpdateWithVerificationRequest": {"type": "object","properties": {@@ -45557,6 +45825,17 @@},"description": "The full list of badge keys to hide from other people. It replaces the stored list, takes precedence over the deprecated hide fields, and keys of custom badges that no longer exist are dropped"},+ "AttestedAgeFloorSchema": {+ "description": "Age floor reported by the device",+ "x-enumNames": ["ADULT", "MINOR", "UNDER_MINIMUM"],+ "x-enumDescriptions": [+ "The device reports an adult",+ "The device reports someone under 18",+ "The device reports someone under 13"+ ],+ "enum": ["adult", "minor", "under_minimum"],+ "type": "string"+ },"ConfirmEmailClaimAccountResponse": {"type": "object","properties": {@@ -46504,6 +46783,13 @@"ACLS_MUST_BE_NON_EMPTY","ADMIN_API_KEY_NOT_FOUND","ALREADY_FRIENDS",+ "APP_ATTEST_NOT_AVAILABLE",+ "APP_ATTEST_KEY_NOT_REGISTERED",+ "APP_ATTEST_KEY_IN_USE",+ "APP_ATTEST_CHALLENGE_INVALID",+ "APP_ATTEST_ATTESTATION_INVALID",+ "APP_ATTEST_ASSERTION_INVALID",+ "APP_ATTEST_REQUEST_INVALID","BOTS_CANNOT_CREATE_GUILDS","BOTS_CANNOT_SEND_FRIEND_REQUESTS","BOT_ALREADY_IN_GUILD",@@ -46880,6 +47166,13 @@"ACLs must be non-empty.","Admin API key wasn't found.","You're already friends with this user.",+ "Age checks from the app aren't available on this instance.",+ "This device key isn't registered with your account.",+ "This device key is already registered to another account.",+ "This check has expired or was already used. Try again.",+ "We couldn't confirm this device key.",+ "We couldn't confirm this age check from your device.",+ "This age check request isn't valid.","Bots can't create communities.","Bots can't send friend requests.","This bot is already in the community.",diff --git a/fluxer_api/src/api/rate_limit_configs/UserRateLimitConfig.ts b/fluxer_api/src/api/rate_limit_configs/UserRateLimitConfig.tsindex dc7a7e655..be2b8d45c 100644--- a/fluxer_api/src/api/rate_limit_configs/UserRateLimitConfig.ts+++ b/fluxer_api/src/api/rate_limit_configs/UserRateLimitConfig.ts@@ -256,6 +256,18 @@ export const UserRateLimitConfigs = {bucket: 'user:entrance_sound:mutate',config: {limit: 20, windowMs: ms('1 minute')},} as RouteRateLimitConfig,+ USER_APP_ATTEST_CHALLENGE: {+ bucket: 'user:app_attest:challenge',+ config: {limit: 10, windowMs: ms('1 minute')},+ } as RouteRateLimitConfig,+ USER_APP_ATTEST_KEY_REGISTER: {+ bucket: 'user:app_attest:key_register',+ config: {limit: 6, windowMs: ms('1 minute')},+ } as RouteRateLimitConfig,+ USER_AGE_ASSURANCE_SUBMIT: {+ bucket: 'user:age_assurance:submit',+ config: {limit: 6, windowMs: ms('1 minute')},+ } as RouteRateLimitConfig,USER_DATE_OF_BIRTH: {bucket: 'user:date_of_birth',config: {limit: 5, windowMs: ms('1 hour')},diff --git a/fluxer_api/src/api/rpc/RpcService.ts b/fluxer_api/src/api/rpc/RpcService.tsindex 2450eec24..61bfb500f 100644--- a/fluxer_api/src/api/rpc/RpcService.ts+++ b/fluxer_api/src/api/rpc/RpcService.ts@@ -1634,7 +1634,11 @@ export class RpcService {const needsIncomingCallRepair = settings.incomingCallFlags === 0;const needsGroupDmRepair = settings.groupDmAddPermissionFlags === 0;if (needsIncomingCallRepair || needsGroupDmRepair) {- const isAdult = canUserAccessNsfwContent({isBot: false, dateOfBirth: user.dateOfBirth});+ const isAdult = canUserAccessNsfwContent({+ isBot: false,+ dateOfBirth: user.dateOfBirth,+ attestedAgeFloor: user.attestedAgeFloor,+ });const baseRow = settings.toRow();const updatedRow = {...baseRow,diff --git a/fluxer_api/src/api/test/Setup.ts b/fluxer_api/src/api/test/Setup.tsindex 1eef1a737..1ac9cca7e 100644--- a/fluxer_api/src/api/test/Setup.ts+++ b/fluxer_api/src/api/test/Setup.ts@@ -11,7 +11,12 @@ import {setCassandraQueryExecutorForTesting,shutdownCassandraQueryExecutorForTesting,} from '@app/api/database/CassandraQueryExecution';-import type {IUsersServiceClient} from '@app/api/infrastructure/UsersServiceClient';+import type {+ AppAttestAgeAccepted,+ AppAttestChallengeIssued,+ AppAttestOutcome,+ IUsersServiceClient,+} from '@app/api/infrastructure/UsersServiceClient';import {setInjectedUsersServiceClient} from '@app/api/infrastructure/UsersServiceClient';import {initializeLogger} from '@app/api/Logger';import {setInjectedKVProvider, setInjectedSnowflakeService} from '@app/api/middleware/ServiceRegistry';@@ -112,6 +117,18 @@ class RepositoryBackedUsersServiceClient implements IUsersServiceClient {}async invalidateUserCache(_userId: UserID): Promise<void> {}++ async appAttestCreateChallenge(): Promise<AppAttestOutcome<AppAttestChallengeIssued>> {+ return {ok: false, code: 'not_configured'};+ }++ async appAttestRegisterKey(): Promise<AppAttestOutcome<true>> {+ return {ok: false, code: 'not_configured'};+ }++ async appAttestSubmitAge(): Promise<AppAttestOutcome<AppAttestAgeAccepted>> {+ return {ok: false, code: 'not_configured'};+ }}setDefaultTestEnv();diff --git a/fluxer_api/src/api/user/AccountTier.ts b/fluxer_api/src/api/user/AccountTier.tsindex 59dd67b77..474cabe4b 100644--- a/fluxer_api/src/api/user/AccountTier.ts+++ b/fluxer_api/src/api/user/AccountTier.ts@@ -14,7 +14,7 @@ import type {User} from '@app/api/models/User';import type {HonoEnv} from '@app/api/types/HonoEnv';import type {UserRepository} from '@app/api/user/repositories/UserRepository';import {UserTraits} from '@app/api/user/UserTraits';-import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';+import {canUserAccessNsfwContent, hasAttestedAge} from '@app/api/utils/AgeUtils';import {EmailDeliveryStates, InteractionTierModes} from '@fluxer/constants/src/AccountConfigConstants';import {type AccountTier,@@ -239,11 +239,17 @@ export function resolvePurchaseEligibility(user: TierUser): PurchaseEligibilityreturn blocked === null ? {allowed: true} : {allowed: false, blocked};}-type VisitUser = Pick<User, 'isBot' | 'isSystem' | 'dateOfBirth'> & {traits: ReadonlySet<string>};+type VisitUser = Pick<User, 'isBot' | 'isSystem' | 'dateOfBirth' | 'attestedAgeFloor'> & {traits: ReadonlySet<string>};export function assertCanVisit(user: VisitUser, guild: {nsfw: boolean}): {adult_content_allowed: boolean} {if (user.traits.has(UserTraits.BELOW_MINIMUM_AGE)) throw new AccountBelowMinimumAgeError();- if (!user.isBot && !user.isSystem && instanceCollectsDateOfBirth() && user.dateOfBirth === null) {+ if (+ !user.isBot &&+ !user.isSystem &&+ instanceCollectsDateOfBirth() &&+ user.dateOfBirth === null &&+ !hasAttestedAge(user.attestedAgeFloor)+ ) {throw new DateOfBirthRequiredError();}const adultContentAllowed = canUserAccessNsfwContent(user);diff --git a/fluxer_api/src/api/user/AgeAssurance.ts b/fluxer_api/src/api/user/AgeAssurance.tsnew file mode 100644index 000000000..4d14502ac--- /dev/null+++ b/fluxer_api/src/api/user/AgeAssurance.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {ApiContext} from '@app/api/ApiContext';+import type {UserID} from '@app/api/BrandedTypes';+import {executeConditional, fetchMany} from '@app/api/database/CassandraQueryExecution';+import {+ type AppAttestOutcome,+ type AppAttestRejectionCode,+ createUsersServiceClient,+} from '@app/api/infrastructure/UsersServiceClient';+import type {User} from '@app/api/models/User';+import {AppAttestKeyLookup, AppAttestKeys} from '@app/api/Tables';+import {settingsForAge} from '@app/api/user/DateOfBirth';+import {mapUserSettingsToResponse, mapUserToPrivateResponse} from '@app/api/user/UserMappers';+import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';+import type {AppAttestChallengePurpose} from '@fluxer/constants/src/AgeAssuranceConstants';+import {AppAttestAssertionInvalidError} from '@fluxer/errors/src/domains/user/AppAttestAssertionInvalidError';+import {AppAttestAttestationInvalidError} from '@fluxer/errors/src/domains/user/AppAttestAttestationInvalidError';+import {AppAttestChallengeInvalidError} from '@fluxer/errors/src/domains/user/AppAttestChallengeInvalidError';+import {AppAttestKeyInUseError} from '@fluxer/errors/src/domains/user/AppAttestKeyInUseError';+import {AppAttestKeyNotRegisteredError} from '@fluxer/errors/src/domains/user/AppAttestKeyNotRegisteredError';+import {AppAttestNotAvailableError} from '@fluxer/errors/src/domains/user/AppAttestNotAvailableError';+import {AppAttestRequestInvalidError} from '@fluxer/errors/src/domains/user/AppAttestRequestInvalidError';+import type {+ AgeAssuranceSubmitRequest,+ AgeAssuranceSubmitResponse,+ AppAttestChallengeResponse,+ AppAttestKeyRegisterRequest,+} from '@fluxer/schema/src/domains/user/AgeAssuranceSchemas';++const FETCH_APP_ATTEST_KEYS_FOR_USER_CQL = AppAttestKeys.selectCql({+ columns: ['key_id', 'app_id'],+ where: AppAttestKeys.where.eq('user_id'),+});++function rejectionError(code: AppAttestRejectionCode): Error {+ switch (code) {+ case 'not_configured':+ return new AppAttestNotAvailableError();+ case 'invalid_request':+ return new AppAttestRequestInvalidError();+ case 'invalid_challenge':+ return new AppAttestChallengeInvalidError();+ case 'invalid_attestation':+ return new AppAttestAttestationInvalidError();+ case 'key_in_use':+ return new AppAttestKeyInUseError();+ case 'unknown_key':+ return new AppAttestKeyNotRegisteredError();+ case 'invalid_assertion':+ return new AppAttestAssertionInvalidError();+ }+}++function unwrap<T>(outcome: AppAttestOutcome<T>): T {+ if (!outcome.ok) throw rejectionError(outcome.code);+ return outcome.value;+}++export async function createAppAttestChallenge(+ userId: UserID,+ purpose: AppAttestChallengePurpose,+): Promise<AppAttestChallengeResponse> {+ return unwrap(await createUsersServiceClient().appAttestCreateChallenge(userId, purpose));+}++export async function registerAppAttestKey(userId: UserID, request: AppAttestKeyRegisterRequest): Promise<void> {+ unwrap(+ await createUsersServiceClient().appAttestRegisterKey({+ userId,+ keyId: request.key_id,+ attestationBase64: request.attestation,+ challenge: request.challenge,+ }),+ );+}++export async function submitAttestedAge(+ ctx: ApiContext,+ user: User,+ request: AgeAssuranceSubmitRequest,+): Promise<AgeAssuranceSubmitResponse> {+ const accepted = unwrap(+ await createUsersServiceClient().appAttestSubmitAge({+ userId: user.id,+ keyId: request.key_id,+ assertionBase64: request.assertion,+ clientDataBase64: request.client_data,+ }),+ );+ const attestedAt = new Date(accepted.attested_at);+ if (user.ageAttestedAt !== null && user.ageAttestedAt.getTime() > attestedAt.getTime()) {+ return {age_floor: accepted.age_floor};+ }+ const updated = await ctx.services.users.patchUpsert(+ user.id,+ {attested_age_floor: accepted.age_floor, age_attested_at: attestedAt},+ user.toRow(),+ );+ if (canUserAccessNsfwContent(user) !== canUserAccessNsfwContent(updated)) {+ const settings = await ctx.services.users.findSettings(user.id);+ const adjusted = settings ? settingsForAge(settings, canUserAccessNsfwContent(updated)) : 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}),+ });+ }+ }+ if (user.attestedAgeFloor !== updated.attestedAgeFloor) {+ await ctx.services.gateway.dispatchPresence({+ userId: user.id,+ event: 'USER_UPDATE',+ data: mapUserToPrivateResponse(updated),+ });+ }+ return {age_floor: accepted.age_floor};+}++export async function deleteAllAppAttestKeys(userId: UserID): Promise<void> {+ const keys = await fetchMany<{key_id: string; app_id: string}>(FETCH_APP_ATTEST_KEYS_FOR_USER_CQL, {+ user_id: userId,+ });+ for (const key of keys) {+ await executeConditional(+ AppAttestKeys.conditionalDeleteByPk({user_id: userId, key_id: key.key_id}, {app_id: key.app_id}),+ );+ await executeConditional(AppAttestKeyLookup.conditionalDeleteByPk({key_id: key.key_id}, {user_id: userId}));+ }+}diff --git a/fluxer_api/src/api/user/DateOfBirth.ts b/fluxer_api/src/api/user/DateOfBirth.tsindex 8c332d30d..12e5fc23e 100644--- a/fluxer_api/src/api/user/DateOfBirth.ts+++ b/fluxer_api/src/api/user/DateOfBirth.ts@@ -17,7 +17,7 @@ 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 {calculateAge, canUserAccessNsfwContent, hasAttestedAge, 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';@@ -33,12 +33,15 @@ import type {DateOfBirthUpdateResponse} from '@fluxer/schema/src/domains/user/Acconst UNDERAGE_DELETION_DELAY_MS = 72 * 3600 * 1000;const ADULT_AGE = 18;-type DateOfBirthUser = Pick<User, 'isBot' | 'isSystem' | 'dateOfBirth'> & {traits: ReadonlySet<string>};+type DateOfBirthUser = Pick<User, 'isBot' | 'isSystem' | 'dateOfBirth' | 'attestedAgeFloor'> & {+ traits: ReadonlySet<string>;+};export function isDateOfBirthMissing(user: DateOfBirthUser): boolean {return (instanceCollectsDateOfBirth() &&user.dateOfBirth === null &&+ !hasAttestedAge(user.attestedAgeFloor) &&!user.isBot &&!user.isSystem &&!user.traits.has(BELOW_MINIMUM_AGE_TRAIT)@@ -58,7 +61,7 @@ export function isDateOfBirthEnforced(user: DateOfBirthUser): boolean {}}-function settingsForAge(settings: UserSettings, adult: boolean): UserSettings | null {+export 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,@@ -171,7 +174,7 @@ export async function setDateOfBirth();const adult = age >= ADULT_AGE;const settings = await ctx.services.users.findSettings(user.id);- const adjusted = settings ? settingsForAge(settings, adult) : null;+ const adjusted = settings ? settingsForAge(settings, canUserAccessNsfwContent(updated)) : null;if (adjusted) {const saved = await ctx.services.users.upsertSettings(adjusted.toRow());await ctx.services.gateway.dispatchPresence({diff --git a/fluxer_api/src/api/user/controllers/UserAccountController.ts b/fluxer_api/src/api/user/controllers/UserAccountController.tsindex 2e73f907e..35f5ffbe7 100644--- a/fluxer_api/src/api/user/controllers/UserAccountController.ts+++ b/fluxer_api/src/api/user/controllers/UserAccountController.ts@@ -756,7 +756,7 @@ export function UserAccountController(app: HonoApp) {const updatedSettings = await ctx.get('userService').accountService.settingsService.updateSettings({userId: user.id,data: ctx.req.valid('json'),- dateOfBirth: user.dateOfBirth,+ ageUser: user,flags: user.flags,});return ctx.json(mapUserSettingsToResponse({settings: updatedSettings}));diff --git a/fluxer_api/src/api/user/controllers/UserAgeAssuranceController.ts b/fluxer_api/src/api/user/controllers/UserAgeAssuranceController.tsnew file mode 100644index 000000000..1f73b6c7f--- /dev/null+++ b/fluxer_api/src/api/user/controllers/UserAgeAssuranceController.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {DefaultUserOnly, LoginRequired} from '@app/api/middleware/AuthMiddleware';+import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';+import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';+import {RateLimitConfigs} from '@app/api/RateLimitConfig';+import type {HonoApp} from '@app/api/types/HonoEnv';+import {createAppAttestChallenge, registerAppAttestKey, submitAttestedAge} from '@app/api/user/AgeAssurance';+import {Validator} from '@app/api/Validator';+import {+ AgeAssuranceSubmitRequest,+ AgeAssuranceSubmitResponse,+ AppAttestChallengeRequest,+ AppAttestChallengeResponse,+ AppAttestKeyRegisterRequest,+} from '@fluxer/schema/src/domains/user/AgeAssuranceSchemas';++export function UserAgeAssuranceController(app: HonoApp) {+ app.post(+ '/users/@me/app-attest/challenge',+ RateLimitMiddleware(RateLimitConfigs.USER_APP_ATTEST_CHALLENGE),+ LoginRequired,+ DefaultUserOnly,+ Validator('json', AppAttestChallengeRequest),+ OpenAPI({+ operationId: 'create_app_attest_challenge',+ summary: 'Create App Attest challenge',+ responseSchema: AppAttestChallengeResponse,+ statusCode: 200,+ errorStatusCodes: [404],+ security: ['bearerToken', 'sessionToken'],+ tags: ['Users'],+ description:+ 'Creates a single use challenge for the iOS app, valid for 5 minutes. Use purpose attest before registering a new App Attest key, and purpose assert before submitting an age floor. Returns APP_ATTEST_NOT_AVAILABLE with status 404 when this instance does not accept App Attest.',+ }),+ async (ctx) => {+ return ctx.json(await createAppAttestChallenge(ctx.get('user').id, ctx.req.valid('json').purpose));+ },+ );+ app.post(+ '/users/@me/app-attest/keys',+ RateLimitMiddleware(RateLimitConfigs.USER_APP_ATTEST_KEY_REGISTER),+ LoginRequired,+ DefaultUserOnly,+ Validator('json', AppAttestKeyRegisterRequest),+ OpenAPI({+ operationId: 'register_app_attest_key',+ summary: 'Register App Attest key',+ responseSchema: null,+ statusCode: 204,+ errorStatusCodes: [404, 409],+ security: ['bearerToken', 'sessionToken'],+ tags: ['Users'],+ description:+ 'Registers an App Attest key for the current user. The attestation must be made with clientDataHash set to the SHA-256 of the UTF-8 challenge string from a challenge with purpose attest. The server keeps the key id, public key, environment, App ID and counter, and does not keep the attestation itself. Registering the same key again for the same user succeeds and changes nothing. Returns APP_ATTEST_NOT_AVAILABLE with status 404 when this instance does not accept App Attest.',+ }),+ async (ctx) => {+ await registerAppAttestKey(ctx.get('user').id, ctx.req.valid('json'));+ return ctx.body(null, 204);+ },+ );+ app.post(+ '/users/@me/age-assurance',+ RateLimitMiddleware(RateLimitConfigs.USER_AGE_ASSURANCE_SUBMIT),+ LoginRequired,+ DefaultUserOnly,+ Validator('json', AgeAssuranceSubmitRequest),+ OpenAPI({+ operationId: 'submit_age_assurance',+ summary: 'Submit attested age floor',+ responseSchema: AgeAssuranceSubmitResponse,+ statusCode: 200,+ errorStatusCodes: [404],+ security: ['bearerToken', 'sessionToken'],+ tags: ['Users'],+ description:+ 'Submits the age floor the device reported, signed by a registered App Attest key. client_data holds the exact JSON bytes the app signed, with the challenge from a challenge with purpose assert and the age_floor. The newest accepted floor replaces the stored one. The stored floor decides the age of the account in place of its date of birth: adult makes age-restricted content available, and minor or under_minimum makes it unavailable. An adult or minor floor also counts as a date of birth for routes that need one. Returns APP_ATTEST_KEY_NOT_REGISTERED when the key is unknown, in which case the app should register a new key. Returns APP_ATTEST_NOT_AVAILABLE with status 404 when this instance does not accept App Attest.',+ }),+ async (ctx) => {+ return ctx.json(await submitAttestedAge(ctx.get('apiContext'), ctx.get('user'), ctx.req.valid('json')));+ },+ );+}diff --git a/fluxer_api/src/api/user/controllers/UserController.ts b/fluxer_api/src/api/user/controllers/UserController.tsindex e832b4b06..6c6da6687 100644--- a/fluxer_api/src/api/user/controllers/UserController.ts+++ b/fluxer_api/src/api/user/controllers/UserController.ts@@ -3,6 +3,7 @@import type {HonoApp} from '@app/api/types/HonoEnv';import {UserAccountController} from '@app/api/user/controllers/UserAccountController';import {UserAccountTierController} from '@app/api/user/controllers/UserAccountTierController';+import {UserAgeAssuranceController} from '@app/api/user/controllers/UserAgeAssuranceController';import {UserAuthController} from '@app/api/user/controllers/UserAuthController';import {UserChannelController} from '@app/api/user/controllers/UserChannelController';import {UserContentController} from '@app/api/user/controllers/UserContentController';@@ -13,6 +14,7 @@ import {EntranceSoundPlayController} from '@app/api/user/entrance_sound/Entranceexport function UserController(app: HonoApp) {UserAccountController(app);UserAccountTierController(app);+ UserAgeAssuranceController(app);UserAuthController(app);UserRelationshipController(app);UserChannelController(app);diff --git a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts b/fluxer_api/src/api/user/services/UserAccountSettingsService.tsindex bcf6a7e48..9e8064f78 100644--- a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts+++ b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts@@ -86,10 +86,10 @@ export class UserAccountSettingsService {async updateSettings(params: {userId: UserID;data: UserSettingsUpdateRequest;- dateOfBirth?: string | null;+ ageUser: Pick<User, 'dateOfBirth' | 'attestedAgeFloor'>;flags?: bigint;}): Promise<UserSettings> {- const {userId, data, dateOfBirth, flags = 0n} = params;+ const {userId, data, ageUser, flags = 0n} = params;const currentSettings = await this.deps.userAccountRepository.findSettings(userId);if (!currentSettings) {throw new UnknownUserError();@@ -206,7 +206,7 @@ export class UserAccountSettingsService {if (data.default_hide_muted_channels !== undefined) {updatedRowData.default_hide_muted_channels = data.default_hide_muted_channels;}- const userIsAdult = canUserAccessNsfwContent({isBot: false, dateOfBirth});+ const userIsAdult = canUserAccessNsfwContent({isBot: false, ...ageUser});if (userIsAdult) {if (data.sensitive_content_friend_dm_filter !== undefined) {updatedRowData.sensitive_content_friend_dm_filter = data.sensitive_content_friend_dm_filter;diff --git a/fluxer_api/src/api/user/services/UserDeletionService.ts b/fluxer_api/src/api/user/services/UserDeletionService.tsindex e310f1e5d..4606b909d 100644--- a/fluxer_api/src/api/user/services/UserDeletionService.ts+++ b/fluxer_api/src/api/user/services/UserDeletionService.ts@@ -34,6 +34,7 @@ import type {ApplicationRepository} from '@app/api/oauth/repositories/Applicatioimport type {OAuth2TokenRepository} from '@app/api/oauth/repositories/OAuth2TokenRepository';import {endOperatorPassesForDeletion} from '@app/api/operator_pass/OperatorPassHoldingService';import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';+import {deleteAllAppAttestKeys} from '@app/api/user/AgeAssurance';import type {UserRepository} from '@app/api/user/repositories/UserRepository';import {isPendingDeletionBlocked} from '@app/api/user/services/PendingDeletionCoordinator';import {@@ -479,6 +480,7 @@ export async function processUserDeletion(revokeAllAuthSessions({users: userRepository, gateway: gatewayService}, userId),userRepository.deleteAllMfaBackupCodes(userId),userRepository.deleteAllWebAuthnCredentials(userId),+ deleteAllAppAttestKeys(userId),deleteRecoveryKit(userId),userRepository.deleteAllPushSubscriptions(userId),userRepository.deleteAllRecentMentions(userId),diff --git a/fluxer_api/src/api/user/tests/AgeAssuranceSubmit.test.ts b/fluxer_api/src/api/user/tests/AgeAssuranceSubmit.test.tsnew file mode 100644index 000000000..f88e5a62a--- /dev/null+++ b/fluxer_api/src/api/user/tests/AgeAssuranceSubmit.test.ts@@ -0,0 +1,124 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ type AppAttestAgeAccepted,+ type AppAttestOutcome,+ createUsersServiceClient,+ type IUsersServiceClient,+ setInjectedUsersServiceClient,+} from '@app/api/infrastructure/UsersServiceClient';+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 AttestedAgeFloor, AttestedAgeFloors} from '@fluxer/constants/src/AgeAssuranceConstants';+import {SensitiveMediaFilterLevel} from '@fluxer/constants/src/UserConstants';+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';++const SUBMISSION = {key_id: `${'A'.repeat(43)}=`, assertion: 'AAAA', client_data: 'AAAA'};++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);+}++function acceptingClient(base: IUsersServiceClient, floor: AttestedAgeFloor, attestedAt: Date): IUsersServiceClient {+ return {+ getUserPartialResponses: (userIds) => base.getUserPartialResponses(userIds),+ invalidateUserCache: (userId) => base.invalidateUserCache(userId),+ appAttestCreateChallenge: (userId, purpose) => base.appAttestCreateChallenge(userId, purpose),+ appAttestRegisterKey: (params) => base.appAttestRegisterKey(params),+ appAttestSubmitAge: async (): Promise<AppAttestOutcome<AppAttestAgeAccepted>> => ({+ ok: true,+ value: {age_floor: floor, attested_at: attestedAt.toISOString()},+ }),+ };+}++describe('Age assurance submit', () => {+ let harness: ApiTestHarness;+ let base: IUsersServiceClient;+ beforeAll(async () => {+ harness = await createApiTestHarness();+ base = createUsersServiceClient();+ });+ beforeEach(async () => {+ await harness.reset();+ });+ afterEach(() => {+ setInjectedUsersServiceClient(base);+ });+ afterAll(async () => {+ await harness?.shutdown();+ });++ async function deferredAccount(): Promise<string> {+ const {token} = await createBuilderWithoutAuth<{token: string}>(harness)+ .post('/auth/register')+ .body({username: 'attested', consent: true})+ .execute();+ return token;+ }++ async function setAdultDateOfBirth(token: string): Promise<void> {+ await createBuilder(harness, token)+ .put('/users/@me/date-of-birth')+ .body({date_of_birth: yearsAgo(30)})+ .execute();+ }++ async function adultAccount(): Promise<string> {+ const token = await deferredAccount();+ await setAdultDateOfBirth(token);+ return token;+ }++ async function friendDmFilter(token: string): Promise<number> {+ return (+ await createBuilder<{sensitive_content_friend_dm_filter: number}>(harness, token)+ .get('/users/@me/settings')+ .execute()+ ).sensitive_content_friend_dm_filter;+ }++ async function submit(token: string, floor: AttestedAgeFloor, attestedAt: Date): Promise<void> {+ setInjectedUsersServiceClient(acceptingClient(base, floor, attestedAt));+ const result = await createBuilder<{age_floor: string}>(harness, token)+ .post('/users/@me/age-assurance')+ .body(SUBMISSION)+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(result.age_floor).toBe(floor);+ }++ async function nsfwAllowed(token: string): Promise<boolean> {+ return (await createBuilder<{nsfw_allowed: boolean}>(harness, token).get('/users/@me').execute()).nsfw_allowed;+ }++ it('lets an attested adult without a date of birth use the app as an adult', async () => {+ const token = await deferredAccount();+ await submit(token, AttestedAgeFloors.ADULT, new Date());+ const me = await createBuilder<{nsfw_allowed: boolean; date_of_birth_required: boolean}>(harness, token)+ .get('/users/@me')+ .execute();+ expect(me.nsfw_allowed).toBe(true);+ expect(me.date_of_birth_required).toBe(false);+ await createBuilder(harness, token).get('/users/@me/guilds').expect(HTTP_STATUS.OK).execute();+ });++ it('lets the newest attested floor decide over the date of birth', async () => {+ const token = await adultAccount();+ expect(await nsfwAllowed(token)).toBe(true);++ await submit(token, AttestedAgeFloors.MINOR, new Date());+ expect(await nsfwAllowed(token)).toBe(false);+ expect(await friendDmFilter(token)).not.toBe(SensitiveMediaFilterLevel.SHOW);++ await submit(token, AttestedAgeFloors.ADULT, new Date(Date.now() - 60_000));+ expect(await nsfwAllowed(token)).toBe(false);++ await submit(token, AttestedAgeFloors.ADULT, new Date(Date.now() + 1000));+ expect(await nsfwAllowed(token)).toBe(true);+ });+});diff --git a/fluxer_api/src/api/user/tests/DateOfBirthStep.test.ts b/fluxer_api/src/api/user/tests/DateOfBirthStep.test.tsindex b71874d6d..b576e69d0 100644--- a/fluxer_api/src/api/user/tests/DateOfBirthStep.test.ts+++ b/fluxer_api/src/api/user/tests/DateOfBirthStep.test.ts@@ -298,6 +298,9 @@ describe('Date of birth gate route coverage', () => {'POST /users/@me/harvest/filtered','POST /users/@me/sudo/email-code','POST /users/@me/sudo/webauthn/authentication-options',+ 'POST /users/@me/age-assurance',+ 'POST /users/@me/app-attest/challenge',+ 'POST /users/@me/app-attest/keys','POST /users/@me/terms-acceptance','PUT /users/@me/date-of-birth',].sort(),diff --git a/fluxer_api/src/api/utils/AgeUtils.test.ts b/fluxer_api/src/api/utils/AgeUtils.test.tsindex 83ae0eca0..f8fbf3b9c 100644--- a/fluxer_api/src/api/utils/AgeUtils.test.ts+++ b/fluxer_api/src/api/utils/AgeUtils.test.ts@@ -3,6 +3,7 @@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 {AttestedAgeFloors} from '@fluxer/constants/src/AgeAssuranceConstants';import {afterEach, describe, expect, it, vi} from 'vitest';function setDateOfBirthPolicy(dateOfBirth: DateOfBirthPolicy): void {@@ -22,32 +23,58 @@ describe('canUserAccessNsfwContent', () => {it('allows a bot whatever the instance collects', () => {setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);- expect(canUserAccessNsfwContent({isBot: true, dateOfBirth: null})).toBe(true);+ expect(canUserAccessNsfwContent({isBot: true, dateOfBirth: null, attestedAgeFloor: null})).toBe(true);});it('allows an adult when the instance collects a date of birth', () => {setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);- expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: ADULT_DATE_OF_BIRTH})).toBe(true);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: ADULT_DATE_OF_BIRTH, attestedAgeFloor: null})).toBe(+ true,+ );});it('blocks a minor when the instance collects a date of birth', () => {setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);- expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH})).toBe(false);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH, attestedAgeFloor: null})).toBe(+ false,+ );});it('blocks a missing date of birth when the instance collects one', () => {setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);- expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null})).toBe(false);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null, attestedAgeFloor: null})).toBe(false);});it('allows a missing date of birth when the instance collects none', () => {setDateOfBirthPolicy(DateOfBirthPolicies.OFF);- expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null})).toBe(true);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null, attestedAgeFloor: null})).toBe(true);});it('allows an account with a minor date of birth when the instance collects none', () => {setDateOfBirthPolicy(DateOfBirthPolicies.OFF);- expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH})).toBe(true);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH, attestedAgeFloor: null})).toBe(+ true,+ );+ });++ it('blocks an attested minor or under_minimum floor even with an adult date of birth', () => {+ for (const policy of [DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS, DateOfBirthPolicies.OFF]) {+ setDateOfBirthPolicy(policy);+ for (const attestedAgeFloor of [AttestedAgeFloors.MINOR, AttestedAgeFloors.UNDER_MINIMUM]) {+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: ADULT_DATE_OF_BIRTH, attestedAgeFloor})).toBe(+ false,+ );+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null, attestedAgeFloor})).toBe(false);+ }+ }+ });++ it('lets an attested adult floor decide over a minor or missing date of birth', () => {+ setDateOfBirthPolicy(DateOfBirthPolicies.REQUIRE_NEW_ACCOUNTS);+ const attestedAgeFloor = AttestedAgeFloors.ADULT;+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: MINOR_DATE_OF_BIRTH, attestedAgeFloor})).toBe(true);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: null, attestedAgeFloor})).toBe(true);+ expect(canUserAccessNsfwContent({isBot: false, dateOfBirth: ADULT_DATE_OF_BIRTH, attestedAgeFloor})).toBe(true);});});diff --git a/fluxer_api/src/api/utils/AgeUtils.ts b/fluxer_api/src/api/utils/AgeUtils.tsindex 797d17815..8dad12413 100644--- a/fluxer_api/src/api/utils/AgeUtils.ts+++ b/fluxer_api/src/api/utils/AgeUtils.ts@@ -2,6 +2,7 @@import {LocalDate} from '@app/api/database/LocalDate';import {instanceCollectsDateOfBirth} from '@app/api/instance/DateOfBirthCollectionCache';+import {type AttestedAgeFloor, AttestedAgeFloors} from '@fluxer/constants/src/AgeAssuranceConstants';import {isPlausibleDateOfBirth} from '@fluxer/constants/src/RegionalMinimumAge';import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';@@ -63,12 +64,23 @@ interface NsfwEligibilityUser {}| string| null;+ attestedAgeFloor: AttestedAgeFloor | null;+}++export function hasAttestedAge(attestedAgeFloor: AttestedAgeFloor | null | undefined): boolean {+ return attestedAgeFloor === AttestedAgeFloors.ADULT || attestedAgeFloor === AttestedAgeFloors.MINOR;}export function canUserAccessNsfwContent(user: NsfwEligibilityUser): boolean {if (user.isBot) {return true;}+ if (user.attestedAgeFloor === AttestedAgeFloors.ADULT) {+ return true;+ }+ if (user.attestedAgeFloor != null) {+ return false;+ }if (!instanceCollectsDateOfBirth()) {return true;}diff --git a/fluxer_docs/src/content/docs/operator/environment.mdx b/fluxer_docs/src/content/docs/operator/environment.mdxindex b4f2c7ef0..44d8871f2 100644--- a/fluxer_docs/src/content/docs/operator/environment.mdx+++ b/fluxer_docs/src/content/docs/operator/environment.mdx@@ -1264,6 +1264,14 @@ The URL of the incident history on your status page. The apps don't use it yet.Whether a new instance starts as already set up. Use `true` or `false`. With `true`, the setup wizard is skipped and registration opens without making the first account an admin. Once a setup state is saved, this has no effect. When it's empty, Fluxer uses `false`. With rexctl, use `rexctl config set FLUXER_INSTANCE_SETUP_CONFIGURED`.+### `FLUXER_APP_ATTEST_APP_IDS`++The iOS apps whose age reports the users service accepts through Apple App Attest, separated by commas. Each entry is a team ID, a dot and a bundle ID, such as `ABCDE12345.com.example.app`. When it's empty, App Attest is off and its API endpoints respond that the feature isn't available. The users service doesn't start when an entry isn't in that form. With rexctl, use `rexctl config set FLUXER_APP_ATTEST_APP_IDS`.++### `FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT`++Whether the users service also accepts App Attest keys from development builds of the apps in `FLUXER_APP_ATTEST_APP_IDS`. Use `true` or `false`. When it's empty, it uses `false`, so only App Store, TestFlight and other production builds are accepted. With rexctl, use `rexctl config set FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT`.+### `FLUXER_ACCOUNT_IDENTITY`How people sign in on a new instance. Use `username` or `email`. Fluxer uses it only on the first start with no saved sign-in method. When it's empty, Fluxer uses `email` if email delivery is set up and `username` otherwise. When `FLUXER_INSTANCE_SETUP_CONFIGURED` is `true` or any account exists, Fluxer uses email sign-in with random tags and ignores this. Otherwise the setup wizard asks again, and its answer replaces this value. With rexctl, use `rexctl config set FLUXER_ACCOUNT_IDENTITY`.diff --git a/fluxer_rexctl/internal/instance/envvars.go b/fluxer_rexctl/internal/instance/envvars.goindex 8350e29ba..fba9aa6bb 100644--- a/fluxer_rexctl/internal/instance/envvars.go+++ b/fluxer_rexctl/internal/instance/envvars.go@@ -331,6 +331,8 @@ var envVars = []envVar{{"FLUXER_APP_STATUS_PAGE_URL", "instance", "The URL of your public status page. The web app links to it when loading takes a long time. Fluxer checks whether it is an Instatus page. If it is, the web app also reads its current incidents and maintenance automatically."},{"FLUXER_APP_STATUS_PAGE_INCIDENT_HISTORY_URL", "instance", "The URL of the incident history on your status page. The apps don't use it yet."},{"FLUXER_INSTANCE_SETUP_CONFIGURED", "instance", "Whether a new instance starts as already set up. Use `true` or `false`. With `true`, the setup wizard is skipped and registration opens without making the first account an admin. Once a setup state is saved, this has no effect. When it's empty, Fluxer uses `false`."},+ {"FLUXER_APP_ATTEST_APP_IDS", "instance", "The iOS apps whose age reports the users service accepts through Apple App Attest, separated by commas. Each entry is a team ID, a dot and a bundle ID, such as `ABCDE12345.com.example.app`. When it's empty, App Attest is off and its API endpoints respond that the feature isn't available. The users service doesn't start when an entry isn't in that form."},+ {"FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT", "instance", "Whether the users service also accepts App Attest keys from development builds of the apps in FLUXER_APP_ATTEST_APP_IDS. Use `true` or `false`. When it's empty, it uses `false`, so only App Store, TestFlight and other production builds are accepted."},{"FLUXER_ACCOUNT_IDENTITY", "instance", "How people sign in on a new instance. Use `username` or `email`. Fluxer uses it only on the first start with no saved sign-in method. When it's empty, Fluxer uses `email` if email delivery is set up and `username` otherwise. When FLUXER_INSTANCE_SETUP_CONFIGURED is `true` or any account exists, Fluxer uses email sign-in with random tags and ignores this. Otherwise the setup wizard asks again, and its answer replaces this value."},{"FLUXER_TAG_STYLE", "instance", "How usernames are tagged on a new instance that signs in by email. Use `none` for unique usernames with no tag or `random` for a random tag on every account. Username sign-in always uses `none`. Fluxer reads this setting only on the first start. When it's empty, Fluxer uses `none`. When FLUXER_INSTANCE_SETUP_CONFIGURED is `true` or any account exists, Fluxer uses random tags and ignores this. Otherwise the setup wizard asks again, and its answer replaces this value."},{"FLUXER_AUTO_JOIN_INVITE_CODE", "instance", "One or more invite codes, separated by commas or spaces. A new account that signs up without an invite of its own joins the communities these invites lead to."},diff --git a/fluxer_rexctl/internal/instance/shipped.json b/fluxer_rexctl/internal/instance/shipped.jsonindex f78f63d3e..d3d969155 100644--- a/fluxer_rexctl/internal/instance/shipped.json+++ b/fluxer_rexctl/internal/instance/shipped.json@@ -15,6 +15,7 @@"1599f1c87d97dbca696a72fd7b7929d467a070bbe037ccc3944abf3ff725f7fd","1c2224572db81239f4500d051dea92aa195338d90085423c0be53f8ac70d8162","1f1f7d647217b224ab8ca7e28ab656eeaf18a3fa2dc125ab6e5a6c9f8242fa5b",+ "2782bd52c0af9ce7a1ef0103173d2f7d04b411efa471d30fef362919e4e7921e","291e8c41701e6757444b64d77df16a1c6f1916cf034f04052d6ee25172736d27","29f53f3e7053c764e3611885708fcff47ae1a8940f47d950924f989b6724591a","2b23ac88751a5e043aa48b14d1bc54336c0fca352f98825079eedb270a388b31",@@ -168,6 +169,7 @@"38e5e6fc6b7ea6f42681f9ab335b28d8d32873ab6dac8ec225d24632e4bf1642","395069f180d077b8663619946e646ed5923a9049e6763bf8561e1789698fc5bc","39f4db5c8030b2de13ff4e0452284c34dc48c4628868bcaabcce9e0eff259deb",+ "3a155ef2e4990defee5de33271e3ed2ae0b7848178c6c31c6c5f9ccab1c70e1c","3cb3b34e4c0e7aaf2234e2d397ffbd208d4b039ac8c7055682b7fed488eca141","3e3b9ddbfc31af66c7fd8f644e90fa06022278f07b794658b1a0e3365e2898c8","41d78075028923bc0e107ca08cfe06ef1f07e702cc9a230a4b01a68d582ebac2",diff --git a/fluxer_rexctl/internal/stack/files/.env.example b/fluxer_rexctl/internal/stack/files/.env.exampleindex 3a71251d0..c039988b7 100644--- a/fluxer_rexctl/internal/stack/files/.env.example+++ b/fluxer_rexctl/internal/stack/files/.env.example@@ -1838,6 +1838,21 @@ FLUXER_VAPID_PRIVATE_KEY=# rexctl: rexctl config set FLUXER_INSTANCE_SETUP_CONFIGURED# FLUXER_INSTANCE_SETUP_CONFIGURED=+# The iOS apps whose age reports the users service accepts through Apple App+# Attest, separated by commas. Each entry is a team ID, a dot and a bundle ID,+# such as ABCDE12345.com.example.app. When it's empty, App Attest is off and+# its API endpoints respond that the feature isn't available. The users+# service doesn't start when an entry isn't in that form.+# rexctl: rexctl config set FLUXER_APP_ATTEST_APP_IDS+# FLUXER_APP_ATTEST_APP_IDS=++# Whether the users service also accepts App Attest keys from development+# builds of the apps in FLUXER_APP_ATTEST_APP_IDS. Use true or false. When+# it's empty, it uses false, so only App Store, TestFlight and other+# production builds are accepted.+# rexctl: rexctl config set FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT+# FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT=+# How people sign in on a new instance. Use username or email. Fluxer uses it# only on the first start with no saved sign-in method. When it's empty,# Fluxer uses email if email delivery is set up and username otherwise. Whendiff --git a/fluxer_rexctl/internal/stack/files/docker-compose.yml b/fluxer_rexctl/internal/stack/files/docker-compose.ymlindex c0390215f..87872dca8 100644--- a/fluxer_rexctl/internal/stack/files/docker-compose.yml+++ b/fluxer_rexctl/internal/stack/files/docker-compose.yml@@ -203,6 +203,9 @@ x-fluxer-env: &fluxer-envFLUXER_PUSH_APNS_PRIVATE_KEY_PATH: ${FLUXER_PUSH_APNS_PRIVATE_KEY_PATH:-}FLUXER_PUSH_APNS_APPS: ${FLUXER_PUSH_APNS_APPS:-}+ FLUXER_APP_ATTEST_APP_IDS: ${FLUXER_APP_ATTEST_APP_IDS:-}+ FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT: ${FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT:-}+FLUXER_SUDO_MODE_SECRET: ${FLUXER_SUDO_MODE_SECRET:-}FLUXER_CONNECTION_INITIATION_SECRET: ${FLUXER_CONNECTION_INITIATION_SECRET:-}FLUXER_PROFILE_PSEUDONYM_SECRET: ${FLUXER_PROFILE_PSEUDONYM_SECRET:-}diff --git a/fluxer_svc/src/postgres.rs b/fluxer_svc/src/postgres.rsindex f0bde1fe4..1f2d18637 100644--- a/fluxer_svc/src/postgres.rs+++ b/fluxer_svc/src/postgres.rs@@ -496,6 +496,7 @@ pub struct KvClient {get_partition_rows_sql: String,get_ordered_rows_sql: String,delete_row_sql: String,+ table: String,sort_ids: Arc<SortIdState>,}@@ -518,6 +519,7 @@ impl KvClient {"SELECT row_key, row_data FROM {table} WHERE table_name = $1 AND partition_key = $2 AND (expires_at IS NULL OR expires_at > now())"),delete_row_sql: format!("DELETE FROM {table} WHERE table_name = $1 AND row_key = $2"),+ table,sort_ids: Arc::new(SortIdState {ready: AtomicBool::new(false),started: Instant::now(),@@ -801,6 +803,80 @@ impl KvClient {Ok(())}+ pub async fn insert_row_if_absent(+ &self,+ table_name: &str,+ partition_key: &str,+ row_key: &str,+ row_data: &Value,+ expires_at_ms: Option<i64>,+ ) -> anyhow::Result<bool> {+ let table = &self.table;+ let sql = format!(+ "INSERT INTO {table} AS kv (table_name, partition_key, row_key, row_data, expires_at) VALUES ($1, $2, $3, $4, to_timestamp($5::bigint / 1000.0)) ON CONFLICT (table_name, row_key) DO UPDATE SET partition_key = EXCLUDED.partition_key, row_data = EXCLUDED.row_data, expires_at = EXCLUDED.expires_at, updated_at = now() WHERE kv.expires_at IS NOT NULL AND kv.expires_at <= now()"+ );+ let client = self.pool.get().await?;+ let inserted = self+ .execute(+ &client,+ &sql,+ &[+ (&table_name, Type::TEXT),+ (&partition_key, Type::TEXT),+ (&row_key, Type::TEXT),+ (row_data, Type::JSONB),+ (&expires_at_ms, Type::INT8),+ ],+ )+ .await?;+ Ok(inserted == 1)+ }++ pub async fn take_row(&self, table_name: &str, row_key: &str) -> anyhow::Result<Option<Value>> {+ let table = &self.table;+ let sql = format!(+ "DELETE FROM {table} WHERE table_name = $1 AND row_key = $2 AND (expires_at IS NULL OR expires_at > now()) RETURNING row_data"+ );+ let client = self.pool.get().await?;+ let row = self+ .query_row(+ &client,+ &sql,+ &[(&table_name, Type::TEXT), (&row_key, Type::TEXT)],+ )+ .await?;+ Ok(row.map(|row| row.get::<_, Value>("row_data")))+ }++ pub async fn merge_row_if_bigint_below(+ &self,+ table_name: &str,+ row_key: &str,+ field_name: &str,+ below: i64,+ patch: &Value,+ ) -> anyhow::Result<bool> {+ let field_expr = json_field_expr(field_name)?;+ let table = &self.table;+ let sql = format!(+ "UPDATE {table} SET row_data = row_data || $3, updated_at = now() WHERE table_name = $1 AND row_key = $2 AND (expires_at IS NULL OR expires_at > now()) AND {field_expr} < $4"+ );+ let client = self.pool.get().await?;+ let updated = self+ .execute(+ &client,+ &sql,+ &[+ (&table_name, Type::TEXT),+ (&row_key, Type::TEXT),+ (patch, Type::JSONB),+ (&below, Type::INT8),+ ],+ )+ .await?;+ Ok(updated == 1)+ }+pub async fn query(&self,sql: &str,diff --git a/fluxer_users/Cargo.toml b/fluxer_users/Cargo.tomlindex 6ab2703d4..26a8fc96a 100644--- a/fluxer_users/Cargo.toml+++ b/fluxer_users/Cargo.toml@@ -7,18 +7,22 @@ publish = false[dependencies]anyhow = "1.0.104"-chrono = { version = "0.4", default-features = false }+base64 = "0.23.1"+chrono = { version = "0.4", default-features = false, features = ["std"] }+ciborium = "0.2.2"fluxer_common = { path = "../fluxer_common" }fluxer-svc = { path = "../fluxer_svc" }futures = "0.3.34"hmac = "0.13.0"moka = { version = "0.12.16", features = ["future"] }+ring = "0.17.14"scylla = { version = "1.9.0", features = ["chrono-04"], optional = true }serde = { version = "1.0.229", features = ["derive"] }serde_json = "1.0.154"sha2 = "0.11.1"-tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "signal"] }+tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread", "signal", "sync"] }tracing = "0.1.44"+x509-cert = { version = "0.2.5", default-features = false, features = ["std"] }[features]default = []diff --git a/fluxer_users/src/app_attest/Apple_App_Attestation_Root_CA.pem b/fluxer_users/src/app_attest/Apple_App_Attestation_Root_CA.pemnew file mode 100644index 000000000..4cff2277b--- /dev/null+++ b/fluxer_users/src/app_attest/Apple_App_Attestation_Root_CA.pem@@ -0,0 +1,14 @@+-----BEGIN CERTIFICATE-----+MIICITCCAaegAwIBAgIQC/O+DvHN0uD7jG5yH2IXmDAKBggqhkjOPQQDAzBSMSYw+JAYDVQQDDB1BcHBsZSBBcHAgQXR0ZXN0YXRpb24gUm9vdCBDQTETMBEGA1UECgwK+QXBwbGUgSW5jLjETMBEGA1UECAwKQ2FsaWZvcm5pYTAeFw0yMDAzMTgxODMyNTNa+Fw00NTAzMTUwMDAwMDBaMFIxJjAkBgNVBAMMHUFwcGxlIEFwcCBBdHRlc3RhdGlv+biBSb290IENBMRMwEQYDVQQKDApBcHBsZSBJbmMuMRMwEQYDVQQIDApDYWxpZm9y+bmlhMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAERTHhmLW07ATaFQIEVwTtT4dyctdh+NbJhFs/Ii2FdCgAHGbpphY3+d8qjuDngIN3WVhQUBHAoMeQ/cLiP1sOUtgjqK9au+Yen1mMEvRq9Sk3Jm5X8U62H+xTD3FE9TgS41o0IwQDAPBgNVHRMBAf8EBTADAQH/+MB0GA1UdDgQWBBSskRBTM72+aEH/pwyp5frq5eWKoTAOBgNVHQ8BAf8EBAMCAQYw+CgYIKoZIzj0EAwMDaAAwZQIwQgFGnByvsiVbpTKwSga0kP0e8EeDS4+sQmTvb7vn+53O5+FRXgeLhpJ06ysC5PrOyAjEAp5U4xDgEgllF7En3VcE3iexZZtKeYnpqtijV+oyFraWVIyd/dganmrduC1bmTBGwD+-----END CERTIFICATE-----diff --git a/fluxer_users/src/app_attest/mod.rs b/fluxer_users/src/app_attest/mod.rsnew file mode 100644index 000000000..d4ff4f8bd--- /dev/null+++ b/fluxer_users/src/app_attest/mod.rs@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++pub mod service;+pub mod store;+pub mod verifier;++use fluxer_svc::config::optional_env;+use serde::{Deserialize, Serialize};++const APP_IDS_ENV: &str = "FLUXER_APP_ATTEST_APP_IDS";+const ALLOW_DEVELOPMENT_ENV: &str = "FLUXER_APP_ATTEST_ALLOW_DEVELOPMENT";+const TEAM_ID_LEN: usize = 10;++#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct AppAttestConfig {+ pub app_ids: Vec<String>,+ pub allow_development: bool,+}++impl AppAttestConfig {+ pub fn from_env() -> anyhow::Result<Self> {+ Self::parse(+ optional_env(APP_IDS_ENV).as_deref(),+ optional_env(ALLOW_DEVELOPMENT_ENV).as_deref(),+ )+ }++ pub fn parse(app_ids: Option<&str>, allow_development: Option<&str>) -> anyhow::Result<Self> {+ let app_ids = app_ids+ .unwrap_or_default()+ .split(',')+ .map(str::trim)+ .filter(|app_id| !app_id.is_empty())+ .map(|app_id| {+ if is_valid_app_id(app_id) {+ Ok(app_id.to_owned())+ } else {+ Err(anyhow::anyhow!(+ "{APP_IDS_ENV} entry {app_id:?} is not TEAMID.bundle.id"+ ))+ }+ })+ .collect::<anyhow::Result<Vec<_>>>()?;+ let allow_development = match allow_development+ .map(|value| value.trim().to_ascii_lowercase())+ .as_deref()+ {+ None | Some("" | "0" | "false" | "no" | "off") => false,+ Some("1" | "true" | "yes" | "on") => true,+ Some(other) => anyhow::bail!("{ALLOW_DEVELOPMENT_ENV} has an invalid value {other:?}"),+ };+ Ok(Self {+ app_ids,+ allow_development,+ })+ }++ pub fn is_enabled(&self) -> bool {+ !self.app_ids.is_empty()+ }+}++fn is_valid_app_id(app_id: &str) -> bool {+ let Some((team_id, bundle_id)) = app_id.split_once('.') else {+ return false;+ };+ team_id.len() == TEAM_ID_LEN+ && team_id+ .bytes()+ .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())+ && !bundle_id.is_empty()+ && bundle_id+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || byte == b'.' || byte == b'-')+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Environment {+ Development,+ Production,+}++impl Environment {+ pub fn as_str(self) -> &'static str {+ match self {+ Environment::Development => "development",+ Environment::Production => "production",+ }+ }++ pub fn parse(value: &str) -> Option<Self> {+ match value {+ "development" => Some(Environment::Development),+ "production" => Some(Environment::Production),+ _ => None,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ChallengePurpose {+ Attest,+ Assert,+}++impl ChallengePurpose {+ pub fn as_str(self) -> &'static str {+ match self {+ ChallengePurpose::Attest => "attest",+ ChallengePurpose::Assert => "assert",+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum AgeFloor {+ Adult,+ Minor,+ UnderMinimum,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum AppAttestRejection {+ NotConfigured,+ InvalidRequest,+ InvalidChallenge,+ InvalidAttestation,+ KeyInUse,+ UnknownKey,+ InvalidAssertion,+}diff --git a/fluxer_users/src/app_attest/service.rs b/fluxer_users/src/app_attest/service.rsnew file mode 100644index 000000000..80dca3271--- /dev/null+++ b/fluxer_users/src/app_attest/service.rs@@ -0,0 +1,299 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++use super::store::{AppAttestStore, CHALLENGE_TTL_SECONDS, ChallengeRecord, StoredKey, iso_millis};+use super::verifier::{self, KEY_ID_LEN, KeyForAssertion};+use super::{AgeFloor, AppAttestConfig, AppAttestRejection, ChallengePurpose};+use crate::types::UserResponse;+use base64::Engine;+use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig, URL_SAFE_NO_PAD};+use base64::engine::{DecodePaddingMode, general_purpose};+use ring::rand::{SecureRandom, SystemRandom};+use serde::Deserialize;+use std::time::{SystemTime, UNIX_EPOCH};++const MAX_KEYS_PER_USER: usize = 10;+const CHALLENGE_BYTES: usize = 32;+const CHALLENGE_TEXT_LEN: usize = 43;+const MAX_ATTESTATION_BYTES: usize = 16 * 1024;+const MAX_ASSERTION_BYTES: usize = 4 * 1024;+const MAX_CLIENT_DATA_BYTES: usize = 1024;++const STANDARD_ANY_PADDING: GeneralPurpose = GeneralPurpose::new(+ &base64::alphabet::STANDARD,+ GeneralPurposeConfig::new().with_decode_padding_mode(DecodePaddingMode::Indifferent),+);++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct AgeClientData {+ challenge: String,+ age_floor: AgeFloor,+}++pub struct AppAttestService {+ config: AppAttestConfig,+ store: AppAttestStore,+ random: SystemRandom,+}++type Outcome = Result<UserResponse, AppAttestRejection>;++impl AppAttestService {+ pub fn new(config: AppAttestConfig, store: AppAttestStore) -> Self {+ Self {+ config,+ store,+ random: SystemRandom::new(),+ }+ }++ pub async fn create_challenge(+ &self,+ user_id: i64,+ purpose: ChallengePurpose,+ now: SystemTime,+ ) -> anyhow::Result<UserResponse> {+ if !self.config.is_enabled() {+ return Ok(rejected(AppAttestRejection::NotConfigured));+ }+ let mut bytes = [0u8; CHALLENGE_BYTES];+ self.random+ .fill(&mut bytes)+ .map_err(|_| anyhow::anyhow!("system random source failed"))?;+ let challenge = URL_SAFE_NO_PAD.encode(bytes);+ let expires_at_ms = unix_ms(now) + CHALLENGE_TTL_SECONDS * 1000;+ self.store+ .insert_challenge(+ &challenge,+ &ChallengeRecord {+ user_id,+ purpose,+ expires_at_ms,+ },+ )+ .await?;+ Ok(UserResponse::AppAttestChallenge {+ challenge,+ expires_at: iso_millis(expires_at_ms),+ })+ }++ pub async fn register_key(+ &self,+ user_id: i64,+ key_id: &str,+ attestation_base64: &str,+ challenge: &str,+ now: SystemTime,+ ) -> anyhow::Result<UserResponse> {+ flatten(+ self.try_register_key(user_id, key_id, attestation_base64, challenge, now)+ .await,+ )+ }++ async fn try_register_key(+ &self,+ user_id: i64,+ key_id: &str,+ attestation_base64: &str,+ challenge: &str,+ now: SystemTime,+ ) -> anyhow::Result<Outcome> {+ if !self.config.is_enabled() {+ return Ok(Err(AppAttestRejection::NotConfigured));+ }+ let Some(key_id) = decode_key_id(key_id) else {+ return Ok(Err(AppAttestRejection::InvalidRequest));+ };+ let Some(attestation) = decode_limited(attestation_base64, MAX_ATTESTATION_BYTES) else {+ return Ok(Err(AppAttestRejection::InvalidRequest));+ };+ if !self+ .consume_challenge(challenge, user_id, ChallengePurpose::Attest, now)+ .await?+ {+ return Ok(Err(AppAttestRejection::InvalidChallenge));+ }+ let client_data_hash = verifier::sha256(challenge.as_bytes());+ let attested = match verifier::verify_attestation(+ &attestation,+ &key_id,+ &client_data_hash,+ now,+ &self.config,+ ) {+ Ok(attested) => attested,+ Err(error) => {+ tracing::info!(user_id, ?error, "app attest attestation rejected");+ return Ok(Err(AppAttestRejection::InvalidAttestation));+ }+ };+ let key_id = general_purpose::STANDARD.encode(key_id);+ if self.store.claim_key_id(&key_id, user_id).await? != user_id {+ return Ok(Err(AppAttestRejection::KeyInUse));+ }+ let key = StoredKey {+ key_id,+ public_key: attested.public_key.to_vec(),+ environment: attested.environment,+ app_id: attested.app_id,+ counter: 0,+ created_at_ms: unix_ms(now),+ last_used_at_ms: None,+ };+ let environment = key.environment;+ if self.store.insert_key_if_absent(user_id, &key).await? {+ self.enforce_key_cap(user_id).await?;+ }+ tracing::info!(user_id, ?environment, "app attest attestation verified");+ Ok(Ok(UserResponse::AppAttestKeyRegistered))+ }++ async fn enforce_key_cap(&self, user_id: i64) -> anyhow::Result<()> {+ let keys = self.store.list_keys(user_id).await?;+ for evicted in keys_to_evict(&keys, MAX_KEYS_PER_USER) {+ self.store.delete_key(user_id, &evicted).await?;+ }+ Ok(())+ }++ pub async fn submit_age(+ &self,+ user_id: i64,+ key_id: &str,+ assertion_base64: &str,+ client_data_base64: &str,+ now: SystemTime,+ ) -> anyhow::Result<UserResponse> {+ flatten(+ self.try_submit_age(user_id, key_id, assertion_base64, client_data_base64, now)+ .await,+ )+ }++ async fn try_submit_age(+ &self,+ user_id: i64,+ key_id: &str,+ assertion_base64: &str,+ client_data_base64: &str,+ now: SystemTime,+ ) -> anyhow::Result<Outcome> {+ if !self.config.is_enabled() {+ return Ok(Err(AppAttestRejection::NotConfigured));+ }+ let (Some(key_id), Some(assertion), Some(client_data)) = (+ decode_key_id(key_id),+ decode_limited(assertion_base64, MAX_ASSERTION_BYTES),+ decode_limited(client_data_base64, MAX_CLIENT_DATA_BYTES),+ ) else {+ return Ok(Err(AppAttestRejection::InvalidRequest));+ };+ let Ok(parsed) = serde_json::from_slice::<AgeClientData>(&client_data) else {+ return Ok(Err(AppAttestRejection::InvalidRequest));+ };+ if !self+ .consume_challenge(&parsed.challenge, user_id, ChallengePurpose::Assert, now)+ .await?+ {+ return Ok(Err(AppAttestRejection::InvalidChallenge));+ }+ let key_id = general_purpose::STANDARD.encode(key_id);+ let Some(key) = self.store.get_key(user_id, &key_id).await? else {+ return Ok(Err(AppAttestRejection::UnknownKey));+ };+ let previous_counter = u32::try_from(key.counter).unwrap_or(u32::MAX);+ let counter = match verifier::verify_assertion(+ &assertion,+ &client_data,+ KeyForAssertion {+ public_key: &key.public_key,+ app_id: &key.app_id,+ environment: key.environment,+ },+ previous_counter,+ &self.config,+ ) {+ Ok(counter) => counter,+ Err(error) => {+ tracing::info!(user_id, ?error, "app attest assertion rejected");+ return Ok(Err(AppAttestRejection::InvalidAssertion));+ }+ };+ let now_ms = unix_ms(now);+ if !self+ .store+ .advance_counter(user_id, &key_id, i64::from(counter), now_ms)+ .await?+ {+ tracing::info!(user_id, "app attest assertion counter lost a race");+ return Ok(Err(AppAttestRejection::InvalidAssertion));+ }+ tracing::info!(user_id, counter, "app attest assertion verified");+ Ok(Ok(UserResponse::AppAttestAgeAccepted {+ age_floor: parsed.age_floor,+ attested_at: iso_millis(now_ms),+ }))+ }++ async fn consume_challenge(+ &self,+ challenge: &str,+ user_id: i64,+ purpose: ChallengePurpose,+ now: SystemTime,+ ) -> anyhow::Result<bool> {+ if challenge.len() != CHALLENGE_TEXT_LEN || URL_SAFE_NO_PAD.decode(challenge).is_err() {+ return Ok(false);+ }+ self.store+ .consume_challenge(challenge, user_id, purpose, unix_ms(now))+ .await+ }+}++fn keys_to_evict(keys: &[StoredKey], max_keys: usize) -> Vec<String> {+ let mut by_age = keys.iter().collect::<Vec<_>>();+ by_age.sort_by(|left, right| {+ let left_used = left.last_used_at_ms.unwrap_or(left.created_at_ms);+ let right_used = right.last_used_at_ms.unwrap_or(right.created_at_ms);+ left_used+ .cmp(&right_used)+ .then_with(|| left.key_id.cmp(&right.key_id))+ });+ let excess = keys.len().saturating_sub(max_keys);+ by_age+ .into_iter()+ .take(excess)+ .map(|key| key.key_id.clone())+ .collect()+}++fn decode_key_id(key_id: &str) -> Option<[u8; KEY_ID_LEN]> {+ STANDARD_ANY_PADDING.decode(key_id).ok()?.try_into().ok()+}++fn decode_limited(value: &str, max_bytes: usize) -> Option<Vec<u8>> {+ if value.len() > max_bytes.div_ceil(3) * 4 {+ return None;+ }+ STANDARD_ANY_PADDING+ .decode(value)+ .ok()+ .filter(|bytes| !bytes.is_empty())+}++fn flatten(outcome: anyhow::Result<Outcome>) -> anyhow::Result<UserResponse> {+ Ok(outcome?.unwrap_or_else(rejected))+}++fn rejected(code: AppAttestRejection) -> UserResponse {+ UserResponse::AppAttestRejected { code }+}++fn unix_ms(now: SystemTime) -> i64 {+ now.duration_since(UNIX_EPOCH)+ .map(|elapsed| elapsed.as_millis() as i64)+ .unwrap_or_default()+}diff --git a/fluxer_users/src/app_attest/store.rs b/fluxer_users/src/app_attest/store.rsnew file mode 100644index 000000000..656d04575--- /dev/null+++ b/fluxer_users/src/app_attest/store.rs@@ -0,0 +1,579 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++use super::{ChallengePurpose, Environment};+use base64::Engine;+use base64::engine::general_purpose::STANDARD;+use chrono::{DateTime, SecondsFormat, Utc};+use fluxer_svc::postgres::{self, KeyPart, KvClient};+use serde_json::{Value, json};++#[cfg(feature = "scylla")]+use scylla::client::session::Session;+#[cfg(feature = "scylla")]+use scylla::statement::prepared::PreparedStatement;+#[cfg(feature = "scylla")]+use std::sync::Arc;++const CHALLENGES_TABLE: &str = "app_attest_challenges";+const KEYS_TABLE: &str = "app_attest_keys";+const KEY_LOOKUP_TABLE: &str = "app_attest_key_lookup";+pub const CHALLENGE_TTL_SECONDS: i64 = 300;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ChallengeRecord {+ pub user_id: i64,+ pub purpose: ChallengePurpose,+ pub expires_at_ms: i64,+}++impl ChallengeRecord {+ pub fn accepts(&self, user_id: i64, purpose: ChallengePurpose, now_ms: i64) -> bool {+ self.user_id == user_id && self.purpose == purpose && now_ms < self.expires_at_ms+ }+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct StoredKey {+ pub key_id: String,+ pub public_key: Vec<u8>,+ pub environment: Environment,+ pub app_id: String,+ pub counter: i64,+ pub created_at_ms: i64,+ pub last_used_at_ms: Option<i64>,+}++#[derive(Clone)]+pub enum AppAttestStore {+ Postgres(KvClient),+ #[cfg(feature = "scylla")]+ Scylla(Arc<ScyllaAppAttestStore>),+}++impl AppAttestStore {+ pub async fn insert_challenge(+ &self,+ challenge: &str,+ record: &ChallengeRecord,+ ) -> anyhow::Result<()> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let key = postgres::kv_key(&[KeyPart::String(challenge)])?;+ let row = json!({+ "challenge": challenge,+ "user_id": bigint(record.user_id),+ "purpose": record.purpose.as_str(),+ "expires_at": date(record.expires_at_ms),+ });+ if !kv+ .insert_row_if_absent(+ CHALLENGES_TABLE,+ &key,+ &key,+ &row,+ Some(record.expires_at_ms),+ )+ .await?+ {+ anyhow::bail!("app attest challenge collision");+ }+ Ok(())+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => store.insert_challenge(challenge, record).await,+ }+ }++ pub async fn consume_challenge(+ &self,+ challenge: &str,+ user_id: i64,+ purpose: ChallengePurpose,+ now_ms: i64,+ ) -> anyhow::Result<bool> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let key = postgres::kv_key(&[KeyPart::String(challenge)])?;+ let Some(row) = kv.take_row(CHALLENGES_TABLE, &key).await? else {+ return Ok(false);+ };+ Ok(decode_challenge(row)+ .is_some_and(|record| record.accepts(user_id, purpose, now_ms)))+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => {+ store+ .consume_challenge(challenge, user_id, purpose, now_ms)+ .await+ }+ }+ }++ pub async fn claim_key_id(&self, key_id: &str, user_id: i64) -> anyhow::Result<i64> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let key = postgres::kv_key(&[KeyPart::String(key_id)])?;+ let row = json!({"key_id": key_id, "user_id": bigint(user_id)});+ if kv+ .insert_row_if_absent(KEY_LOOKUP_TABLE, &key, &key, &row, None)+ .await?+ {+ return Ok(user_id);+ }+ let row = kv+ .get_row(KEY_LOOKUP_TABLE, &key)+ .await?+ .ok_or_else(|| anyhow::anyhow!("app attest key lookup vanished"))?;+ let row = postgres::decode_row_dates_as_millis(row)?;+ row.get("user_id")+ .and_then(Value::as_i64)+ .ok_or_else(|| anyhow::anyhow!("app attest key lookup has no user"))+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => store.claim_key_id(key_id, user_id).await,+ }+ }++ pub async fn insert_key_if_absent(+ &self,+ user_id: i64,+ key: &StoredKey,+ ) -> anyhow::Result<bool> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let (partition, row_key) = key_row_keys(user_id, &key.key_id)?;+ let row = json!({+ "user_id": bigint(user_id),+ "key_id": key.key_id,+ "public_key": {"__fluxer_type": "buffer", "value": STANDARD.encode(&key.public_key)},+ "environment": key.environment.as_str(),+ "app_id": key.app_id,+ "counter": bigint(key.counter),+ "created_at": date(key.created_at_ms),+ "last_used_at": key.last_used_at_ms.map(date),+ });+ kv.insert_row_if_absent(KEYS_TABLE, &partition, &row_key, &row, None)+ .await+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => store.insert_key_if_absent(user_id, key).await,+ }+ }++ pub async fn get_key(&self, user_id: i64, key_id: &str) -> anyhow::Result<Option<StoredKey>> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let (_, row_key) = key_row_keys(user_id, key_id)?;+ kv.get_row(KEYS_TABLE, &row_key)+ .await?+ .map(decode_key)+ .transpose()+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => store.get_key(user_id, key_id).await,+ }+ }++ pub async fn list_keys(&self, user_id: i64) -> anyhow::Result<Vec<StoredKey>> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let partition = postgres::kv_key(&[KeyPart::BigInt(user_id)])?;+ kv.get_partition_rows(KEYS_TABLE, &partition)+ .await?+ .into_iter()+ .map(|(_, row)| decode_key(row))+ .collect()+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => store.list_keys(user_id).await,+ }+ }++ pub async fn delete_key(&self, user_id: i64, key_id: &str) -> anyhow::Result<()> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let (_, row_key) = key_row_keys(user_id, key_id)?;+ kv.delete_row(KEYS_TABLE, &row_key).await?;+ let lookup = postgres::kv_key(&[KeyPart::String(key_id)])?;+ kv.delete_row(KEY_LOOKUP_TABLE, &lookup).await+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => store.delete_key(user_id, key_id).await,+ }+ }++ pub async fn advance_counter(+ &self,+ user_id: i64,+ key_id: &str,+ counter: i64,+ now_ms: i64,+ ) -> anyhow::Result<bool> {+ match self {+ AppAttestStore::Postgres(kv) => {+ let (_, row_key) = key_row_keys(user_id, key_id)?;+ let patch = json!({"counter": bigint(counter), "last_used_at": date(now_ms)});+ kv.merge_row_if_bigint_below(KEYS_TABLE, &row_key, "counter", counter, &patch)+ .await+ }+ #[cfg(feature = "scylla")]+ AppAttestStore::Scylla(store) => {+ store+ .advance_counter(user_id, key_id, counter, now_ms)+ .await+ }+ }+ }+}++fn key_row_keys(user_id: i64, key_id: &str) -> anyhow::Result<(String, String)> {+ Ok((+ postgres::kv_key(&[KeyPart::BigInt(user_id)])?,+ postgres::kv_key(&[KeyPart::BigInt(user_id), KeyPart::String(key_id)])?,+ ))+}++fn bigint(value: i64) -> Value {+ json!({"__fluxer_type": "bigint", "value": value.to_string()})+}++fn date(ms: i64) -> Value {+ json!({"__fluxer_type": "date", "value": iso_millis(ms)})+}++pub fn iso_millis(ms: i64) -> String {+ DateTime::<Utc>::from_timestamp_millis(ms)+ .unwrap_or_default()+ .to_rfc3339_opts(SecondsFormat::Millis, true)+}++fn decode_challenge(row: Value) -> Option<ChallengeRecord> {+ let row = postgres::decode_row_dates_as_millis(row).ok()?;+ let purpose = match row.get("purpose")?.as_str()? {+ "attest" => ChallengePurpose::Attest,+ "assert" => ChallengePurpose::Assert,+ _ => return None,+ };+ Some(ChallengeRecord {+ user_id: row.get("user_id")?.as_i64()?,+ purpose,+ expires_at_ms: row.get("expires_at")?.as_i64()?,+ })+}++fn decode_key(row: Value) -> anyhow::Result<StoredKey> {+ let row = postgres::decode_row_dates_as_millis(row)?;+ let field = |name: &str| {+ row.get(name)+ .ok_or_else(|| anyhow::anyhow!("app attest key row has no {name}"))+ };+ let text = |name: &str| {+ field(name)?+ .as_str()+ .map(ToOwned::to_owned)+ .ok_or_else(|| anyhow::anyhow!("app attest key row {name} is not text"))+ };+ let number = |name: &str| {+ field(name)?+ .as_i64()+ .ok_or_else(|| anyhow::anyhow!("app attest key row {name} is not a number"))+ };+ Ok(StoredKey {+ key_id: text("key_id")?,+ public_key: STANDARD.decode(text("public_key")?)?,+ environment: Environment::parse(&text("environment")?)+ .ok_or_else(|| anyhow::anyhow!("app attest key row has an unknown environment"))?,+ app_id: text("app_id")?,+ counter: number("counter")?,+ created_at_ms: number("created_at")?,+ last_used_at_ms: row.get("last_used_at").and_then(Value::as_i64),+ })+}++#[cfg(feature = "scylla")]+pub struct ScyllaAppAttestStore {+ db: Arc<Session>,+ statements: tokio::sync::OnceCell<ScyllaStatements>,+}++#[cfg(feature = "scylla")]+struct ScyllaStatements {+ insert_challenge: PreparedStatement,+ consume_challenge: PreparedStatement,+ claim_key_id: PreparedStatement,+ insert_key: PreparedStatement,+ select_key: PreparedStatement,+ select_keys: PreparedStatement,+ delete_key: PreparedStatement,+ delete_lookup: PreparedStatement,+ advance_counter: PreparedStatement,+}++#[cfg(feature = "scylla")]+const SCYLLA_KEY_COLUMNS: &str =+ "key_id, public_key, environment, app_id, counter, created_at, last_used_at";++#[cfg(feature = "scylla")]+#[derive(scylla::DeserializeRow)]+struct ScyllaKeyRow {+ key_id: String,+ public_key: Vec<u8>,+ environment: String,+ app_id: String,+ counter: i64,+ created_at: DateTime<Utc>,+ last_used_at: Option<DateTime<Utc>>,+}++#[cfg(feature = "scylla")]+impl TryFrom<ScyllaKeyRow> for StoredKey {+ type Error = anyhow::Error;++ fn try_from(row: ScyllaKeyRow) -> anyhow::Result<Self> {+ Ok(StoredKey {+ key_id: row.key_id,+ public_key: row.public_key,+ environment: Environment::parse(&row.environment)+ .ok_or_else(|| anyhow::anyhow!("app attest key row has an unknown environment"))?,+ app_id: row.app_id,+ counter: row.counter,+ created_at_ms: row.created_at.timestamp_millis(),+ last_used_at_ms: row.last_used_at.map(|at| at.timestamp_millis()),+ })+ }+}++#[cfg(feature = "scylla")]+fn timestamp(ms: i64) -> DateTime<Utc> {+ DateTime::<Utc>::from_timestamp_millis(ms).unwrap_or_default()+}++#[cfg(feature = "scylla")]+struct LwtOutcome {+ applied: bool,+ user_id: Option<i64>,+}++#[cfg(feature = "scylla")]+fn lwt_outcome(result: scylla::response::query_result::QueryResult) -> anyhow::Result<LwtOutcome> {+ use scylla::value::{CqlValue, Row};+ let rows = result.into_rows_result()?;+ let names = rows+ .column_specs()+ .iter()+ .map(|spec| spec.name().to_owned())+ .collect::<Vec<_>>();+ let row = rows+ .maybe_first_row::<Row>()?+ .ok_or_else(|| anyhow::anyhow!("lightweight transaction returned no row"))?;+ let column = |name: &str| {+ names+ .iter()+ .position(|candidate| candidate == name)+ .and_then(|index| row.columns.get(index).cloned().flatten())+ };+ let applied = matches!(column("[applied]"), Some(CqlValue::Boolean(true)));+ let user_id = match column("user_id") {+ Some(CqlValue::BigInt(user_id)) => Some(user_id),+ _ => None,+ };+ Ok(LwtOutcome { applied, user_id })+}++#[cfg(feature = "scylla")]+impl ScyllaAppAttestStore {+ pub fn new(db: Arc<Session>) -> Self {+ Self {+ db,+ statements: tokio::sync::OnceCell::new(),+ }+ }++ async fn statements(&self) -> anyhow::Result<&ScyllaStatements> {+ self.statements+ .get_or_try_init(|| async {+ let db = &self.db;+ Ok::<_, anyhow::Error>(ScyllaStatements {+ insert_challenge: db+ .prepare(format!(+ "INSERT INTO {CHALLENGES_TABLE} (challenge, user_id, purpose, expires_at) VALUES (?, ?, ?, ?) IF NOT EXISTS USING TTL {CHALLENGE_TTL_SECONDS}"+ ))+ .await?,+ consume_challenge: db+ .prepare(format!(+ "DELETE FROM {CHALLENGES_TABLE} WHERE challenge = ? IF user_id = ? AND purpose = ? AND expires_at > ?"+ ))+ .await?,+ claim_key_id: db+ .prepare(format!(+ "INSERT INTO {KEY_LOOKUP_TABLE} (key_id, user_id) VALUES (?, ?) IF NOT EXISTS"+ ))+ .await?,+ insert_key: db+ .prepare(format!(+ "INSERT INTO {KEYS_TABLE} (user_id, {SCYLLA_KEY_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?, ?) IF NOT EXISTS"+ ))+ .await?,+ select_key: db+ .prepare(format!(+ "SELECT {SCYLLA_KEY_COLUMNS} FROM {KEYS_TABLE} WHERE user_id = ? AND key_id = ?"+ ))+ .await?,+ select_keys: db+ .prepare(format!(+ "SELECT {SCYLLA_KEY_COLUMNS} FROM {KEYS_TABLE} WHERE user_id = ?"+ ))+ .await?,+ delete_key: db+ .prepare(format!(+ "DELETE FROM {KEYS_TABLE} WHERE user_id = ? AND key_id = ? IF EXISTS"+ ))+ .await?,+ delete_lookup: db+ .prepare(format!(+ "DELETE FROM {KEY_LOOKUP_TABLE} WHERE key_id = ? IF user_id = ?"+ ))+ .await?,+ advance_counter: db+ .prepare(format!(+ "UPDATE {KEYS_TABLE} SET counter = ?, last_used_at = ? WHERE user_id = ? AND key_id = ? IF counter < ?"+ ))+ .await?,+ })+ })+ .await+ }++ async fn insert_challenge(+ &self,+ challenge: &str,+ record: &ChallengeRecord,+ ) -> anyhow::Result<()> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(+ &statements.insert_challenge,+ (+ challenge,+ record.user_id,+ record.purpose.as_str(),+ timestamp(record.expires_at_ms),+ ),+ )+ .await?;+ if !lwt_outcome(result)?.applied {+ anyhow::bail!("app attest challenge collision");+ }+ Ok(())+ }++ async fn consume_challenge(+ &self,+ challenge: &str,+ user_id: i64,+ purpose: ChallengePurpose,+ now_ms: i64,+ ) -> anyhow::Result<bool> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(+ &statements.consume_challenge,+ (challenge, user_id, purpose.as_str(), timestamp(now_ms)),+ )+ .await?;+ Ok(lwt_outcome(result)?.applied)+ }++ async fn claim_key_id(&self, key_id: &str, user_id: i64) -> anyhow::Result<i64> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(&statements.claim_key_id, (key_id, user_id))+ .await?;+ let outcome = lwt_outcome(result)?;+ if outcome.applied {+ return Ok(user_id);+ }+ outcome+ .user_id+ .ok_or_else(|| anyhow::anyhow!("app attest key lookup has no user"))+ }++ async fn insert_key_if_absent(&self, user_id: i64, key: &StoredKey) -> anyhow::Result<bool> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(+ &statements.insert_key,+ (+ user_id,+ key.key_id.as_str(),+ key.public_key.as_slice(),+ key.environment.as_str(),+ key.app_id.as_str(),+ key.counter,+ timestamp(key.created_at_ms),+ key.last_used_at_ms.map(timestamp),+ ),+ )+ .await?;+ Ok(lwt_outcome(result)?.applied)+ }++ async fn get_key(&self, user_id: i64, key_id: &str) -> anyhow::Result<Option<StoredKey>> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(&statements.select_key, (user_id, key_id))+ .await?;+ result+ .into_rows_result()?+ .maybe_first_row::<ScyllaKeyRow>()?+ .map(StoredKey::try_from)+ .transpose()+ }++ async fn list_keys(&self, user_id: i64) -> anyhow::Result<Vec<StoredKey>> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(&statements.select_keys, (user_id,))+ .await?;+ result+ .into_rows_result()?+ .rows::<ScyllaKeyRow>()?+ .map(|row| StoredKey::try_from(row?))+ .collect()+ }++ async fn delete_key(&self, user_id: i64, key_id: &str) -> anyhow::Result<()> {+ let statements = self.statements().await?;+ self.db+ .execute_unpaged(&statements.delete_key, (user_id, key_id))+ .await?;+ self.db+ .execute_unpaged(&statements.delete_lookup, (key_id, user_id))+ .await?;+ Ok(())+ }++ async fn advance_counter(+ &self,+ user_id: i64,+ key_id: &str,+ counter: i64,+ now_ms: i64,+ ) -> anyhow::Result<bool> {+ let statements = self.statements().await?;+ let result = self+ .db+ .execute_unpaged(+ &statements.advance_counter,+ (counter, timestamp(now_ms), user_id, key_id, counter),+ )+ .await?;+ Ok(lwt_outcome(result)?.applied)+ }+}diff --git a/fluxer_users/src/app_attest/testdata/node-app-attest-production-attestation.cbor b/fluxer_users/src/app_attest/testdata/node-app-attest-production-attestation.cbornew file mode 100644index 000000000..32c9d9c4eBinary files /dev/null and b/fluxer_users/src/app_attest/testdata/node-app-attest-production-attestation.cbor differdiff --git a/fluxer_users/src/app_attest/testdata/synthetic-untrusted-root-attestation.cbor b/fluxer_users/src/app_attest/testdata/synthetic-untrusted-root-attestation.cbornew file mode 100644index 000000000..faab6e6daBinary files /dev/null and b/fluxer_users/src/app_attest/testdata/synthetic-untrusted-root-attestation.cbor differdiff --git a/fluxer_users/src/app_attest/testdata/vectors.json b/fluxer_users/src/app_attest/testdata/vectors.jsonnew file mode 100644index 000000000..3e33cd4e2--- /dev/null+++ b/fluxer_users/src/app_attest/testdata/vectors.json@@ -0,0 +1,72 @@+[+ {+ "id": "veehaitch-ios-14.4-attestation",+ "kind": "attestation",+ "ios_version": "14.4",+ "source_repo": "https://github.com/veehaitch/devicecheck-appattest",+ "source_commit": "cb26211f63c1e2e7949deafe2efdf352daca27fa",+ "source_license": "Apache-2.0",+ "source_path": "src/test/resources/ios-14.4.yaml",+ "source_sample_id": "e0d7ae88-ccb4-a905-27cd-d869d458f869",+ "environment": "development",+ "team_id": "6MURL8TA57",+ "bundle_id": "de.vincent-haupert.apple-appattest-poc",+ "app_id": "6MURL8TA57.de.vincent-haupert.apple-appattest-poc",+ "key_id_b64": "YmbJO4x5nEHUvncp9zdWuVZjNBEMgJn3cdSToAXQe3M=",+ "client_data_b64": "d3VyemVscGZyb3Bm",+ "client_data_hash_b64": "i+ZcylFa0JfJU5Z9GNY12G3XihQu09B3UmvtEca+xns=",+ "now": "2021-01-23T12:13:33.335Z",+ "expected": "accept",+ "attestation_object_file": "veehaitch-ios-14.4-attestation.cbor",+ "public_key_x962_hex": "0488c034a190aa7dbc5a061501c6542803942582198b3f1cc54673ca3b9ad20b41528267a54f5fdba0469fafb46bb6990a396bf04f94a49d4320c81c7ab240a398",+ "leaf_not_before": "2021-01-22T12:13:35+00:00",+ "leaf_not_after": "2021-01-25T12:13:35+00:00",+ "intermediate_not_before": "2020-03-18T18:39:55+00:00",+ "intermediate_not_after": "2030-03-13T00:00:00+00:00"+ },+ {+ "id": "veehaitch-ios-14.4-assertion",+ "kind": "assertion",+ "source_repo": "https://github.com/veehaitch/devicecheck-appattest",+ "source_commit": "cb26211f63c1e2e7949deafe2efdf352daca27fa",+ "source_license": "Apache-2.0",+ "source_path": "src/test/resources/ios-14.4.yaml",+ "source_sample_id": "c5051b6a-7f30-8d79-012a-f46d5de83193",+ "environment": "development",+ "team_id": "6MURL8TA57",+ "bundle_id": "de.vincent-haupert.apple-appattest-poc",+ "app_id": "6MURL8TA57.de.vincent-haupert.apple-appattest-poc",+ "key_id_b64": "YmbJO4x5nEHUvncp9zdWuVZjNBEMgJn3cdSToAXQe3M=",+ "client_data_b64": "d3VyemVscGZyb3Bm",+ "client_data_hash_b64": "i+ZcylFa0JfJU5Z9GNY12G3XihQu09B3UmvtEca+xns=",+ "now": "2021-01-23T12:13:36.016Z",+ "expected": "accept",+ "assertion_file": "veehaitch-ios-14.4-assertion.cbor",+ "challenge_b64": "d3VyemVs",+ "public_key_x962_hex": "0488c034a190aa7dbc5a061501c6542803942582198b3f1cc54673ca3b9ad20b41528267a54f5fdba0469fafb46bb6990a396bf04f94a49d4320c81c7ab240a398",+ "expected_counter": 1,+ "previous_counter": 0+ },+ {+ "id": "node-app-attest-production-attestation",+ "kind": "attestation",+ "source_repo": "https://github.com/uebelack/node-app-attest",+ "source_commit": "f16c4bb71b737466872bc8b8a7dfd215364eaa83",+ "source_license": "MIT",+ "source_path": "test/fixtures/attestation-production.json",+ "environment": "production",+ "team_id": "V8H6LQ9448",+ "bundle_id": "io.uebelacker.AppAttestExample",+ "app_id": "V8H6LQ9448.io.uebelacker.AppAttestExample",+ "key_id_b64": "SC86LZmoFbL/KxWfezr7ihgEdLHK8ZrDbTwMtAkBCbM=",+ "client_data_b64": "ZGU1ZTAzNTktODRmNy00ZGQ3LWE5OGQtNTM2M2U5NDE1ZmIx",+ "attestation_object_file": "node-app-attest-production-attestation.cbor",+ "expected": "accept",+ "leaf_not_before": "2024-02-06T21:08:56+00:00",+ "leaf_not_after": "2024-12-21T12:42:56+00:00",+ "intermediate_not_before": "2020-03-18T18:39:55+00:00",+ "intermediate_not_after": "2030-03-13T00:00:00+00:00",+ "now": "2024-02-07T21:08:56Z",+ "now_note": "source gives no clock, chosen as leaf notBefore plus one day"+ }+]diff --git a/fluxer_users/src/app_attest/testdata/veehaitch-ios-14.4-assertion.cbor b/fluxer_users/src/app_attest/testdata/veehaitch-ios-14.4-assertion.cbornew file mode 100644index 000000000..ea6bf927eBinary files /dev/null and b/fluxer_users/src/app_attest/testdata/veehaitch-ios-14.4-assertion.cbor differdiff --git a/fluxer_users/src/app_attest/testdata/veehaitch-ios-14.4-attestation.cbor b/fluxer_users/src/app_attest/testdata/veehaitch-ios-14.4-attestation.cbornew file mode 100644index 000000000..5c5d54d71Binary files /dev/null and b/fluxer_users/src/app_attest/testdata/veehaitch-ios-14.4-attestation.cbor differdiff --git a/fluxer_users/src/app_attest/verifier.rs b/fluxer_users/src/app_attest/verifier.rsnew file mode 100644index 000000000..f5c103c39--- /dev/null+++ b/fluxer_users/src/app_attest/verifier.rs@@ -0,0 +1,879 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++use super::{AppAttestConfig, Environment};+use base64::Engine;+use base64::engine::general_purpose::STANDARD;+use ciborium::Value;+use ring::signature::{self, UnparsedPublicKey, VerificationAlgorithm};+use sha2::{Digest, Sha256};+use std::sync::LazyLock;+use std::time::SystemTime;+use x509_cert::Certificate;+use x509_cert::der::asn1::ObjectIdentifier;+use x509_cert::der::{Decode, Encode};+use x509_cert::ext::pkix::BasicConstraints;++pub const KEY_ID_LEN: usize = 32;+pub const PUBLIC_KEY_LEN: usize = 65;++const ROOT_CA_PEM: &str = include_str!("Apple_App_Attestation_Root_CA.pem");+const FORMAT: &str = "apple-appattest";+const MAX_CHAIN_LEN: usize = 4;+const MAX_MAP_ENTRIES: usize = 16;+const RP_ID_HASH_END: usize = 32;+const FLAGS_INDEX: usize = 32;+const COUNTER_END: usize = 37;+const AAGUID_END: usize = 53;+const CREDENTIAL_ID_LEN_END: usize = 55;+const FLAG_ATTESTED_CREDENTIAL_DATA: u8 = 0x40;+const AAGUID_DEVELOPMENT: &[u8; 16] = b"appattestdevelop";+const AAGUID_PRODUCTION: &[u8; 16] = b"appattest\0\0\0\0\0\0\0";+const NONCE_EXTENSION_PREFIX: [u8; 6] = [0x30, 0x24, 0xa1, 0x22, 0x04, 0x20];++const OID_NONCE: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113635.100.8.2");+const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");+const OID_P256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");+const OID_P384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");+const OID_ECDSA_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");+const OID_ECDSA_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3");+const OID_BASIC_CONSTRAINTS: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.19");+const OID_KEY_USAGE: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.29.15");++static ROOT_CA: LazyLock<Certificate> = LazyLock::new(|| {+ let body = ROOT_CA_PEM+ .lines()+ .filter(|line| !line.starts_with("-----"))+ .collect::<String>();+ let der = STANDARD+ .decode(body)+ .expect("the embedded App Attest root is base64");+ Certificate::from_der(&der).expect("the embedded App Attest root is a certificate")+});++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AttestationError {+ Malformed,+ UnsupportedFormat,+ Certificate,+ UntrustedChain,+ CertificateTime,+ Nonce,+ KeyId,+ AppId,+ Flags,+ Counter,+ Environment,+ DevelopmentNotAllowed,+ CredentialId,+ CoseKey,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AssertionError {+ Malformed,+ KeyNotAccepted,+ Signature,+ AppId,+ Counter,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AttestedKey {+ pub public_key: [u8; PUBLIC_KEY_LEN],+ pub environment: Environment,+ pub app_id: String,+}++#[derive(Clone, Copy, Debug)]+pub struct KeyForAssertion<'a> {+ pub public_key: &'a [u8],+ pub app_id: &'a str,+ pub environment: Environment,+}++pub fn verify_attestation(+ attestation: &[u8],+ key_id: &[u8],+ client_data_hash: &[u8],+ now: SystemTime,+ config: &AppAttestConfig,+) -> Result<AttestedKey, AttestationError> {+ if key_id.len() != KEY_ID_LEN {+ return Err(AttestationError::KeyId);+ }+ let object = decode_single(attestation).ok_or(AttestationError::Malformed)?;+ let object = as_map(&object).ok_or(AttestationError::Malformed)?;+ let format = map_text(object, "fmt").ok_or(AttestationError::Malformed)?;+ if format != FORMAT {+ return Err(AttestationError::UnsupportedFormat);+ }+ let statement = map_get(object, "attStmt")+ .and_then(as_map)+ .ok_or(AttestationError::Malformed)?;+ let auth_data = map_bytes(object, "authData").ok_or(AttestationError::Malformed)?;+ map_bytes(statement, "receipt").ok_or(AttestationError::Malformed)?;+ let chain = map_get(statement, "x5c")+ .and_then(Value::as_array)+ .ok_or(AttestationError::Malformed)?+ .iter()+ .map(|cert| cert.as_bytes().map(Vec::as_slice))+ .collect::<Option<Vec<_>>>()+ .ok_or(AttestationError::Malformed)?;++ let leaf = verify_chain(&chain, now)?;+ let nonce = sha256_concat(auth_data, client_data_hash);+ if !constant_time_eq(&leaf_nonce(&leaf)?, &nonce) {+ return Err(AttestationError::Nonce);+ }+ let public_key = leaf_public_key(&leaf)?;+ if !constant_time_eq(&sha256(&public_key), key_id) {+ return Err(AttestationError::KeyId);+ }+ let (environment, app_id, cose_key) = check_attested_auth_data(auth_data, key_id, config)?;+ if cose_key != public_key {+ return Err(AttestationError::CoseKey);+ }+ Ok(AttestedKey {+ public_key,+ environment,+ app_id,+ })+}++pub fn check_attested_auth_data(+ auth_data: &[u8],+ key_id: &[u8],+ config: &AppAttestConfig,+) -> Result<(Environment, String, [u8; PUBLIC_KEY_LEN]), AttestationError> {+ if auth_data.len() < CREDENTIAL_ID_LEN_END + KEY_ID_LEN {+ return Err(AttestationError::Malformed);+ }+ let app_id = configured_app_id(&auth_data[..RP_ID_HASH_END], config)+ .ok_or(AttestationError::AppId)?+ .to_owned();+ if auth_data[FLAGS_INDEX] & FLAG_ATTESTED_CREDENTIAL_DATA == 0 {+ return Err(AttestationError::Flags);+ }+ if read_counter(auth_data) != 0 {+ return Err(AttestationError::Counter);+ }+ let environment = match &auth_data[COUNTER_END..AAGUID_END] {+ aaguid if aaguid == AAGUID_PRODUCTION => Environment::Production,+ aaguid if aaguid == AAGUID_DEVELOPMENT => Environment::Development,+ _ => return Err(AttestationError::Environment),+ };+ if environment == Environment::Development && !config.allow_development {+ return Err(AttestationError::DevelopmentNotAllowed);+ }+ let credential_id_len =+ u16::from_be_bytes([auth_data[AAGUID_END], auth_data[AAGUID_END + 1]]) as usize;+ let credential_id_end = CREDENTIAL_ID_LEN_END + KEY_ID_LEN;+ if credential_id_len != KEY_ID_LEN+ || !constant_time_eq(&auth_data[CREDENTIAL_ID_LEN_END..credential_id_end], key_id)+ {+ return Err(AttestationError::CredentialId);+ }+ let mut rest = &auth_data[credential_id_end..];+ let cose_key = decode_next(&mut rest).ok_or(AttestationError::CoseKey)?;+ let cose_key = cose_public_key(&cose_key).ok_or(AttestationError::CoseKey)?;+ if !rest.is_empty() {+ let extensions = decode_single(rest).ok_or(AttestationError::Malformed)?;+ as_map(&extensions).ok_or(AttestationError::Malformed)?;+ }+ Ok((environment, app_id, cose_key))+}++pub fn verify_assertion(+ assertion: &[u8],+ client_data: &[u8],+ key: KeyForAssertion<'_>,+ previous_counter: u32,+ config: &AppAttestConfig,+) -> Result<u32, AssertionError> {+ if !config.app_ids.iter().any(|app_id| app_id == key.app_id)+ || (key.environment == Environment::Development && !config.allow_development)+ {+ return Err(AssertionError::KeyNotAccepted);+ }+ let object = decode_single(assertion).ok_or(AssertionError::Malformed)?;+ let object = as_map(&object).ok_or(AssertionError::Malformed)?;+ let signature_der = map_bytes(object, "signature").ok_or(AssertionError::Malformed)?;+ let auth_data = map_bytes(object, "authenticatorData").ok_or(AssertionError::Malformed)?;+ if auth_data.len() < COUNTER_END {+ return Err(AssertionError::Malformed);+ }+ if auth_data.len() > COUNTER_END {+ let extensions =+ decode_single(&auth_data[COUNTER_END..]).ok_or(AssertionError::Malformed)?;+ as_map(&extensions).ok_or(AssertionError::Malformed)?;+ }+ let nonce = sha256_concat(auth_data, &sha256(client_data));+ UnparsedPublicKey::new(&signature::ECDSA_P256_SHA256_ASN1, key.public_key)+ .verify(&nonce, signature_der)+ .map_err(|_| AssertionError::Signature)?;+ if !constant_time_eq(&auth_data[..RP_ID_HASH_END], &sha256(key.app_id.as_bytes())) {+ return Err(AssertionError::AppId);+ }+ let counter = read_counter(auth_data);+ if counter <= previous_counter {+ return Err(AssertionError::Counter);+ }+ Ok(counter)+}++fn verify_chain(chain: &[&[u8]], now: SystemTime) -> Result<Certificate, AttestationError> {+ if chain.len() < 2 || chain.len() > MAX_CHAIN_LEN {+ return Err(AttestationError::UntrustedChain);+ }+ let certs = chain+ .iter()+ .map(|der| Certificate::from_der(der).map_err(|_| AttestationError::Certificate))+ .collect::<Result<Vec<_>, _>>()?;+ check_validity(&ROOT_CA, now)?;+ for (index, cert) in certs.iter().enumerate() {+ let issuer = certs.get(index + 1).unwrap_or(&ROOT_CA);+ check_validity(cert, now)?;+ check_critical_extensions(cert)?;+ if !is_ca(issuer)? {+ return Err(AttestationError::UntrustedChain);+ }+ check_issued_by(cert, issuer)?;+ }+ let leaf = certs+ .into_iter()+ .next()+ .ok_or(AttestationError::Malformed)?;+ if is_ca(&leaf)? {+ return Err(AttestationError::UntrustedChain);+ }+ Ok(leaf)+}++fn check_validity(cert: &Certificate, now: SystemTime) -> Result<(), AttestationError> {+ let now = now+ .duration_since(SystemTime::UNIX_EPOCH)+ .map_err(|_| AttestationError::CertificateTime)?;+ let validity = &cert.tbs_certificate.validity;+ if now < validity.not_before.to_unix_duration() || now > validity.not_after.to_unix_duration() {+ return Err(AttestationError::CertificateTime);+ }+ Ok(())+}++fn check_critical_extensions(cert: &Certificate) -> Result<(), AttestationError> {+ let known = |oid: &ObjectIdentifier| *oid == OID_BASIC_CONSTRAINTS || *oid == OID_KEY_USAGE;+ let unknown_critical = cert+ .tbs_certificate+ .extensions+ .iter()+ .flatten()+ .any(|extension| extension.critical && !known(&extension.extn_id));+ if unknown_critical {+ return Err(AttestationError::Certificate);+ }+ Ok(())+}++fn is_ca(cert: &Certificate) -> Result<bool, AttestationError> {+ let mut found = cert+ .tbs_certificate+ .extensions+ .iter()+ .flatten()+ .filter(|extension| extension.extn_id == OID_BASIC_CONSTRAINTS);+ let Some(extension) = found.next() else {+ return Ok(false);+ };+ if found.next().is_some() {+ return Err(AttestationError::Certificate);+ }+ BasicConstraints::from_der(extension.extn_value.as_bytes())+ .map(|constraints| constraints.ca)+ .map_err(|_| AttestationError::Certificate)+}++fn check_issued_by(cert: &Certificate, issuer: &Certificate) -> Result<(), AttestationError> {+ let issuer_name = cert+ .tbs_certificate+ .issuer+ .to_der()+ .map_err(|_| AttestationError::Certificate)?;+ let subject_name = issuer+ .tbs_certificate+ .subject+ .to_der()+ .map_err(|_| AttestationError::Certificate)?;+ if issuer_name != subject_name {+ return Err(AttestationError::UntrustedChain);+ }+ if cert.signature_algorithm != cert.tbs_certificate.signature+ || cert.signature_algorithm.parameters.is_some()+ {+ return Err(AttestationError::Certificate);+ }+ let curve = ec_curve(issuer).ok_or(AttestationError::UntrustedChain)?;+ let algorithm: &dyn VerificationAlgorithm = match (curve, cert.signature_algorithm.oid) {+ (OID_P384, OID_ECDSA_SHA384) => &signature::ECDSA_P384_SHA384_ASN1,+ (OID_P384, OID_ECDSA_SHA256) => &signature::ECDSA_P384_SHA256_ASN1,+ (OID_P256, OID_ECDSA_SHA256) => &signature::ECDSA_P256_SHA256_ASN1,+ _ => return Err(AttestationError::UntrustedChain),+ };+ let issuer_key = issuer+ .tbs_certificate+ .subject_public_key_info+ .subject_public_key+ .as_bytes()+ .ok_or(AttestationError::Certificate)?;+ let signature = cert+ .signature+ .as_bytes()+ .ok_or(AttestationError::Certificate)?;+ let tbs = cert+ .tbs_certificate+ .to_der()+ .map_err(|_| AttestationError::Certificate)?;+ UnparsedPublicKey::new(algorithm, issuer_key)+ .verify(&tbs, signature)+ .map_err(|_| AttestationError::UntrustedChain)+}++fn ec_curve(cert: &Certificate) -> Option<ObjectIdentifier> {+ let algorithm = &cert.tbs_certificate.subject_public_key_info.algorithm;+ if algorithm.oid != OID_EC_PUBLIC_KEY {+ return None;+ }+ algorithm.parameters.as_ref()?.decode_as().ok()+}++fn leaf_nonce(leaf: &Certificate) -> Result<[u8; 32], AttestationError> {+ let mut found = leaf+ .tbs_certificate+ .extensions+ .iter()+ .flatten()+ .filter(|extension| extension.extn_id == OID_NONCE);+ let extension = found.next().ok_or(AttestationError::Nonce)?;+ if found.next().is_some() {+ return Err(AttestationError::Nonce);+ }+ let value = extension.extn_value.as_bytes();+ let nonce = value+ .strip_prefix(&NONCE_EXTENSION_PREFIX)+ .ok_or(AttestationError::Nonce)?;+ nonce.try_into().map_err(|_| AttestationError::Nonce)+}++fn leaf_public_key(leaf: &Certificate) -> Result<[u8; PUBLIC_KEY_LEN], AttestationError> {+ if ec_curve(leaf) != Some(OID_P256) {+ return Err(AttestationError::KeyId);+ }+ let point = leaf+ .tbs_certificate+ .subject_public_key_info+ .subject_public_key+ .as_bytes()+ .ok_or(AttestationError::KeyId)?;+ if point.first() != Some(&0x04) {+ return Err(AttestationError::KeyId);+ }+ point.try_into().map_err(|_| AttestationError::KeyId)+}++fn cose_public_key(value: &Value) -> Option<[u8; PUBLIC_KEY_LEN]> {+ let map = as_map(value)?;+ if map.len() != 5 {+ return None;+ }+ let int_entry = |label: i128| {+ map.iter()+ .find(|(key, _)| key.as_integer().map(i128::from) == Some(label))+ .map(|(_, value)| value)+ };+ let int_value = |label: i128| int_entry(label)?.as_integer().map(i128::from);+ if int_value(1)? != 2 || int_value(3)? != -7 || int_value(-1)? != 1 {+ return None;+ }+ let x = int_entry(-2)?.as_bytes()?;+ let y = int_entry(-3)?.as_bytes()?;+ if x.len() != 32 || y.len() != 32 {+ return None;+ }+ let mut point = [0u8; PUBLIC_KEY_LEN];+ point[0] = 0x04;+ point[1..33].copy_from_slice(x);+ point[33..].copy_from_slice(y);+ Some(point)+}++fn configured_app_id<'a>(rp_id_hash: &[u8], config: &'a AppAttestConfig) -> Option<&'a str> {+ config+ .app_ids+ .iter()+ .find(|app_id| constant_time_eq(&sha256(app_id.as_bytes()), rp_id_hash))+ .map(String::as_str)+}++fn read_counter(auth_data: &[u8]) -> u32 {+ u32::from_be_bytes([+ auth_data[FLAGS_INDEX + 1],+ auth_data[FLAGS_INDEX + 2],+ auth_data[FLAGS_INDEX + 3],+ auth_data[FLAGS_INDEX + 4],+ ])+}++fn decode_next(input: &mut &[u8]) -> Option<Value> {+ ciborium::de::from_reader::<Value, _>(input).ok()+}++fn decode_single(bytes: &[u8]) -> Option<Value> {+ let mut rest = bytes;+ let value = decode_next(&mut rest)?;+ rest.is_empty().then_some(value)+}++fn as_map(value: &Value) -> Option<&[(Value, Value)]> {+ let map = value.as_map()?;+ if map.len() > MAX_MAP_ENTRIES {+ return None;+ }+ let distinct = map+ .iter()+ .enumerate()+ .all(|(index, (key, _))| map[..index].iter().all(|(other, _)| other != key));+ distinct.then_some(map.as_slice())+}++fn map_get<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a Value> {+ map.iter()+ .find(|(candidate, _)| candidate.as_text() == Some(key))+ .map(|(_, value)| value)+}++fn map_text<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a str> {+ map_get(map, key)?.as_text()+}++fn map_bytes<'a>(map: &'a [(Value, Value)], key: &str) -> Option<&'a [u8]> {+ map_get(map, key)?.as_bytes().map(Vec::as_slice)+}++pub fn sha256(bytes: &[u8]) -> [u8; 32] {+ Sha256::digest(bytes).into()+}++fn sha256_concat(first: &[u8], second: &[u8]) -> [u8; 32] {+ let mut hasher = Sha256::new();+ hasher.update(first);+ hasher.update(second);+ hasher.finalize().into()+}++fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {+ left.len() == right.len()+ && left+ .iter()+ .zip(right)+ .fold(0u8, |diff, (a, b)| diff | (a ^ b))+ == 0+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::Value as Json;+ use std::time::Duration;++ const VECTORS: &str = include_str!("testdata/vectors.json");++ struct Attestation {+ id: String,+ object: Vec<u8>,+ key_id: Vec<u8>,+ client_data_hash: Vec<u8>,+ app_id: String,+ environment: Environment,+ public_key: Vec<u8>,+ now: SystemTime,+ }++ struct Assertion {+ id: String,+ object: Vec<u8>,+ client_data: Vec<u8>,+ app_id: String,+ environment: Environment,+ public_key: Vec<u8>,+ previous_counter: u32,+ expected_counter: Option<u32>,+ }++ fn vectors() -> Vec<Json> {+ serde_json::from_str::<Json>(VECTORS)+ .expect("vectors parse")+ .as_array()+ .expect("a vector list")+ .clone()+ }++ fn testdata(name: &str) -> Vec<u8> {+ std::fs::read(+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("src/app_attest/testdata")+ .join(name),+ )+ .expect("vector file")+ }++ fn text<'a>(vector: &'a Json, field: &str) -> &'a str {+ vector[field].as_str().unwrap_or_else(|| panic!("{field}"))+ }++ fn b64(vector: &Json, field: &str) -> Vec<u8> {+ STANDARD.decode(text(vector, field)).expect("base64")+ }++ fn hex(value: &str) -> Vec<u8> {+ (0..value.len())+ .step_by(2)+ .map(|index| u8::from_str_radix(&value[index..index + 2], 16).expect("hex"))+ .collect()+ }++ fn time(value: &str) -> SystemTime {+ let millis = chrono::DateTime::parse_from_rfc3339(value)+ .expect("rfc3339")+ .timestamp_millis();+ SystemTime::UNIX_EPOCH + Duration::from_millis(millis as u64)+ }++ fn environment(vector: &Json) -> Environment {+ Environment::parse(text(vector, "environment")).unwrap_or(Environment::Production)+ }++ fn attestations() -> Vec<Attestation> {+ vectors()+ .iter()+ .filter(|vector| vector["kind"] == "attestation")+ .map(|vector| Attestation {+ id: text(vector, "id").to_owned(),+ object: testdata(text(vector, "attestation_object_file")),+ key_id: b64(vector, "key_id_b64"),+ client_data_hash: if vector["client_data_hash_b64"].is_string() {+ b64(vector, "client_data_hash_b64")+ } else {+ sha256(&b64(vector, "client_data_b64")).to_vec()+ },+ app_id: text(vector, "app_id").to_owned(),+ environment: environment(vector),+ public_key: vector["public_key_x962_hex"]+ .as_str()+ .map(hex)+ .unwrap_or_default(),+ now: time(text(vector, "now")),+ })+ .collect()+ }++ fn assertions() -> Vec<Assertion> {+ vectors()+ .iter()+ .filter(|vector| vector["kind"] == "assertion")+ .map(|vector| Assertion {+ id: text(vector, "id").to_owned(),+ object: testdata(text(vector, "assertion_file")),+ client_data: b64(vector, "client_data_b64"),+ app_id: text(vector, "app_id").to_owned(),+ environment: environment(vector),+ public_key: hex(text(vector, "public_key_x962_hex")),+ previous_counter: vector["previous_counter"].as_u64().unwrap_or(0) as u32,+ expected_counter: vector["expected_counter"]+ .as_u64()+ .map(|value| value as u32),+ })+ .collect()+ }++ fn config(app_id: &str, allow_development: bool) -> AppAttestConfig {+ AppAttestConfig {+ app_ids: vec!["3G5837T29K.com.fluxer".to_owned(), app_id.to_owned()],+ allow_development,+ }+ }++ fn development() -> Attestation {+ attestations()+ .into_iter()+ .find(|vector| vector.id == "veehaitch-ios-14.4-attestation")+ .expect("a development vector")+ }++ fn production() -> Attestation {+ attestations()+ .into_iter()+ .find(|vector| vector.id == "node-app-attest-production-attestation")+ .expect("a production vector")+ }++ fn verify(vector: &Attestation, object: &[u8]) -> Result<AttestedKey, AttestationError> {+ verify_attestation(+ object,+ &vector.key_id,+ &vector.client_data_hash,+ vector.now,+ &config(&vector.app_id, true),+ )+ }++ fn rewrite(object: &[u8], edit: impl FnOnce(&mut Vec<(Value, Value)>)) -> Vec<u8> {+ let mut value: Value = ciborium::de::from_reader(object).expect("cbor");+ let Value::Map(map) = &mut value else {+ panic!("not a map")+ };+ edit(map);+ let mut out = Vec::new();+ ciborium::ser::into_writer(&value, &mut out).expect("encode");+ out+ }++ fn entry<'a>(map: &'a mut [(Value, Value)], key: &str) -> &'a mut Value {+ &mut map+ .iter_mut()+ .find(|(candidate, _)| candidate.as_text() == Some(key))+ .expect("key")+ .1+ }++ fn auth_data(object: &[u8]) -> Vec<u8> {+ let value: Value = ciborium::de::from_reader(object).expect("cbor");+ map_bytes(value.as_map().expect("map"), "authData")+ .expect("authData")+ .to_vec()+ }++ fn flip(bytes: &mut [u8], index: usize) {+ bytes[index] ^= 0x01;+ }++ #[test]+ fn every_real_attestation_verifies_inside_its_validity() {+ let vectors = attestations();+ assert_eq!(vectors.len(), 2);+ for vector in &vectors {+ let attested = verify(vector, &vector.object)+ .unwrap_or_else(|error| panic!("{}: {error:?}", vector.id));+ assert_eq!(attested.environment, vector.environment, "{}", vector.id);+ assert_eq!(attested.app_id, vector.app_id, "{}", vector.id);+ if !vector.public_key.is_empty() {+ assert_eq!(+ attested.public_key.to_vec(),+ vector.public_key,+ "{}",+ vector.id+ );+ }+ assert_eq!(+ verify(vector, &rewrite(&vector.object, |_| {})),+ Ok(attested),+ "{} re-encoded",+ vector.id+ );+ }+ }++ #[test]+ fn every_real_assertion_verifies_and_returns_its_counter() {+ let vectors = assertions();+ assert_eq!(vectors.len(), 1);+ for vector in &vectors {+ let counter = verify_assertion(+ &vector.object,+ &vector.client_data,+ KeyForAssertion {+ public_key: &vector.public_key,+ app_id: &vector.app_id,+ environment: vector.environment,+ },+ vector.previous_counter,+ &config(&vector.app_id, true),+ )+ .unwrap_or_else(|error| panic!("{}: {error:?}", vector.id));+ assert!(counter > vector.previous_counter, "{}", vector.id);+ if let Some(expected) = vector.expected_counter {+ assert_eq!(counter, expected, "{}", vector.id);+ }+ }+ }++ #[test]+ fn attestation_rejects_the_wrong_app_id_or_disallowed_development() {+ let vector = development();+ let mut wrong_app = config("ABCDEFGHIJ.de.vincent-haupert.apple-appattest-poc", true);+ wrong_app.app_ids.retain(|app_id| app_id != &vector.app_id);+ let check = |config: &AppAttestConfig| {+ verify_attestation(+ &vector.object,+ &vector.key_id,+ &vector.client_data_hash,+ vector.now,+ config,+ )+ };+ assert_eq!(check(&wrong_app), Err(AttestationError::AppId));+ assert_eq!(+ check(&config(&vector.app_id, false)),+ Err(AttestationError::DevelopmentNotAllowed)+ );+ let production = production();+ assert!(+ verify_attestation(+ &production.object,+ &production.key_id,+ &production.client_data_hash,+ production.now,+ &config(&production.app_id, false),+ )+ .is_ok()+ );+ }++ fn assertion_vector() -> Assertion {+ assertions()+ .into_iter()+ .find(|vector| vector.id == "veehaitch-ios-14.4-assertion")+ .expect("an assertion vector")+ }++ fn rewrite_assertion(object: &[u8], field: &str, edit: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {+ rewrite(object, |map| {+ let Value::Bytes(bytes) = entry(map, field) else {+ panic!("{field}")+ };+ edit(bytes);+ })+ }++ #[test]+ fn assertion_rejects_replays_changes_and_foreign_keys() {+ let vector = assertion_vector();+ let config = config(&vector.app_id, true);+ let key = KeyForAssertion {+ public_key: &vector.public_key,+ app_id: &vector.app_id,+ environment: Environment::Development,+ };+ let check = verify_assertion;+ assert_eq!(+ check(&vector.object, &vector.client_data, key, 0, &config),+ Ok(1)+ );+ assert_eq!(+ check(&vector.object, &vector.client_data, key, 1, &config),+ Err(AssertionError::Counter)+ );+ assert_eq!(+ check(&vector.object, &vector.client_data, key, 7, &config),+ Err(AssertionError::Counter)+ );+ assert_eq!(+ check(&vector.object, b"wurzelpfropg", key, 0, &config),+ Err(AssertionError::Signature)+ );+ for index in [0, 32, 36] {+ let object = rewrite_assertion(&vector.object, "authenticatorData", |data| {+ flip(data, index)+ });+ assert_eq!(+ check(&object, &vector.client_data, key, 0, &config),+ Err(AssertionError::Signature),+ "byte {index}"+ );+ }+ let object = rewrite_assertion(&vector.object, "signature", |signature| {+ let last = signature.len() - 1;+ flip(signature, last);+ });+ assert_eq!(+ check(&object, &vector.client_data, key, 0, &config),+ Err(AssertionError::Signature)+ );+ let object = rewrite_assertion(&vector.object, "authenticatorData", |data| data.push(0));+ assert_eq!(+ check(&object, &vector.client_data, key, 0, &config),+ Err(AssertionError::Malformed)+ );+ let other = production();+ let other_key = verify(&other, &other.object)+ .expect("another key")+ .public_key;+ assert_eq!(+ check(+ &vector.object,+ &vector.client_data,+ KeyForAssertion {+ public_key: &other_key,+ ..key+ },+ 0,+ &config+ ),+ Err(AssertionError::Signature)+ );+ let other_app = "ABCDEFGHIJ.de.vincent-haupert.apple-appattest-poc";+ assert_eq!(+ check(+ &vector.object,+ &vector.client_data,+ KeyForAssertion {+ app_id: other_app,+ ..key+ },+ 0,+ &AppAttestConfig {+ app_ids: vec![other_app.to_owned()],+ allow_development: true,+ }+ ),+ Err(AssertionError::AppId)+ );+ assert_eq!(+ check(+ &vector.object,+ &vector.client_data,+ key,+ 0,+ &AppAttestConfig {+ app_ids: vec![other_app.to_owned()],+ allow_development: true,+ }+ ),+ Err(AssertionError::KeyNotAccepted)+ );+ let mut no_development = config.clone();+ no_development.allow_development = false;+ assert_eq!(+ check(&vector.object, &vector.client_data, key, 0, &no_development),+ Err(AssertionError::KeyNotAccepted)+ );+ }++ #[test]+ fn attestation_rejects_a_chain_that_copies_apple_names_under_another_root() {+ let object = testdata("synthetic-untrusted-root-attestation.cbor");+ let key_id = STANDARD+ .decode("G+TdKKtHTrJ9RAqGkJl/1YfvudeyG7u/uHZRWyJct8Y=")+ .expect("key id");+ let config = config("3G5837T29K.com.fluxer", true);+ assert!(check_attested_auth_data(&auth_data(&object), &key_id, &config).is_ok());+ assert_eq!(+ verify_attestation(+ &object,+ &key_id,+ &sha256(b"fake-challenge"),+ SystemTime::UNIX_EPOCH + Duration::from_secs(1_793_836_800),+ &config,+ ),+ Err(AttestationError::UntrustedChain)+ );+ }+}diff --git a/fluxer_users/src/main.rs b/fluxer_users/src/main.rsindex 849b86e1f..0b0303b11 100644--- a/fluxer_users/src/main.rs+++ b/fluxer_users/src/main.rs@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+mod app_attest;mod pseudonym;mod router_impl;mod shard_impl;@@ -41,6 +42,12 @@ async fn main() -> anyhow::Result<()> {async fn build_shard(config: &ServiceConfig) -> anyhow::Result<UsersShard> {pseudonym::configure_from_env()?;+ let app_attest = app_attest::AppAttestConfig::from_env()?;+ tracing::info!(+ app_ids = app_attest.app_ids.len(),+ allow_development = app_attest.allow_development,+ "app attest configuration"+ );match config.database_backend {DatabaseBackend::Postgres => {let postgres_config = fluxer_svc::postgres::PostgresConfig::from_service_config(config);@@ -50,6 +57,7 @@ async fn build_shard(config: &ServiceConfig) -> anyhow::Result<UsersShard> {kv,config.cache_max_entries,config.cache_ttl,+ app_attest,))}DatabaseBackend::Cassandra => {@@ -57,7 +65,8 @@ async fn build_shard(config: &ServiceConfig) -> anyhow::Result<UsersShard> {{let scylla_config = fluxer_svc::scylla::ScyllaConfig::from_service_config(config);let db = fluxer_svc::scylla::connect(&scylla_config).await?;- UsersShard::new_scylla(db, config.cache_max_entries, config.cache_ttl).await+ UsersShard::new_scylla(db, config.cache_max_entries, config.cache_ttl, app_attest)+ .await}#[cfg(not(feature = "scylla"))]{diff --git a/fluxer_users/src/router_impl.rs b/fluxer_users/src/router_impl.rsindex c8d9d1ffc..ae8573cfa 100644--- a/fluxer_users/src/router_impl.rs+++ b/fluxer_users/src/router_impl.rs@@ -17,7 +17,10 @@ impl RouterService for UsersRouter {fn route_key(req: &UserRequest) -> String {match req {- UserRequest::Invalidate { user_id } => user_id.to_string(),+ UserRequest::Invalidate { user_id }+ | UserRequest::AppAttestCreateChallenge { user_id, .. }+ | UserRequest::AppAttestRegisterKey { user_id, .. }+ | UserRequest::AppAttestSubmitAge { user_id, .. } => user_id.to_string(),UserRequest::GetPartialsByIds { user_ids, .. } => user_ids.iter().min()@@ -57,7 +60,10 @@ impl RouterService for UsersRouter {ids.dedup();Some(format!("api_partials:{instance_name}:{}", ids.join(",")))}- UserRequest::Invalidate { .. } => None,+ UserRequest::Invalidate { .. }+ | UserRequest::AppAttestCreateChallenge { .. }+ | UserRequest::AppAttestRegisterKey { .. }+ | UserRequest::AppAttestSubmitAge { .. } => None,}}diff --git a/fluxer_users/src/shard_impl.rs b/fluxer_users/src/shard_impl.rsindex a1b337dc7..41820eb8d 100644--- a/fluxer_users/src/shard_impl.rs+++ b/fluxer_users/src/shard_impl.rs@@ -1,5 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-or-later+use crate::app_attest::AppAttestConfig;+use crate::app_attest::service::AppAttestService;+use crate::app_attest::store::AppAttestStore;use crate::types::{ApiUserPartial, UserPartial, UserRequest, UserResponse};#[cfg(feature = "scylla")]use chrono::{DateTime, Utc};@@ -25,7 +28,7 @@ use std::future::Future;use std::hash::{Hash, Hasher};use std::sync::Arc;use std::sync::atomic::{AtomicU64, Ordering};-use std::time::Duration;+use std::time::{Duration, SystemTime};#[cfg(feature = "scylla")]type OptionalTimestamp = Option<MaybeEmpty<DateTime<Utc>>>;@@ -45,6 +48,7 @@ const USER_CACHE_MAX_GENERATION_STRIPES: usize = 1 << 20;pub struct UsersShard {storage: UsersStorage,caches: UserCaches,+ app_attest: AppAttestService,}struct UserCaches {@@ -230,8 +234,14 @@ impl UserCaches {}impl UsersShard {- pub fn new_postgres(kv: postgres::KvClient, max_entries: u64, ttl: Duration) -> Self {+ pub fn new_postgres(+ kv: postgres::KvClient,+ max_entries: u64,+ ttl: Duration,+ app_attest: AppAttestConfig,+ ) -> Self {Self {+ app_attest: AppAttestService::new(app_attest, AppAttestStore::Postgres(kv.clone())),storage: UsersStorage::Postgres(PostgresUsersStorage { kv }),caches: UserCaches::new(max_entries, ttl),}@@ -242,6 +252,7 @@ impl UsersShard {db: Arc<Session>,max_entries: u64,ttl: Duration,+ app_attest: AppAttestConfig,) -> anyhow::Result<Self> {let stmt_partial = db.prepare(format!(@@ -254,7 +265,11 @@ impl UsersShard {)).await?;+ let app_attest_store = AppAttestStore::Scylla(Arc::new(+ crate::app_attest::store::ScyllaAppAttestStore::new(db.clone()),+ ));Ok(Self {+ app_attest: AppAttestService::new(app_attest, app_attest_store),storage: UsersStorage::Scylla(Arc::new(ScyllaUsersStorage {db,stmt_partial,@@ -523,6 +538,43 @@ impl ShardService for UsersShard {self.caches.invalidate(user_id).await;Ok(UserResponse::Invalidated)}+ UserRequest::AppAttestCreateChallenge { user_id, purpose } => {+ self.app_attest+ .create_challenge(user_id, purpose, SystemTime::now())+ .await+ }+ UserRequest::AppAttestRegisterKey {+ user_id,+ key_id,+ attestation_base64,+ challenge,+ } => {+ self.app_attest+ .register_key(+ user_id,+ &key_id,+ &attestation_base64,+ &challenge,+ SystemTime::now(),+ )+ .await+ }+ UserRequest::AppAttestSubmitAge {+ user_id,+ key_id,+ assertion_base64,+ client_data_base64,+ } => {+ self.app_attest+ .submit_age(+ user_id,+ &key_id,+ &assertion_base64,+ &client_data_base64,+ SystemTime::now(),+ )+ .await+ }}}}diff --git a/fluxer_users/src/types.rs b/fluxer_users/src/types.rsindex 4841d5abd..a632aba63 100644--- a/fluxer_users/src/types.rs+++ b/fluxer_users/src/types.rs@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+use crate::app_attest::{AgeFloor, AppAttestRejection, ChallengePurpose};use crate::pseudonym::pseudonym;use fluxer_common::user_flags::AccountStanding;#[cfg(test)]@@ -27,6 +28,25 @@ pub enum UserRequest {#[serde(deserialize_with = "deserialize_i64_from_number_or_string")]user_id: i64,},+ AppAttestCreateChallenge {+ #[serde(deserialize_with = "deserialize_i64_from_number_or_string")]+ user_id: i64,+ purpose: ChallengePurpose,+ },+ AppAttestRegisterKey {+ #[serde(deserialize_with = "deserialize_i64_from_number_or_string")]+ user_id: i64,+ key_id: String,+ attestation_base64: String,+ challenge: String,+ },+ AppAttestSubmitAge {+ #[serde(deserialize_with = "deserialize_i64_from_number_or_string")]+ user_id: i64,+ key_id: String,+ assertion_base64: String,+ client_data_base64: String,+ },}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -35,6 +55,18 @@ pub enum UserResponse {FoundPartials(Vec<UserPartial>),FoundApiPartials(Vec<ApiUserPartial>),Invalidated,+ AppAttestChallenge {+ challenge: String,+ expires_at: String,+ },+ AppAttestKeyRegistered,+ AppAttestAgeAccepted {+ age_floor: AgeFloor,+ attested_at: String,+ },+ AppAttestRejected {+ code: AppAttestRejection,+ },}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -200,4 +232,55 @@ mod tests {}));}++ #[test]+ fn app_attest_messages_match_the_api_contract() {+ let request: UserRequest = serde_json::from_value(json!({+ "op": "AppAttestSubmitAge",+ "user_id": "9007199254740993",+ "key_id": "a2V5",+ "assertion_base64": "YXNzZXJ0aW9u",+ "client_data_base64": "e30="+ }))+ .unwrap();+ assert!(matches!(+ request,+ UserRequest::AppAttestSubmitAge {+ user_id: 9007199254740993,+ ..+ }+ ));+ let request: UserRequest = serde_json::from_value(json!({+ "op": "AppAttestCreateChallenge",+ "user_id": 42,+ "purpose": "assert"+ }))+ .unwrap();+ assert!(matches!(+ request,+ UserRequest::AppAttestCreateChallenge {+ user_id: 42,+ purpose: ChallengePurpose::Assert+ }+ ));+ assert_eq!(+ serde_json::to_value(UserResponse::AppAttestAgeAccepted {+ age_floor: AgeFloor::UnderMinimum,+ attested_at: "2026-11-05T12:00:00.000Z".to_owned(),+ })+ .unwrap(),+ json!({"AppAttestAgeAccepted": {"age_floor": "under_minimum", "attested_at": "2026-11-05T12:00:00.000Z"}})+ );+ assert_eq!(+ serde_json::to_value(UserResponse::AppAttestKeyRegistered).unwrap(),+ json!("AppAttestKeyRegistered")+ );+ assert_eq!(+ serde_json::to_value(UserResponse::AppAttestRejected {+ code: AppAttestRejection::NotConfigured,+ })+ .unwrap(),+ json!({"AppAttestRejected": {"code": "not_configured"}})+ );+ }}diff --git a/packages/constants/src/AgeAssuranceConstants.ts b/packages/constants/src/AgeAssuranceConstants.tsnew file mode 100644index 000000000..84c198eb2--- /dev/null+++ b/packages/constants/src/AgeAssuranceConstants.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {ValueOf} from '@fluxer/constants/src/ValueOf';++export const AttestedAgeFloors = {+ ADULT: 'adult',+ MINOR: 'minor',+ UNDER_MINIMUM: 'under_minimum',+} as const;++export type AttestedAgeFloor = ValueOf<typeof AttestedAgeFloors>;++const ATTESTED_AGE_FLOOR_VALUES: ReadonlyArray<AttestedAgeFloor> = Object.values(AttestedAgeFloors);++export function isAttestedAgeFloor(value: unknown): value is AttestedAgeFloor {+ return typeof value === 'string' && (ATTESTED_AGE_FLOOR_VALUES as ReadonlyArray<string>).includes(value);+}++export const AppAttestChallengePurposes = {+ ATTEST: 'attest',+ ASSERT: 'assert',+} as const;++export type AppAttestChallengePurpose = ValueOf<typeof AppAttestChallengePurposes>;++export const APP_ATTEST_KEY_ID_BYTES = 32;+export const APP_ATTEST_CHALLENGE_BYTES = 32;+export const APP_ATTEST_ATTESTATION_MAX_BYTES = 16 * 1024;+export const APP_ATTEST_ASSERTION_MAX_BYTES = 4 * 1024;+export const APP_ATTEST_CLIENT_DATA_MAX_BYTES = 1024;diff --git a/packages/constants/src/ApiErrorCodes.ts b/packages/constants/src/ApiErrorCodes.tsindex afab92395..53f4b92d6 100644--- a/packages/constants/src/ApiErrorCodes.ts+++ b/packages/constants/src/ApiErrorCodes.ts@@ -17,6 +17,13 @@ export const APIErrorCodes = {ACLS_MUST_BE_NON_EMPTY: 'ACLS_MUST_BE_NON_EMPTY',ADMIN_API_KEY_NOT_FOUND: 'ADMIN_API_KEY_NOT_FOUND',ALREADY_FRIENDS: 'ALREADY_FRIENDS',+ APP_ATTEST_NOT_AVAILABLE: 'APP_ATTEST_NOT_AVAILABLE',+ APP_ATTEST_KEY_NOT_REGISTERED: 'APP_ATTEST_KEY_NOT_REGISTERED',+ APP_ATTEST_KEY_IN_USE: 'APP_ATTEST_KEY_IN_USE',+ APP_ATTEST_CHALLENGE_INVALID: 'APP_ATTEST_CHALLENGE_INVALID',+ APP_ATTEST_ATTESTATION_INVALID: 'APP_ATTEST_ATTESTATION_INVALID',+ APP_ATTEST_ASSERTION_INVALID: 'APP_ATTEST_ASSERTION_INVALID',+ APP_ATTEST_REQUEST_INVALID: 'APP_ATTEST_REQUEST_INVALID',BOTS_CANNOT_CREATE_GUILDS: 'BOTS_CANNOT_CREATE_GUILDS',BOTS_CANNOT_SEND_FRIEND_REQUESTS: 'BOTS_CANNOT_SEND_FRIEND_REQUESTS',BOT_ALREADY_IN_GUILD: 'BOT_ALREADY_IN_GUILD',diff --git a/packages/errors/src/domains/user/AppAttestAssertionInvalidError.ts b/packages/errors/src/domains/user/AppAttestAssertionInvalidError.tsnew file mode 100644index 000000000..000cdede7--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestAssertionInvalidError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';++export class AppAttestAssertionInvalidError extends BadRequestError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_ASSERTION_INVALID});+ }+}diff --git a/packages/errors/src/domains/user/AppAttestAttestationInvalidError.ts b/packages/errors/src/domains/user/AppAttestAttestationInvalidError.tsnew file mode 100644index 000000000..b825986a2--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestAttestationInvalidError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';++export class AppAttestAttestationInvalidError extends BadRequestError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_ATTESTATION_INVALID});+ }+}diff --git a/packages/errors/src/domains/user/AppAttestChallengeInvalidError.ts b/packages/errors/src/domains/user/AppAttestChallengeInvalidError.tsnew file mode 100644index 000000000..bc6259a64--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestChallengeInvalidError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';++export class AppAttestChallengeInvalidError extends BadRequestError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_CHALLENGE_INVALID});+ }+}diff --git a/packages/errors/src/domains/user/AppAttestKeyInUseError.ts b/packages/errors/src/domains/user/AppAttestKeyInUseError.tsnew file mode 100644index 000000000..6ce8ca5ee--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestKeyInUseError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';++export class AppAttestKeyInUseError extends ConflictError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_KEY_IN_USE});+ }+}diff --git a/packages/errors/src/domains/user/AppAttestKeyNotRegisteredError.ts b/packages/errors/src/domains/user/AppAttestKeyNotRegisteredError.tsnew file mode 100644index 000000000..261b1f3be--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestKeyNotRegisteredError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';++export class AppAttestKeyNotRegisteredError extends BadRequestError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_KEY_NOT_REGISTERED});+ }+}diff --git a/packages/errors/src/domains/user/AppAttestNotAvailableError.ts b/packages/errors/src/domains/user/AppAttestNotAvailableError.tsnew file mode 100644index 000000000..3d6ede316--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestNotAvailableError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {NotFoundError} from '@fluxer/errors/src/domains/core/NotFoundError';++export class AppAttestNotAvailableError extends NotFoundError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_NOT_AVAILABLE});+ }+}diff --git a/packages/errors/src/domains/user/AppAttestRequestInvalidError.ts b/packages/errors/src/domains/user/AppAttestRequestInvalidError.tsnew file mode 100644index 000000000..ac16c8cae--- /dev/null+++ b/packages/errors/src/domains/user/AppAttestRequestInvalidError.ts@@ -0,0 +1,10 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';+import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';++export class AppAttestRequestInvalidError extends BadRequestError {+ constructor() {+ super({code: APIErrorCodes.APP_ATTEST_REQUEST_INVALID});+ }+}diff --git a/packages/errors/src/i18n/ErrorCodeMappings.ts b/packages/errors/src/i18n/ErrorCodeMappings.tsindex 863c6783f..f715418ab 100644--- a/packages/errors/src/i18n/ErrorCodeMappings.ts+++ b/packages/errors/src/i18n/ErrorCodeMappings.ts@@ -11,6 +11,13 @@ type AllErrorCodes = APIErrorCode | ValidationErrorCode;export const ErrorCodeToI18nKey = {[APIErrorCodes.ACCESS_DENIED]: 'permissions.missing_access',[APIErrorCodes.ACCOUNT_LIMITED]: 'account.limited',+ [APIErrorCodes.APP_ATTEST_NOT_AVAILABLE]: 'account.app_attest_not_available',+ [APIErrorCodes.APP_ATTEST_KEY_NOT_REGISTERED]: 'account.app_attest_key_not_registered',+ [APIErrorCodes.APP_ATTEST_KEY_IN_USE]: 'account.app_attest_key_in_use',+ [APIErrorCodes.APP_ATTEST_CHALLENGE_INVALID]: 'account.app_attest_challenge_invalid',+ [APIErrorCodes.APP_ATTEST_ATTESTATION_INVALID]: 'account.app_attest_attestation_invalid',+ [APIErrorCodes.APP_ATTEST_ASSERTION_INVALID]: 'account.app_attest_assertion_invalid',+ [APIErrorCodes.APP_ATTEST_REQUEST_INVALID]: 'account.app_attest_request_invalid',[APIErrorCodes.ACCOUNT_VERIFICATION_REQUIRED]: 'account.verification_required',[APIErrorCodes.DATE_OF_BIRTH_REQUIRED]: 'account.date_of_birth_required',[APIErrorCodes.DATE_OF_BIRTH_ALREADY_SET]: 'account.date_of_birth_already_set',diff --git a/packages/errors/src/i18n/ErrorI18nMessages.ts b/packages/errors/src/i18n/ErrorI18nMessages.tsindex d10017c7e..b86b86886 100644--- a/packages/errors/src/i18n/ErrorI18nMessages.ts+++ b/packages/errors/src/i18n/ErrorI18nMessages.ts@@ -2,6 +2,13 @@export const ERROR_I18N_MESSAGES = {'account.already_claimed': 'This account is already set up to sign in from other devices.',+ 'account.app_attest_assertion_invalid': "We couldn't confirm this age check from your device.",+ 'account.app_attest_attestation_invalid': "We couldn't confirm this device key.",+ 'account.app_attest_challenge_invalid': 'This check has expired or was already used. Try again.',+ 'account.app_attest_key_in_use': 'This device key is already registered to another account.',+ 'account.app_attest_key_not_registered': "This device key isn't registered with your account.",+ 'account.app_attest_not_available': "Age checks from the app aren't available on this instance.",+ 'account.app_attest_request_invalid': "This age check request isn't valid.",'account.below_minimum_age': "You aren't old enough to have an account here.",'account.date_of_birth_already_set': 'Your date of birth is already set.','account.date_of_birth_required': 'Enter your date of birth to continue.',diff --git a/packages/errors/src/i18n/weblate/locales/ar.json b/packages/errors/src/i18n/weblate/locales/ar.jsonindex beaf5b2f1..941732f71 100644--- a/packages/errors/src/i18n/weblate/locales/ar.json+++ b/packages/errors/src/i18n/weblate/locales/ar.json@@ -1,5 +1,12 @@{"account.already_claimed": "هذا الحساب مُعدّ بالفعل لتسجيل الدخول من أجهزة أخرى.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "أنت لست كبيرًا بما يكفي لامتلاك حساب هنا.","account.communication_disabled": "المراسلة معطلة.","account.date_of_birth_already_set": "تاريخ ميلادك مُعين بالفعل.",diff --git a/packages/errors/src/i18n/weblate/locales/bg.json b/packages/errors/src/i18n/weblate/locales/bg.jsonindex 5f7d73c77..352ad8a89 100644--- a/packages/errors/src/i18n/weblate/locales/bg.json+++ b/packages/errors/src/i18n/weblate/locales/bg.json@@ -1,5 +1,12 @@{"account.already_claimed": "Този акаунт вече е настроен за вход от други устройства.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Още нямаш нужната възраст, за да имаш акаунт тук.","account.communication_disabled": "Комуникацията е деактивирана.","account.date_of_birth_already_set": "Датата ти на раждане вече е зададена.",diff --git a/packages/errors/src/i18n/weblate/locales/cs.json b/packages/errors/src/i18n/weblate/locales/cs.jsonindex 6b422139b..4ed5f0afd 100644--- a/packages/errors/src/i18n/weblate/locales/cs.json+++ b/packages/errors/src/i18n/weblate/locales/cs.json@@ -1,5 +1,12 @@{"account.already_claimed": "Tento účet už je nastavený pro přihlášení z jiných zařízení.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Nemáte dostatečný věk, abyste si tu mohli vytvořit účet.","account.communication_disabled": "Komunikace je zakázána.","account.date_of_birth_already_set": "Vaše datum narození je již nastaveno.",diff --git a/packages/errors/src/i18n/weblate/locales/da.json b/packages/errors/src/i18n/weblate/locales/da.jsonindex 4a273077b..1e3c98cb8 100644--- a/packages/errors/src/i18n/weblate/locales/da.json+++ b/packages/errors/src/i18n/weblate/locales/da.json@@ -1,5 +1,12 @@{"account.already_claimed": "Denne konto er allerede sat op til at logge ind fra andre enheder.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Du er ikke gammel nok til at have en konto her.","account.communication_disabled": "Kommunikation er slået fra.","account.date_of_birth_already_set": "Din fødselsdato er allerede angivet.",diff --git a/packages/errors/src/i18n/weblate/locales/de.json b/packages/errors/src/i18n/weblate/locales/de.jsonindex 279bedbb4..68ed2a3cb 100644--- a/packages/errors/src/i18n/weblate/locales/de.json+++ b/packages/errors/src/i18n/weblate/locales/de.json@@ -1,5 +1,12 @@{"account.already_claimed": "Dieser Account ist bereits für die Anmeldung auf anderen Geräten eingerichtet.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Du bist nicht alt genug, um hier einen Account zu haben.","account.communication_disabled": "Kommunikation ist deaktiviert.","account.date_of_birth_already_set": "Dein Geburtsdatum ist bereits festgelegt.",diff --git a/packages/errors/src/i18n/weblate/locales/el.json b/packages/errors/src/i18n/weblate/locales/el.jsonindex 0ba8e3ee7..e5a09d84d 100644--- a/packages/errors/src/i18n/weblate/locales/el.json+++ b/packages/errors/src/i18n/weblate/locales/el.json@@ -1,5 +1,12 @@{"account.already_claimed": "Αυτός ο λογαριασμός έχει ήδη ρυθμιστεί για σύνδεση από άλλες συσκευές.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Δεν έχετε ακόμη την απαιτούμενη ηλικία για να έχετε λογαριασμό εδώ.","account.communication_disabled": "Η επικοινωνία είναι απενεργοποιημένη.","account.date_of_birth_already_set": "Η ημερομηνία γέννησής σας έχει ήδη οριστεί.",diff --git a/packages/errors/src/i18n/weblate/locales/en-GB.json b/packages/errors/src/i18n/weblate/locales/en-GB.jsonindex dc497fc58..7c5faaf27 100644--- a/packages/errors/src/i18n/weblate/locales/en-GB.json+++ b/packages/errors/src/i18n/weblate/locales/en-GB.json@@ -1,5 +1,12 @@{"account.already_claimed": "This account is already set up to sign in from other devices.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "You aren't old enough to have an account here.","account.communication_disabled": "Communication is disabled.","account.date_of_birth_already_set": "Your date of birth is already set.",diff --git a/packages/errors/src/i18n/weblate/locales/es-419.json b/packages/errors/src/i18n/weblate/locales/es-419.jsonindex 6dd34fff4..7c6bfb800 100644--- a/packages/errors/src/i18n/weblate/locales/es-419.json+++ b/packages/errors/src/i18n/weblate/locales/es-419.json@@ -1,5 +1,12 @@{"account.already_claimed": "Esta cuenta ya está configurada para iniciar sesión desde otros dispositivos.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "No tienes la edad suficiente para tener una cuenta aquí.","account.communication_disabled": "La comunicación está deshabilitada.","account.date_of_birth_already_set": "Tu fecha de nacimiento ya está establecida.",diff --git a/packages/errors/src/i18n/weblate/locales/es-ES.json b/packages/errors/src/i18n/weblate/locales/es-ES.jsonindex 2f21b0b72..cceaec061 100644--- a/packages/errors/src/i18n/weblate/locales/es-ES.json+++ b/packages/errors/src/i18n/weblate/locales/es-ES.json@@ -1,5 +1,12 @@{"account.already_claimed": "Esta cuenta ya está configurada para iniciar sesión desde otros dispositivos.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "No tienes la edad suficiente para tener una cuenta aquí.","account.communication_disabled": "La comunicación está deshabilitada.","account.date_of_birth_already_set": "Tu fecha de nacimiento ya está establecida.",diff --git a/packages/errors/src/i18n/weblate/locales/fi.json b/packages/errors/src/i18n/weblate/locales/fi.jsonindex 06ecda53b..920045dd0 100644--- a/packages/errors/src/i18n/weblate/locales/fi.json+++ b/packages/errors/src/i18n/weblate/locales/fi.json@@ -1,5 +1,12 @@{"account.already_claimed": "Tähän tiliin voi jo kirjautua muilta laitteilta.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Et ole tarpeeksi vanha käyttämään tiliä täällä.","account.communication_disabled": "Viestintä on poistettu käytöstä.","account.date_of_birth_already_set": "Syntymäaikasi on jo asetettu.",diff --git a/packages/errors/src/i18n/weblate/locales/fr.json b/packages/errors/src/i18n/weblate/locales/fr.jsonindex b0d6e97d1..e01508fef 100644--- a/packages/errors/src/i18n/weblate/locales/fr.json+++ b/packages/errors/src/i18n/weblate/locales/fr.json@@ -1,5 +1,12 @@{"account.already_claimed": "Ce compte est déjà configuré pour se connecter depuis d'autres appareils.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Vous n’avez pas l’âge requis pour avoir un compte ici.","account.communication_disabled": "La communication est désactivée.","account.date_of_birth_already_set": "Votre date de naissance est déjà définie.",diff --git a/packages/errors/src/i18n/weblate/locales/he.json b/packages/errors/src/i18n/weblate/locales/he.jsonindex 62f7ea065..cdccba7e0 100644--- a/packages/errors/src/i18n/weblate/locales/he.json+++ b/packages/errors/src/i18n/weblate/locales/he.json@@ -1,5 +1,12 @@{"account.already_claimed": "החשבון הזה כבר מוגדר להתחברות ממכשירים אחרים.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "אתה צעיר מדי בשביל חשבון כאן.","account.communication_disabled": "התקשורת מושבתת.","account.date_of_birth_already_set": "תאריך הלידה שלך כבר מוגדר.",diff --git a/packages/errors/src/i18n/weblate/locales/hi.json b/packages/errors/src/i18n/weblate/locales/hi.jsonindex e3d8debb3..d7bf8f9c4 100644--- a/packages/errors/src/i18n/weblate/locales/hi.json+++ b/packages/errors/src/i18n/weblate/locales/hi.json@@ -1,5 +1,12 @@{"account.already_claimed": "यह अकाउंट पहले से दूसरे डिवाइस से साइन इन करने के लिए सेट है।",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "आप यहाँ अकाउंट रखने के लिए पर्याप्त उम्र के नहीं हैं।","account.communication_disabled": "कम्युनिकेशन डिसेबल कर दिया गया है।","account.date_of_birth_already_set": "आपकी जन्मतिथि पहले से ही सेट है।",diff --git a/packages/errors/src/i18n/weblate/locales/hr.json b/packages/errors/src/i18n/weblate/locales/hr.jsonindex d4ef3c37a..40a9fcf7c 100644--- a/packages/errors/src/i18n/weblate/locales/hr.json+++ b/packages/errors/src/i18n/weblate/locales/hr.json@@ -1,5 +1,12 @@{"account.already_claimed": "Ovaj račun već je postavljen za prijavu s drugih uređaja.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Niste dovoljno stari da biste ovdje imali račun.","account.communication_disabled": "Komunikacija je onemogućena.","account.date_of_birth_already_set": "Vaš datum rođenja je već postavljen.",diff --git a/packages/errors/src/i18n/weblate/locales/hu.json b/packages/errors/src/i18n/weblate/locales/hu.jsonindex edbd53ae6..f61320e21 100644--- a/packages/errors/src/i18n/weblate/locales/hu.json+++ b/packages/errors/src/i18n/weblate/locales/hu.json@@ -1,5 +1,12 @@{"account.already_claimed": "Ez a fiók már be van állítva a más eszközökről való bejelentkezéshez.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Még nem vagy elég idős ahhoz, hogy itt fiókod legyen.","account.communication_disabled": "A kommunikáció letiltva.","account.date_of_birth_already_set": "A születési dátumod már be van állítva.",diff --git a/packages/errors/src/i18n/weblate/locales/id.json b/packages/errors/src/i18n/weblate/locales/id.jsonindex e45ecd45e..86af17c9a 100644--- a/packages/errors/src/i18n/weblate/locales/id.json+++ b/packages/errors/src/i18n/weblate/locales/id.json@@ -1,5 +1,12 @@{"account.already_claimed": "Akun ini sudah diatur agar bisa masuk dari perangkat lain.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Kamu belum cukup umur untuk memiliki akun di sini.","account.communication_disabled": "Komunikasi dinonaktifkan.","account.date_of_birth_already_set": "Tanggal lahirmu sudah diatur.",diff --git a/packages/errors/src/i18n/weblate/locales/it.json b/packages/errors/src/i18n/weblate/locales/it.jsonindex 11a4498e8..6bf2d38e8 100644--- a/packages/errors/src/i18n/weblate/locales/it.json+++ b/packages/errors/src/i18n/weblate/locales/it.json@@ -1,5 +1,12 @@{"account.already_claimed": "Questo account è già configurato per accedere da altri dispositivi.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Non hai l'età minima per avere un account qui.","account.communication_disabled": "La comunicazione è disabilitata.","account.date_of_birth_already_set": "La tua data di nascita è già impostata.",diff --git a/packages/errors/src/i18n/weblate/locales/ja.json b/packages/errors/src/i18n/weblate/locales/ja.jsonindex b5de9eda7..0672377ff 100644--- a/packages/errors/src/i18n/weblate/locales/ja.json+++ b/packages/errors/src/i18n/weblate/locales/ja.json@@ -1,5 +1,12 @@{"account.already_claimed": "このアカウントは、すでにほかのデバイスからサインインできるように設定されています。",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "アカウントを作成するには年齢が足りません。","account.communication_disabled": "コミュニケーションが無効になっています。","account.date_of_birth_already_set": "生年月日はすでに設定されています。",diff --git a/packages/errors/src/i18n/weblate/locales/ko.json b/packages/errors/src/i18n/weblate/locales/ko.jsonindex 3910805dd..0528c3424 100644--- a/packages/errors/src/i18n/weblate/locales/ko.json+++ b/packages/errors/src/i18n/weblate/locales/ko.json@@ -1,5 +1,12 @@{"account.already_claimed": "이 계정은 이미 다른 기기에서 로그인할 수 있도록 설정되어 있어요.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "이곳에서 계정을 만들 수 있는 나이가 아니에요.","account.communication_disabled": "메시지 보내기가 비활성화되었어요.","account.date_of_birth_already_set": "생년월일이 이미 설정되어 있어요.",diff --git a/packages/errors/src/i18n/weblate/locales/lt.json b/packages/errors/src/i18n/weblate/locales/lt.jsonindex b0637957d..deea7b299 100644--- a/packages/errors/src/i18n/weblate/locales/lt.json+++ b/packages/errors/src/i18n/weblate/locales/lt.json@@ -1,5 +1,12 @@{"account.already_claimed": "Ši paskyra jau nustatyta prisijungti iš kitų įrenginių.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Esate per jauni, kad čia turėtumėte paskyrą.","account.communication_disabled": "Bendravimas išjungtas.","account.date_of_birth_already_set": "Jūsų gimimo data jau nustatyta.",diff --git a/packages/errors/src/i18n/weblate/locales/nl.json b/packages/errors/src/i18n/weblate/locales/nl.jsonindex 616976e78..e3cbc28d8 100644--- a/packages/errors/src/i18n/weblate/locales/nl.json+++ b/packages/errors/src/i18n/weblate/locales/nl.json@@ -1,5 +1,12 @@{"account.already_claimed": "Dit account is al ingesteld om op andere apparaten in te loggen.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Je bent niet oud genoeg om hier een account te hebben.","account.communication_disabled": "Communicatie is uitgeschakeld.","account.date_of_birth_already_set": "Je geboortedatum is al ingesteld.",diff --git a/packages/errors/src/i18n/weblate/locales/no.json b/packages/errors/src/i18n/weblate/locales/no.jsonindex 098cfde83..67a0be9ac 100644--- a/packages/errors/src/i18n/weblate/locales/no.json+++ b/packages/errors/src/i18n/weblate/locales/no.json@@ -1,5 +1,12 @@{"account.already_claimed": "Denne kontoen er allerede satt opp for innlogging fra andre enheter.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Du er ikke gammel nok til å ha en konto her.","account.communication_disabled": "Kommunikasjon er deaktivert.","account.date_of_birth_already_set": "Fødselsdatoen din er allerede angitt.",diff --git a/packages/errors/src/i18n/weblate/locales/pl.json b/packages/errors/src/i18n/weblate/locales/pl.jsonindex 84a93473d..020cd6bfd 100644--- a/packages/errors/src/i18n/weblate/locales/pl.json+++ b/packages/errors/src/i18n/weblate/locales/pl.json@@ -1,5 +1,12 @@{"account.already_claimed": "To konto jest już skonfigurowane do logowania na innych urządzeniach.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Nie spełniasz wymogu minimalnego wieku, aby założyć tu konto.","account.communication_disabled": "Komunikacja wyłączona.","account.date_of_birth_already_set": "Twoja data urodzenia jest już ustawiona.",diff --git a/packages/errors/src/i18n/weblate/locales/pt-BR.json b/packages/errors/src/i18n/weblate/locales/pt-BR.jsonindex baf4e9389..bde7b21cb 100644--- a/packages/errors/src/i18n/weblate/locales/pt-BR.json+++ b/packages/errors/src/i18n/weblate/locales/pt-BR.json@@ -1,5 +1,12 @@{"account.already_claimed": "Esta conta já está configurada para entrar em outros dispositivos.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Você não tem idade suficiente para ter uma conta aqui.","account.communication_disabled": "A comunicação está desativada.","account.date_of_birth_already_set": "Sua data de nascimento já foi definida.",diff --git a/packages/errors/src/i18n/weblate/locales/ro.json b/packages/errors/src/i18n/weblate/locales/ro.jsonindex 9f884dc1a..475fcd6ec 100644--- a/packages/errors/src/i18n/weblate/locales/ro.json+++ b/packages/errors/src/i18n/weblate/locales/ro.json@@ -1,5 +1,12 @@{"account.already_claimed": "Acest cont este deja configurat pentru conectarea de pe alte dispozitive.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Nu ai vârsta suficientă pentru a avea un cont aici.","account.communication_disabled": "Comunicarea este dezactivată.","account.date_of_birth_already_set": "Data nașterii tale este deja setată.",diff --git a/packages/errors/src/i18n/weblate/locales/ru.json b/packages/errors/src/i18n/weblate/locales/ru.jsonindex 5a72ea228..49b31c044 100644--- a/packages/errors/src/i18n/weblate/locales/ru.json+++ b/packages/errors/src/i18n/weblate/locales/ru.json@@ -1,5 +1,12 @@{"account.already_claimed": "Для этого аккаунта уже настроен вход с других устройств.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Вы пока не достигли возраста, необходимого для аккаунта здесь.","account.communication_disabled": "Общение отключено.","account.date_of_birth_already_set": "Дата вашего рождения уже установлена.",diff --git a/packages/errors/src/i18n/weblate/locales/sv-SE.json b/packages/errors/src/i18n/weblate/locales/sv-SE.jsonindex 6c22bc263..b0c06664c 100644--- a/packages/errors/src/i18n/weblate/locales/sv-SE.json+++ b/packages/errors/src/i18n/weblate/locales/sv-SE.json@@ -1,5 +1,12 @@{"account.already_claimed": "Det här kontot är redan klart för inloggning från andra enheter.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Du är inte tillräckligt gammal för att ha ett konto här.","account.communication_disabled": "Kommunikationen är inaktiverad.","account.date_of_birth_already_set": "Ditt födelsedatum är redan angivet.",diff --git a/packages/errors/src/i18n/weblate/locales/th.json b/packages/errors/src/i18n/weblate/locales/th.jsonindex 0a5ba6ae4..ad7420e39 100644--- a/packages/errors/src/i18n/weblate/locales/th.json+++ b/packages/errors/src/i18n/weblate/locales/th.json@@ -1,5 +1,12 @@{"account.already_claimed": "บัญชีนี้ตั้งค่าให้ลงชื่อเข้าใช้จากอุปกรณ์อื่นได้แล้ว",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "คุณอายุไม่ถึงเกณฑ์ที่จะมีบัญชีที่นี่ได้","account.communication_disabled": "ปิดใช้งานการสื่อสารแล้ว","account.date_of_birth_already_set": "วันเกิดของคุณถูกตั้งค่าไว้แล้ว",diff --git a/packages/errors/src/i18n/weblate/locales/tr.json b/packages/errors/src/i18n/weblate/locales/tr.jsonindex 6a25dd25d..d027978d4 100644--- a/packages/errors/src/i18n/weblate/locales/tr.json+++ b/packages/errors/src/i18n/weblate/locales/tr.json@@ -1,5 +1,12 @@{"account.already_claimed": "Bu hesap, başka cihazlardan giriş yapmak için zaten ayarlanmış.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Burada bir hesap oluşturmak için yaşınız yetmiyor.","account.communication_disabled": "İletişim devre dışı bırakıldı.","account.date_of_birth_already_set": "Doğum tarihiniz zaten ayarlanmış.",diff --git a/packages/errors/src/i18n/weblate/locales/uk.json b/packages/errors/src/i18n/weblate/locales/uk.jsonindex e28af246e..8e97e809b 100644--- a/packages/errors/src/i18n/weblate/locales/uk.json+++ b/packages/errors/src/i18n/weblate/locales/uk.json@@ -1,5 +1,12 @@{"account.already_claimed": "Для цього облікового запису вже налаштовано вхід з інших пристроїв.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Ви ще недостатньо дорослі, щоб мати тут обліковий запис.","account.communication_disabled": "Спілкування вимкнено.","account.date_of_birth_already_set": "Вашу дату народження вже встановлено.",diff --git a/packages/errors/src/i18n/weblate/locales/vi.json b/packages/errors/src/i18n/weblate/locales/vi.jsonindex 7eeb4803d..84d4230bd 100644--- a/packages/errors/src/i18n/weblate/locales/vi.json+++ b/packages/errors/src/i18n/weblate/locales/vi.json@@ -1,5 +1,12 @@{"account.already_claimed": "Tài khoản này đã được thiết lập để đăng nhập từ các thiết bị khác.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "Bạn chưa đủ tuổi để có tài khoản ở đây.","account.communication_disabled": "Quyền giao tiếp đã bị tắt.","account.date_of_birth_already_set": "Ngày sinh của bạn đã được thiết lập.",diff --git a/packages/errors/src/i18n/weblate/locales/zh-CN.json b/packages/errors/src/i18n/weblate/locales/zh-CN.jsonindex 1e9bb33c6..f7255ee87 100644--- a/packages/errors/src/i18n/weblate/locales/zh-CN.json+++ b/packages/errors/src/i18n/weblate/locales/zh-CN.json@@ -1,5 +1,12 @@{"account.already_claimed": "此账号已设置为可从其他设备登录。",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "你未达到在此创建账号的最低年龄。","account.communication_disabled": "你已被禁言。","account.date_of_birth_already_set": "你的出生日期已设置。",diff --git a/packages/errors/src/i18n/weblate/locales/zh-TW.json b/packages/errors/src/i18n/weblate/locales/zh-TW.jsonindex 847019f9a..b70db2158 100644--- a/packages/errors/src/i18n/weblate/locales/zh-TW.json+++ b/packages/errors/src/i18n/weblate/locales/zh-TW.json@@ -1,5 +1,12 @@{"account.already_claimed": "此帳號已設定為可從其他裝置登入。",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "你未滿可在此建立帳號的年齡。","account.communication_disabled": "通訊功能已停用。","account.date_of_birth_already_set": "你的出生日期已設定。",diff --git a/packages/errors/src/i18n/weblate/messages.json b/packages/errors/src/i18n/weblate/messages.jsonindex e94deaa3a..05a33d550 100644--- a/packages/errors/src/i18n/weblate/messages.json+++ b/packages/errors/src/i18n/weblate/messages.json@@ -1,5 +1,12 @@{"account.already_claimed": "This account is already set up to sign in from other devices.",+ "account.app_attest_assertion_invalid": "We couldn't confirm this age check from your device.",+ "account.app_attest_attestation_invalid": "We couldn't confirm this device key.",+ "account.app_attest_challenge_invalid": "This check has expired or was already used. Try again.",+ "account.app_attest_key_in_use": "This device key is already registered to another account.",+ "account.app_attest_key_not_registered": "This device key isn't registered with your account.",+ "account.app_attest_not_available": "Age checks from the app aren't available on this instance.",+ "account.app_attest_request_invalid": "This age check request isn't valid.","account.below_minimum_age": "You aren't old enough to have an account here.","account.communication_disabled": "Communication is disabled.","account.date_of_birth_already_set": "Your date of birth is already set.",diff --git a/packages/openapi/src/registry/ResponseRegistry.ts b/packages/openapi/src/registry/ResponseRegistry.tsindex c6e682a34..d5e41e769 100644--- a/packages/openapi/src/registry/ResponseRegistry.ts+++ b/packages/openapi/src/registry/ResponseRegistry.ts@@ -68,6 +68,14 @@ const COMMON_RESPONSES: Record<string, OpenAPIResponse> = {},},},+ '409': {+ description: 'Conflict - The request conflicts with the current state of the resource',+ content: {+ 'application/json': {+ schema: {$ref: '#/components/schemas/Error'},+ },+ },+ },'429': {description: 'Too Many Requests - You are being rate limited',content: {diff --git a/packages/schema/src/domains/user/AgeAssuranceSchemas.ts b/packages/schema/src/domains/user/AgeAssuranceSchemas.tsnew file mode 100644index 000000000..ea6cd3d86--- /dev/null+++ b/packages/schema/src/domains/user/AgeAssuranceSchemas.ts@@ -0,0 +1,129 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ APP_ATTEST_ASSERTION_MAX_BYTES,+ APP_ATTEST_ATTESTATION_MAX_BYTES,+ APP_ATTEST_CHALLENGE_BYTES,+ APP_ATTEST_CLIENT_DATA_MAX_BYTES,+ APP_ATTEST_KEY_ID_BYTES,+ AppAttestChallengePurposes,+ AttestedAgeFloors,+} from '@fluxer/constants/src/AgeAssuranceConstants';+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';+import {withBase64Binary} from '@fluxer/schema/src/primitives/Base64BinaryFields';+import {base64LengthForBytes, isValidBase64} from '@fluxer/schema/src/primitives/FileValidators';+import {createNamedStringLiteralUnion} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import {z} from 'zod';++const BASE64URL_REGEX = /^[A-Za-z0-9_-]+$/;++function decodedBase64Length(value: string): number {+ const padding = value.length - value.replace(/=+$/, '').length;+ return (value.length / 4) * 3 - padding;+}++function base64BytesType(minBytes: number, maxBytes: number) {+ const minLength = base64LengthForBytes(minBytes);+ const maxLength = base64LengthForBytes(maxBytes);+ return withBase64Binary(+ z+ .string()+ .superRefine((value, ctx) => {+ if (value.length < minLength || value.length > maxLength) {+ ctx.addIssue({+ code: 'custom',+ message: ValidationErrorCodes.BASE64_LENGTH_INVALID,+ params: {min: minLength, maxLength},+ });+ return;+ }+ if (!isValidBase64(value)) {+ ctx.addIssue({code: 'custom', message: ValidationErrorCodes.INVALID_BASE64_FORMAT});+ return;+ }+ const bytes = decodedBase64Length(value);+ if (bytes < minBytes || bytes > maxBytes) {+ ctx.addIssue({+ code: 'custom',+ message: ValidationErrorCodes.BASE64_LENGTH_INVALID,+ params: {min: minLength, maxLength},+ });+ }+ })+ .meta({minLength, maxLength}),+ );+}++const CHALLENGE_LENGTH = Math.ceil((APP_ATTEST_CHALLENGE_BYTES * 4) / 3);++const AppAttestChallengeType = z+ .string()+ .superRefine((value, ctx) => {+ if (value.length !== CHALLENGE_LENGTH || !BASE64URL_REGEX.test(value)) {+ ctx.addIssue({code: 'custom', message: ValidationErrorCodes.INVALID_BASE64_FORMAT});+ }+ })+ .meta({minLength: CHALLENGE_LENGTH, maxLength: CHALLENGE_LENGTH})+ .describe('Challenge from the challenge endpoint, 32 bytes as unpadded base64url');++const AppAttestKeyIdType = base64BytesType(APP_ATTEST_KEY_ID_BYTES, APP_ATTEST_KEY_ID_BYTES).describe(+ 'App Attest key identifier from DCAppAttestService, 32 bytes as standard base64',+);++const AppAttestChallengePurposeSchema = createNamedStringLiteralUnion(+ [+ [AppAttestChallengePurposes.ATTEST, 'ATTEST', 'Challenge for registering a new App Attest key'],+ [AppAttestChallengePurposes.ASSERT, 'ASSERT', 'Challenge for an assertion signed by a registered key'],+ ],+ 'What the challenge will be used for',+);++export const AttestedAgeFloorSchema = createNamedStringLiteralUnion(+ [+ [AttestedAgeFloors.ADULT, 'ADULT', 'The device reports an adult'],+ [AttestedAgeFloors.MINOR, 'MINOR', 'The device reports someone under 18'],+ [AttestedAgeFloors.UNDER_MINIMUM, 'UNDER_MINIMUM', 'The device reports someone under 13'],+ ],+ 'Age floor reported by the device',+);++export const AppAttestChallengeRequest = z.object({+ purpose: AppAttestChallengePurposeSchema,+});++export type AppAttestChallengeRequest = z.infer<typeof AppAttestChallengeRequest>;++export const AppAttestChallengeResponse = z.object({+ challenge: z.string().describe('Single use challenge, 32 bytes as unpadded base64url'),+ expires_at: z.iso.datetime().describe('When the challenge stops working'),+});++export type AppAttestChallengeResponse = z.infer<typeof AppAttestChallengeResponse>;++export const AppAttestKeyRegisterRequest = z.object({+ key_id: AppAttestKeyIdType,+ attestation: base64BytesType(1, APP_ATTEST_ATTESTATION_MAX_BYTES).describe(+ 'Attestation object from DCAppAttestService.attestKey as standard base64',+ ),+ challenge: AppAttestChallengeType,+});++export type AppAttestKeyRegisterRequest = z.infer<typeof AppAttestKeyRegisterRequest>;++export const AgeAssuranceSubmitRequest = z.object({+ key_id: AppAttestKeyIdType,+ assertion: base64BytesType(1, APP_ATTEST_ASSERTION_MAX_BYTES).describe(+ 'Assertion from DCAppAttestService.generateAssertion as standard base64',+ ),+ client_data: base64BytesType(1, APP_ATTEST_CLIENT_DATA_MAX_BYTES).describe(+ 'The exact UTF-8 JSON bytes the app signed, as standard base64. The JSON holds challenge and age_floor',+ ),+});++export type AgeAssuranceSubmitRequest = z.infer<typeof AgeAssuranceSubmitRequest>;++export const AgeAssuranceSubmitResponse = z.object({+ age_floor: AttestedAgeFloorSchema,+});++export type AgeAssuranceSubmitResponse = z.infer<typeof AgeAssuranceSubmitResponse>;diff --git a/tools/dev/cassandra_target_schema.json b/tools/dev/cassandra_target_schema.jsonindex 9f2459c2b..78ad986a3 100644--- a/tools/dev/cassandra_target_schema.json+++ b/tools/dev/cassandra_target_schema.json@@ -1010,6 +1010,83 @@"primary_key": "(log_id)","options": ""},+ {+ "name": "app_attest_challenges",+ "columns": [+ {+ "name": "challenge",+ "type": "text"+ },+ {+ "name": "user_id",+ "type": "bigint"+ },+ {+ "name": "purpose",+ "type": "text"+ },+ {+ "name": "expires_at",+ "type": "timestamp"+ }+ ],+ "primary_key": "(challenge)",+ "options": ""+ },+ {+ "name": "app_attest_key_lookup",+ "columns": [+ {+ "name": "key_id",+ "type": "text"+ },+ {+ "name": "user_id",+ "type": "bigint"+ }+ ],+ "primary_key": "(key_id)",+ "options": ""+ },+ {+ "name": "app_attest_keys",+ "columns": [+ {+ "name": "user_id",+ "type": "bigint"+ },+ {+ "name": "key_id",+ "type": "text"+ },+ {+ "name": "public_key",+ "type": "blob"+ },+ {+ "name": "environment",+ "type": "text"+ },+ {+ "name": "app_id",+ "type": "text"+ },+ {+ "name": "counter",+ "type": "bigint"+ },+ {+ "name": "created_at",+ "type": "timestamp"+ },+ {+ "name": "last_used_at",+ "type": "timestamp"+ }+ ],+ "primary_key": "((user_id), key_id)",+ "options": ""+ },{"name": "applications","columns": [@@ -10427,6 +10504,14 @@{"name": "enforcement_decision_id","type": "bigint"+ },+ {+ "name": "attested_age_floor",+ "type": "text"+ },+ {+ "name": "age_attested_at",+ "type": "timestamp"}],"primary_key": "((user_id))",