Skip to content

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

TypeScript fluxerfluxerapp
33.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {ThemeTypes} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {
	CaptchaProviderSchema,
	InstantAccountAvailabilitySchema,
} from '@fluxer/schema/src/domains/account/AccountTierSchemas';
import {
	WebAuthnAuthenticationOptions,
	WebAuthnAuthenticationResponse,
	WebAuthnRegistrationResponse,
} from '@fluxer/schema/src/domains/auth/WebAuthnSchemas';
import {GuildEntryResult} from '@fluxer/schema/src/domains/user/AccountSchemas';
import {UserPartialResponse, UserPrivateResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import {
	createNamedStringLiteralUnion,
	createStringType,
	SnowflakeStringType,
} from '@fluxer/schema/src/primitives/SchemaPrimitives';
import {EmailType, GlobalNameType, PasswordType, UsernameType} from '@fluxer/schema/src/primitives/UserValidators';
import {z} from 'zod';

const RegisterThemeType = createNamedStringLiteralUnion(
	[
		[ThemeTypes.DARK, 'DARK', 'Dark colour theme'],
		[ThemeTypes.DARK_LEGACY, 'DARK_LEGACY', 'Legacy dark colour theme (original neutral grey palette)'],
		[ThemeTypes.COAL, 'COAL', 'Coal/darker colour theme'],
		[ThemeTypes.LIGHT, 'LIGHT', 'Light colour theme'],
		[ThemeTypes.SYSTEM, 'SYSTEM', 'Follow system colour preference'],
	] as const,
	'UI theme preference',
);

const SixDigitCodeType = createStringType(6, 6).refine((value) => /^\d{6}$/.test(value), 'Invalid code');

export const RegisterRequest = z.object({
	email: EmailType.optional().describe('Email address for the new account'),
	username: UsernameType.optional().describe('Username for the new account (1-32 characters)'),
	global_name: GlobalNameType.optional().describe('Display name shown to other users'),
	password: PasswordType.optional().describe('Password for the new account'),
	date_of_birth: createStringType(10, 10)
		.refine((value) => /^\d{4}-\d{2}-\d{2}$/.test(value), 'Invalid date format')
		.optional()
		.describe('Date of birth in YYYY-MM-DD format'),
	consent: z
		.boolean()
		.default(false)
		.describe(
			'Whether the person submitted the step that says creating the account accepts the terms of service. Must be true when the instance publishes terms or a privacy policy',
		),
	invite_code: createStringType(0, 256).nullish().describe('Guild invite code to join after registration'),
	registration_url_code: createStringType(1, 128)
		.nullish()
		.describe('Admin-issued registration URL code to use for this registration'),
	theme: RegisterThemeType.optional().describe('Initial UI theme preference for the new account'),
	setup_token: createStringType(1, 256)
		.nullish()
		.describe('Setup token of a new self-hosted instance. Required until the first admin account exists'),
});

export type RegisterRequest = z.infer<typeof RegisterRequest>;

export const UsernameInstanceRegisterRequest = RegisterRequest.extend({
	email: createStringType(1, 320)
		.optional()
		.describe('Email address sent by older apps. Accepted and discarded on username instances'),
});

export const UsernameSuggestionsRequest = z.object({
	global_name: GlobalNameType.describe('Display name to generate username suggestions from'),
});

export type UsernameSuggestionsRequest = z.infer<typeof UsernameSuggestionsRequest>;

export const UsernameAvailabilityQuery = z.object({
	username: UsernameType.describe('Username to check (1-32 characters)'),
});

export type UsernameAvailabilityQuery = z.infer<typeof UsernameAvailabilityQuery>;

const LoginIdentifierType = createStringType(1, 320);

const LoginRequestObject = z.object({
	email: EmailType.optional().describe('Email address for authentication. Send this or login, not both'),
	login: LoginIdentifierType.optional().describe(
		'Sign-in identifier. An email address on email instances, a username on username instances',
	),
	password: PasswordType.describe('Account password'),
	invite_code: createStringType(0, 256).nullish().describe('Guild invite code to join after login'),
});

function requireLoginIdentifier(value: unknown): unknown {
	if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;
	const {login, ...rest} = value as Record<string, unknown>;
	if (rest.email !== undefined) return rest;
	if (login !== undefined && login !== null && login !== '') return value;
	return {...rest, email: null};
}

export const LoginRequest = z.preprocess(requireLoginIdentifier, LoginRequestObject);

export const UsernameInstanceLoginRequest = z.preprocess(
	requireLoginIdentifier,
	LoginRequestObject.extend({
		email: LoginIdentifierType.optional().describe(
			'Sign-in identifier sent by older apps. A username or username@instance host on username instances',
		),
	}),
);

export type LoginRequest = z.infer<typeof LoginRequest>;

export const LogoutAuthSessionsRequest = z.object({
	session_id_hashes: z.array(createStringType()).max(100).describe('Array of session ID hashes to log out (max 100)'),
	password: PasswordType.optional().describe('Account password for verification'),
});

export type LogoutAuthSessionsRequest = z.infer<typeof LogoutAuthSessionsRequest>;

export const ForgotPasswordRequest = z.object({
	email: EmailType.describe('Email address to send password reset link'),
});

export type ForgotPasswordRequest = z.infer<typeof ForgotPasswordRequest>;

export const ResetPasswordRequest = z.object({
	token: createStringType(64, 64).describe('Password reset token from email'),
	password: PasswordType.describe('New password to set'),
});

export type ResetPasswordRequest = z.infer<typeof ResetPasswordRequest>;

export const ResetPasswordTokenParam = z.object({
	token: createStringType(64, 64).describe('Password reset token from email'),
});

export type ResetPasswordTokenParam = z.infer<typeof ResetPasswordTokenParam>;

export const ValidateResetPasswordTokenResponse = z.object({
	valid: z.boolean().describe('Whether the password reset token is valid and unexpired'),
});

export type ValidateResetPasswordTokenResponse = z.infer<typeof ValidateResetPasswordTokenResponse>;

export const EmailRevertRequest = z.object({
	token: createStringType(64, 64).describe('Email revert token from email'),
	password: PasswordType.describe('Account password for verification'),
});

export type EmailRevertRequest = z.infer<typeof EmailRevertRequest>;

export const VerifyEmailRequest = z.object({
	token: createStringType(64, 64).describe('Email verification token from email'),
});

export type VerifyEmailRequest = z.infer<typeof VerifyEmailRequest>;

export const SudoVerificationSchema = z.object({
	password: PasswordType.optional().describe('Account password for sudo verification'),
	mfa_method: createNamedStringLiteralUnion(
		[
			['totp', 'TOTP', 'Time-based one-time password authentication via authenticator app'],
			['webauthn', 'WebAuthn', 'Security key or biometric authentication'],
			['email_code', 'Email code', 'A 6-digit code sent to the account email address'],
		],
		'MFA method to use for verification',
	).optional(),
	mfa_code: createStringType(1, 32).optional().describe('MFA verification code from an authenticator app'),
	email_code_ticket: createStringType(1, 128)
		.optional()
		.describe('Ticket from POST /users/@me/sudo/email-code, sent with mfa_method email_code'),
	email_code: SixDigitCodeType.optional().describe('The 6-digit code from the email, sent with mfa_method email_code'),
	webauthn_response: WebAuthnAuthenticationResponse.optional().describe('WebAuthn authentication response'),
	webauthn_challenge: createStringType().optional().describe('WebAuthn challenge string'),
});
export const SsoStatusResponse = z.object({
	enabled: z.boolean().describe('Whether SSO is enabled for this instance'),
	enforced: z.boolean().describe('Whether SSO is required for all users'),
	username_from_provider: z
		.boolean()
		.describe('Whether each SSO sign-in sets the username from the provider, so SSO accounts cannot change it'),
	display_name: z.string().nullable().describe('Display name of the SSO provider'),
	button_label: z
		.string()
		.nullable()
		.describe('Text for the SSO sign-in button, or null when the client shows its default label'),
	redirect_uri: z.string().describe('OAuth redirect URI for SSO'),
});

export type SsoStatusResponse = z.infer<typeof SsoStatusResponse>;

export const SsoStartResponse = z.object({
	authorization_url: z.string().describe('URL to redirect user to for SSO authentication'),
	state: z.string().describe('State parameter for CSRF protection'),
	redirect_uri: z.string().describe('OAuth redirect URI used for the SSO provider callback'),
	client_binding: z
		.string()
		.describe('Secret the client keeps and sends back with the code and state to complete this sign-in'),
});

export type SsoStartResponse = z.infer<typeof SsoStartResponse>;

export const AuthTokenWithUserIdResponse = z.object({
	token: z.string().describe('Authentication token for API requests'),
	user_id: SnowflakeStringType.describe('ID of the authenticated user'),
	user: UserPartialResponse.describe('Partial user data for the authenticated account'),
	device_proof: z
		.string()
		.optional()
		.describe(
			'Opaque value to keep beside this account and send on later sign-ins from this device. It is not a credential',
		),
});

export type AuthTokenWithUserIdResponse = z.infer<typeof AuthTokenWithUserIdResponse>;

export const AuthRegistrationPendingApprovalResponse = z.object({
	registration_pending_approval: z.literal(true).describe('Registration succeeded and is waiting for admin approval'),
	user_id: SnowflakeStringType.describe('ID of the registered account waiting for approval'),
});

export type AuthRegistrationPendingApprovalResponse = z.infer<typeof AuthRegistrationPendingApprovalResponse>;

const AuthMfaRequiredResponse = z.object({
	mfa: z.literal(true).describe('Indicates MFA is required to complete authentication'),
	ticket: z.string().describe('MFA ticket to use when completing MFA verification'),
	allowed_methods: z.array(z.string()).max(10).describe('List of allowed MFA methods'),
	totp: z.boolean().describe('Whether TOTP authenticator MFA is available'),
	webauthn: z.boolean().describe('Whether WebAuthn security key MFA is available'),
	backup_codes: z.boolean().describe('Whether the account has at least one unconsumed backup code'),
});

export const AuthLoginResponse = z.union([AuthTokenWithUserIdResponse, AuthMfaRequiredResponse]);

export type AuthLoginResponse = z.infer<typeof AuthLoginResponse>;

const SsoRedirectField = {
	redirect_to: z.string().describe('URL to redirect the user to after completion'),
};

export const SsoCompleteResponse = z.union([
	AuthTokenWithUserIdResponse.extend(SsoRedirectField),
	AuthMfaRequiredResponse.extend(SsoRedirectField),
	z
		.object({
			linked: z.literal(true).describe('The SSO identity is now connected to the account that started the link'),
		})
		.extend(SsoRedirectField),
]);

export type SsoCompleteResponse = z.infer<typeof SsoCompleteResponse>;

export const RecoverAccountRequest = z.object({
	login: LoginIdentifierType.describe('Username of the account to recover'),
	recovery_key: createStringType(1, 128).describe('Recovery key from the recovery kit. Spaces and dashes are ignored'),
	password: PasswordType.describe('New password to set'),
});

export type RecoverAccountRequest = z.infer<typeof RecoverAccountRequest>;

const RecoveryKitIssuedFields = {
	recovery_key: z
		.string()
		.describe(
			'New recovery key as 8 groups of 4 joined by dashes. It replaces the one just used and is shown only once',
		),
	recovery_kit_created_at: z.iso.datetime().describe('ISO 8601 timestamp when the new recovery kit was created'),
};

export const RecoverAccountResponse = z.union([
	AuthTokenWithUserIdResponse.extend(RecoveryKitIssuedFields),
	AuthMfaRequiredResponse.extend(RecoveryKitIssuedFields),
]);

export type RecoverAccountResponse = z.infer<typeof RecoverAccountResponse>;

export const AuthRegisterSuccessResponse = AuthTokenWithUserIdResponse.extend({
	entry: GuildEntryResult.nullable().optional().describe('Community to open next, from an invite used during sign-up'),
});

export type AuthRegisterSuccessResponse = z.infer<typeof AuthRegisterSuccessResponse>;

export const AuthRegisterResponse = z.union([AuthRegisterSuccessResponse, AuthRegistrationPendingApprovalResponse]);

export type AuthRegisterResponse = z.infer<typeof AuthRegisterResponse>;

export const AuthSessionLocation = z.object({
	city: z.string().nullish().describe('The city name reported by the client'),
	region: z.string().nullish().describe('The region reported by the client'),
	country: z.string().nullish().describe('The country reported by the client'),
});

export type AuthSessionLocation = z.infer<typeof AuthSessionLocation>;

const AuthSessionClientInfo = z.object({
	platform: z.string().nullish().describe('The platform reported by the client'),
	os: z.string().nullish().describe('The operating system reported by the client'),
	browser: z.string().nullish().describe('The browser reported by the client'),
	device: z.enum(['mobile', 'desktop']).describe('Device class of the session, decided by the server'),
	location: AuthSessionLocation.nullish().describe('The geolocation data sent by the client'),
});

export const AuthSessionResponse = z.object({
	id_hash: z.string().describe('The base64url-encoded session id hash'),
	client_info: AuthSessionClientInfo.nullish().describe('Client metadata recorded for this session'),
	masked_ip: z.string().nullable().describe('Semi-redacted IP address recorded for this session'),
	approx_last_used_at: z.iso.datetime().nullish().describe('Approximate timestamp of the last session activity'),
	current: z.boolean().describe('Whether this is the current session making the request'),
});

export type AuthSessionResponse = z.infer<typeof AuthSessionResponse>;

export const AuthSessionsResponse = z.array(AuthSessionResponse);

export type AuthSessionsResponse = z.infer<typeof AuthSessionsResponse>;

export const WebAuthnAuthenticationOptionsResponse = WebAuthnAuthenticationOptions.omit({
	hints: true,
	extensions: true,
});

export type WebAuthnAuthenticationOptionsResponse = z.infer<typeof WebAuthnAuthenticationOptionsResponse>;

export const UsernameSuggestionsResponse = z.object({
	suggestions: z.array(z.string()).max(20).describe('List of suggested usernames'),
});

export type UsernameSuggestionsResponse = z.infer<typeof UsernameSuggestionsResponse>;

export const UsernameAvailabilityResponse = z.object({
	available: z.boolean().describe('Whether no other account holds this username'),
});

export type UsernameAvailabilityResponse = z.infer<typeof UsernameAvailabilityResponse>;

const DESKTOP_HANDOFF_RETURN_URI_PATTERN = /^fluxer(?:-canary|-development)?:\/\/handoff$/u;

export const DesktopHandoffReturnMethod = z.enum(['deep_link', 'code']);

export type DesktopHandoffReturnMethod = z.infer<typeof DesktopHandoffReturnMethod>;

export const HandoffInitiateRequest = z
	.object({
		return_uri: createStringType(1, 64)
			.refine((value) => DESKTOP_HANDOFF_RETURN_URI_PATTERN.test(value), ValidationErrorCodes.INVALID_FORMAT)
			.optional()
			.describe('Deep link the approving browser opens to return the sign-in to the initiating desktop app'),
	})
	.nullish();

export type HandoffInitiateRequest = z.infer<typeof HandoffInitiateRequest>;

export const HandoffInitiateResponse = z.object({
	code: z.string().describe('Handoff code to share with the receiving device'),
	expires_at: z.iso.datetime().describe('ISO 8601 timestamp when the handoff code expires'),
	poll_secret: z.string().optional().describe('Secret the initiating device must present to retrieve the token'),
	return_method: DesktopHandoffReturnMethod.optional().describe(
		'deep_link when the approving browser will hand the sign-in back through the return deep link, code otherwise',
	),
});

export type HandoffInitiateResponse = z.infer<typeof HandoffInitiateResponse>;

const HandoffInfoClientInfo = z.object({
	platform: z.string().nullish().describe('The platform of the requesting device'),
	os: z.string().nullish().describe('The operating system of the requesting device'),
	device: z.enum(['mobile', 'desktop']).describe('Device class of the requesting device, decided by the server'),
	location: AuthSessionLocation.nullish().describe('The approximate location of the requesting device'),
});

export const HandoffInfoResponse = z.object({
	status: z.string().describe('Current status of the handoff (pending, expired)'),
	client_info: HandoffInfoClientInfo.nullish().describe('Client information of the initiating device'),
	return_method: DesktopHandoffReturnMethod.optional().describe(
		'How the approving browser hands the sign-in back. deep_link opens the initiating app, code relies on the user comparing the code',
	),
});

export type HandoffInfoResponse = z.infer<typeof HandoffInfoResponse>;

export const HandoffStatusResponse = z.object({
	status: z.string().describe('Current status of the handoff (pending, completed, denied, expired)'),
	token: z.string().nullish().describe('Authentication token if handoff is complete'),
	user_id: SnowflakeStringType.nullish().describe('User ID if handoff is complete'),
	user: UserPartialResponse.nullish().describe('Partial user data if handoff is complete'),
});

export type HandoffStatusResponse = z.infer<typeof HandoffStatusResponse>;

export const SsoStartRequest = z.object({
	redirect_to: createStringType(0, 2048).nullish().describe('URL to redirect to after SSO completion'),
	redirect_uri: createStringType(0, 2048).nullish().describe('OAuth redirect URI to use for the SSO provider callback'),
});

export type SsoStartRequest = z.infer<typeof SsoStartRequest>;

export const SsoCompleteRequest = z.object({
	code: createStringType(1, 4096).describe('Authorization code from the SSO provider'),
	state: createStringType(1, 4096).describe('State parameter for CSRF protection'),
	client_binding: createStringType(1, 128)
		.nullish()
		.describe('The client_binding returned by SSO start. Required except for the mobile app callback'),
});

export type SsoCompleteRequest = z.infer<typeof SsoCompleteRequest>;

export const MfaTotpRequest = z.object({
	code: createStringType().describe('The TOTP code from the authenticator app'),
	ticket: createStringType().describe('The MFA ticket from the login response'),
});

export type MfaTotpRequest = z.infer<typeof MfaTotpRequest>;

export const MfaTicketRequest = z.object({
	ticket: createStringType().describe('The MFA ticket from the login response'),
});

export type MfaTicketRequest = z.infer<typeof MfaTicketRequest>;

export const AuthorizeIpRequest = z.object({
	token: createStringType().describe('The IP authorization token from email'),
});

export type AuthorizeIpRequest = z.infer<typeof AuthorizeIpRequest>;

export const SignInLinkRequest = z.object({
	token: createStringType().describe('The token from the sign-in link'),
});

export type SignInLinkRequest = z.infer<typeof SignInLinkRequest>;

export const IpAuthorizationPollQuery = z.object({
	ticket: createStringType().describe('The IP authorization ticket'),
});

export type IpAuthorizationPollQuery = z.infer<typeof IpAuthorizationPollQuery>;

export const IpAuthorizationPollResponse = z.object({
	completed: z.boolean().describe('Whether the IP authorization has been completed'),
	token: z.string().nullish().describe('Authentication token if authorization is complete'),
	user_id: SnowflakeStringType.nullish().describe('User ID if authorization is complete'),
	user: UserPartialResponse.nullish().describe('Partial user data if authorization is complete'),
});

export type IpAuthorizationPollResponse = z.infer<typeof IpAuthorizationPollResponse>;

export const WebAuthnAuthenticateRequest = z.object({
	response: WebAuthnAuthenticationResponse.describe('WebAuthn authentication response'),
	challenge: createStringType().describe('The challenge string from authentication options'),
});

export type WebAuthnAuthenticateRequest = z.infer<typeof WebAuthnAuthenticateRequest>;

export const WebAuthnMfaRequest = z.object({
	response: WebAuthnAuthenticationResponse.describe('WebAuthn authentication response'),
	challenge: createStringType().describe('The challenge string from authentication options'),
	ticket: createStringType().describe('The MFA ticket from the login response'),
});

export type WebAuthnMfaRequest = z.infer<typeof WebAuthnMfaRequest>;

export const HandoffCompleteRequest = z.object({
	code: createStringType().describe('The handoff code from the initiating session'),
	token: createStringType().optional().describe('The authentication token to transfer'),
	user_id: createStringType().describe('The user ID associated with the authenticated session'),
	return_method: DesktopHandoffReturnMethod.optional().describe(
		'deep_link returns a one-time grant the initiating app must present, code releases the token to the poll secret alone',
	),
});

export type HandoffCompleteRequest = z.infer<typeof HandoffCompleteRequest>;

export const HandoffCodeParam = z.object({
	code: createStringType().describe('The handoff code'),
});

export type HandoffCodeParam = z.infer<typeof HandoffCodeParam>;

export const HandoffCompleteResponse = z.object({
	return_url: z.string().describe('Deep link that returns the sign-in to the initiating app, with its one-time grant'),
});

export type HandoffCompleteResponse = z.infer<typeof HandoffCompleteResponse>;

export const HandoffStatusRequest = z.object({
	poll_secret: createStringType().describe('The poll secret issued when the handoff was initiated'),
	grant: createStringType(1, 128).optional().describe('The one-time grant delivered to the app through the deep link'),
});

export type HandoffStatusRequest = z.infer<typeof HandoffStatusRequest>;

export const HandoffCancelRequest = z.object({
	poll_secret: createStringType().describe('The poll secret issued when the handoff was initiated'),
});

export type HandoffCancelRequest = z.infer<typeof HandoffCancelRequest>;

export const EnableMfaTotpRequest = z
	.object({
		secret: createStringType(1, 256).describe('The TOTP secret key'),
		code: createStringType(1, 32).describe('The TOTP verification code'),
	})
	.extend(SudoVerificationSchema.shape);

export type EnableMfaTotpRequest = z.infer<typeof EnableMfaTotpRequest>;

export const DisableTotpRequest = z
	.object({
		code: createStringType(1, 32).describe('The TOTP code to verify'),
		password: PasswordType.optional().describe('Account password for verification'),
	})
	.extend(SudoVerificationSchema.shape);

export type DisableTotpRequest = z.infer<typeof DisableTotpRequest>;

export const MfaBackupCodesRequest = z
	.object({
		regenerate: z.boolean().describe('Whether to regenerate backup codes'),
		password: PasswordType.optional().describe('Account password for verification'),
	})
	.extend(SudoVerificationSchema.shape);

export type MfaBackupCodesRequest = z.infer<typeof MfaBackupCodesRequest>;

const MfaBackupCodeResponse = z.object({
	code: z.string().describe('The backup code'),
	consumed: z.boolean().describe('Whether the code has been used'),
});

export const MfaBackupCodesResponse = z.object({
	backup_codes: z.array(MfaBackupCodeResponse).describe('List of backup codes'),
});

export type MfaBackupCodesResponse = z.infer<typeof MfaBackupCodesResponse>;

export const MfaBackupCodesChallengeStartResponse = z.object({
	ticket: z.string().describe('Ticket for backup codes challenge actions'),
	code_expires_at: z.string().describe('ISO8601 timestamp when the verification code expires'),
	resend_available_at: z.string().describe('ISO8601 timestamp when the code can be resent'),
});

export type MfaBackupCodesChallengeStartResponse = z.infer<typeof MfaBackupCodesChallengeStartResponse>;

export const MfaBackupCodesChallengeResendRequest = z.object({
	ticket: createStringType().describe('Backup codes challenge ticket identifier'),
});

export type MfaBackupCodesChallengeResendRequest = z.infer<typeof MfaBackupCodesChallengeResendRequest>;

export const MfaBackupCodesChallengeVerifyRequest = MfaBackupCodesChallengeResendRequest.extend({
	code: createStringType().describe('Verification code sent to the email address'),
});

export type MfaBackupCodesChallengeVerifyRequest = z.infer<typeof MfaBackupCodesChallengeVerifyRequest>;

export const MfaBackupCodesChallengeVerifyResponse = MfaBackupCodesResponse.extend({
	verification_proof: z.string().describe('Proof token authorizing backup code regeneration on this ticket'),
});

export type MfaBackupCodesChallengeVerifyResponse = z.infer<typeof MfaBackupCodesChallengeVerifyResponse>;

export const MfaBackupCodesChallengeRegenerateRequest = MfaBackupCodesChallengeResendRequest.extend({
	verification_proof: createStringType().describe('Proof token obtained from verifying the email code'),
});

export type MfaBackupCodesChallengeRegenerateRequest = z.infer<typeof MfaBackupCodesChallengeRegenerateRequest>;

export const WebAuthnCredentialResponse = z.object({
	id: z.string().describe('The credential ID'),
	name: z.string().describe('User-assigned name for the credential'),
	created_at: z.string().describe('When the credential was registered'),
	last_used_at: z.string().nullable().describe('When the credential was last used'),
	rp_id: z.string().describe('Relying party ID the passkey belongs to'),
});

export type WebAuthnCredentialResponse = z.infer<typeof WebAuthnCredentialResponse>;

export const WebAuthnCredentialListResponse = z.array(WebAuthnCredentialResponse);

export type WebAuthnCredentialListResponse = z.infer<typeof WebAuthnCredentialListResponse>;

export const WebAuthnChallengeResponse = z.looseObject({
	challenge: z.string().describe('The WebAuthn challenge'),
});

export type WebAuthnChallengeResponse = z.infer<typeof WebAuthnChallengeResponse>;

export const WebAuthnRegisterRequest = z.object({
	response: WebAuthnRegistrationResponse.describe('WebAuthn registration response'),
	challenge: createStringType(1, 1024).describe('The challenge from registration options'),
	name: createStringType(1, 100).describe('User-assigned name for the credential'),
});

export type WebAuthnRegisterRequest = z.infer<typeof WebAuthnRegisterRequest>;

export const WebAuthnCredentialUpdateRequest = z
	.object({
		name: createStringType(1, 100).describe('New name for the credential'),
	})
	.extend(SudoVerificationSchema.shape);

export type WebAuthnCredentialUpdateRequest = z.infer<typeof WebAuthnCredentialUpdateRequest>;

export const WebAuthnTwoFactorRequest = z
	.object({
		enabled: z.boolean().describe('Whether registered passkeys count as a second factor when logging in'),
	})
	.extend(SudoVerificationSchema.shape);

export type WebAuthnTwoFactorRequest = z.infer<typeof WebAuthnTwoFactorRequest>;

export const WebAuthnTwoFactorResponse = z.object({
	user: UserPrivateResponse.describe('The updated account'),
	backup_codes: z
		.array(MfaBackupCodeResponse)
		.nullable()
		.describe('Backup codes minted by this call, or null when none were minted'),
});

export type WebAuthnTwoFactorResponse = z.infer<typeof WebAuthnTwoFactorResponse>;

export const SudoMfaMethodsResponse = z.object({
	totp: z.boolean().describe('Whether TOTP is enabled'),
	webauthn: z.boolean().describe('Whether the account has at least one registered WebAuthn credential'),
	backup_codes: z.boolean().describe('Whether the account has at least one unconsumed backup code'),
	has_mfa: z.boolean().describe('Whether the account can satisfy a sudo mode challenge'),
	email_code: z
		.boolean()
		.optional()
		.describe('Whether a code sent to the confirmed email address can verify the account, for accounts without MFA'),
	password: z.boolean().optional().describe('Whether the account password can verify the account'),
});

export type SudoMfaMethodsResponse = z.infer<typeof SudoMfaMethodsResponse>;

export const LogoutAuthSessionsWithVerificationRequest = LogoutAuthSessionsRequest.extend(SudoVerificationSchema.shape);

const DeviceProofType = createStringType(1, 128).describe('device_proof from an earlier sign-in on this device');

export const IdentifyRequest = z.object({
	email: EmailType.optional().describe(
		'Email address to sign in or sign up with, on instances that sign in with an email',
	),
	login: UsernameType.optional().describe('Username to sign in or sign up with, on username instances'),
	device_proof: DeviceProofType.optional(),
	registration_url_code: createStringType(1, 128)
		.nullish()
		.describe('Admin-issued registration URL code, for sign-ups'),
});

export type IdentifyRequest = z.infer<typeof IdentifyRequest>;

export const IdentifyResponse = z.object({
	ticket: z.string().describe('Opaque ticket for the next step, valid for 15 minutes'),
	account: z.enum(['existing', 'new']).describe('Whether an account already uses this address'),
	sign_in_method: z
		.enum(['password', 'code'])
		.nullable()
		.describe(
			'How the existing account signs in: password for an account that has a password, code for one without. Null when account is new',
		),
	registration: z
		.object({
			mode: z.enum(['open', 'approval', 'closed']).describe('How new accounts are admitted'),
			consent_required: z.boolean().describe('Whether sign-up needs agreement to the terms and privacy policy'),
			requires_password: z.boolean().describe('Whether sign-up needs a password because email codes are off'),
			instant_account_availability: InstantAccountAvailabilitySchema.optional().describe(
				'Whether an account can be created from just a display name, taking the registration URL code into account',
			),
		})
		.nullable()
		.describe('Sign-up details, present when account is new'),
});

export type IdentifyResponse = z.infer<typeof IdentifyResponse>;

export const EmailCodeSendRequest = z.object({
	ticket: createStringType(1, 128).describe('Ticket from POST /auth/identify'),
	registration_url_code: createStringType(1, 128)
		.nullish()
		.describe('Admin-issued registration URL code, for sign-ups'),
});

export type EmailCodeSendRequest = z.infer<typeof EmailCodeSendRequest>;

export const EmailCodeSendResponse = z.object({
	purpose: z.enum(['sign_in', 'sign_up']).describe('Whether the code signs in or creates an account'),
	code_expires_at: z.iso.datetime().describe('When the emailed code stops working'),
	resend_available_at: z.iso.datetime().describe('When another code can be requested'),
});

export type EmailCodeSendResponse = z.infer<typeof EmailCodeSendResponse>;

export const EmailCodeVerifyRequest = z.object({
	ticket: createStringType(1, 128).describe('Ticket from POST /auth/identify'),
	code: SixDigitCodeType.describe('The 6-digit code from the email'),
	consent: z
		.boolean()
		.optional()
		.describe(
			'For sign-ups, whether the person submitted the step that says creating the account accepts the terms of service. Must be true when the instance publishes terms or a privacy policy',
		),
	registration_url_code: createStringType(1, 128)
		.nullish()
		.describe('Admin-issued registration URL code, for sign-ups'),
	invite_code: createStringType(0, 256).nullish().describe('Invite to open after the date of birth step, for sign-ups'),
	username: UsernameType.optional().describe('For sign-ups, the username for the new account. Ignored when signing in'),
	global_name: GlobalNameType.optional().describe(
		'For sign-ups, the display name shown to other people. Ignored when signing in',
	),
});

export type EmailCodeVerifyRequest = z.infer<typeof EmailCodeVerifyRequest>;

export const EmailCodeVerifyResponse = z.union([
	AuthRegisterSuccessResponse,
	AuthMfaRequiredResponse,
	AuthRegistrationPendingApprovalResponse,
]);

export type EmailCodeVerifyResponse = z.infer<typeof EmailCodeVerifyResponse>;

export const AccountHandoffRequest = z.object({
	global_name: GlobalNameType.describe(
		'Display name for the new account. The username is derived from it and given a tag on the server',
	),
	nonce_hash: z
		.string()
		.regex(/^[0-9a-f]{64}$/u)
		.describe('Hex SHA-256 of the nonce the browser keeps until redeeming'),
	locale: z.string().min(2).max(16).optional().describe('Locale of the page the account was created from'),
	registration_url_code: createStringType(1, 128)
		.nullish()
		.describe('Admin-issued registration URL code, for sign-ups'),
});

export type AccountHandoffRequest = z.infer<typeof AccountHandoffRequest>;

export const AccountHandoffResponse = z.object({
	handoff_code: z.string().describe('Single-use code to redeem in the app within 15 minutes'),
});

export type AccountHandoffResponse = z.infer<typeof AccountHandoffResponse>;

export const AccountHandoffRedeemRequest = z.object({
	handoff_code: z
		.string()
		.regex(/^[A-Za-z0-9_-]{43}$/u)
		.describe('Code from POST /auth/register/handoff'),
	nonce: z
		.string()
		.regex(/^[A-Za-z0-9_-]{16,256}$/u)
		.describe('The nonce whose hash was sent with the handoff'),
	consent: z
		.boolean()
		.optional()
		.describe(
			'Whether the person submitted the step that says creating the account accepts the terms of service. Must be true when the instance publishes terms or a privacy policy',
		),
	global_name: GlobalNameType.optional().describe(
		'Display name for the new account, when the person changed it in the app. Defaults to the one sent with the handoff',
	),
});

export type AccountHandoffRedeemRequest = z.infer<typeof AccountHandoffRedeemRequest>;

export const CaptchaChallengeResponse = z.object({
	captcha_provider: CaptchaProviderSchema.describe('Captcha the next request must solve'),
	altcha_challenge: z.record(z.string(), z.unknown()).optional().describe('ALTCHA challenge to solve'),
});

export type CaptchaChallengeResponse = z.infer<typeof CaptchaChallengeResponse>;