staging-tester / ocean-landing-serve / src/ lib/ live/ webauthn.ts

// Bridges the server's WebAuthn options (webauthn-rs JSON: binary fields as base64url, absent ones as null) and
// navigator.credentials, which takes and returns ArrayBuffers.

const toBytes = (value: string): ArrayBuffer => {
	const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
	const raw = atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '='));
	const bytes = new Uint8Array(raw.length);
	for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
	return bytes.buffer;
};

const toText = (buffer: ArrayBuffer | null): string | null => {
	if (!buffer) return null;
	let raw = '';
	for (const byte of new Uint8Array(buffer)) raw += String.fromCharCode(byte);
	return btoa(raw).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};

type Descriptor = { id: string; type: 'public-key'; transports?: AuthenticatorTransport[] | null };

const descriptors = (list: Descriptor[] | null | undefined): PublicKeyCredentialDescriptor[] =>
	(list ?? []).map((c) => ({ id: toBytes(c.id), type: c.type, ...(c.transports ? { transports: c.transports } : {}) }));

export type CreationOptions = {
	publicKey: {
		rp: PublicKeyCredentialRpEntity;
		user: { id: string; name: string; displayName: string };
		challenge: string;
		pubKeyCredParams: PublicKeyCredentialParameters[];
		timeout?: number | null;
		excludeCredentials?: Descriptor[] | null;
		authenticatorSelection?: AuthenticatorSelectionCriteria | null;
		attestation?: AttestationConveyancePreference | null;
		extensions?: AuthenticationExtensionsClientInputs | null;
	};
};

export type RequestOptions = {
	publicKey: {
		challenge: string;
		timeout?: number | null;
		rpId?: string | null;
		allowCredentials?: Descriptor[] | null;
		userVerification?: UserVerificationRequirement | null;
		extensions?: AuthenticationExtensionsClientInputs | null;
	};
	mediation?: string | null;
};

export const passkeysSupported = () => typeof window !== 'undefined' && 'PublicKeyCredential' in window && !!navigator.credentials;

export async function createCredential(options: CreationOptions) {
	const pk = options.publicKey;
	const publicKey: PublicKeyCredentialCreationOptions = {
		rp: pk.rp,
		user: { ...pk.user, id: toBytes(pk.user.id) },
		challenge: toBytes(pk.challenge),
		pubKeyCredParams: pk.pubKeyCredParams,
		excludeCredentials: descriptors(pk.excludeCredentials),
		...(pk.timeout ? { timeout: pk.timeout } : {}),
		...(pk.authenticatorSelection ? { authenticatorSelection: pk.authenticatorSelection } : {}),
		...(pk.attestation ? { attestation: pk.attestation } : {}),
		...(pk.extensions ? { extensions: pk.extensions } : {})
	};
	const credential = await navigator.credentials.create({ publicKey });
	if (!(credential instanceof PublicKeyCredential) || !(credential.response instanceof AuthenticatorAttestationResponse)) throw new Error('No passkey was created.');
	const response = credential.response;
	return {
		id: credential.id,
		rawId: toText(credential.rawId),
		type: credential.type,
		response: {
			attestationObject: toText(response.attestationObject),
			clientDataJSON: toText(response.clientDataJSON),
			transports: response.getTransports()
		},
		extensions: {}
	};
}

export async function getAssertion(options: RequestOptions) {
	const pk = options.publicKey;
	const publicKey: PublicKeyCredentialRequestOptions = {
		challenge: toBytes(pk.challenge),
		allowCredentials: descriptors(pk.allowCredentials),
		...(pk.timeout ? { timeout: pk.timeout } : {}),
		...(pk.rpId ? { rpId: pk.rpId } : {}),
		...(pk.userVerification ? { userVerification: pk.userVerification } : {}),
		...(pk.extensions ? { extensions: pk.extensions } : {})
	};
	const credential = await navigator.credentials.get({ publicKey });
	if (!(credential instanceof PublicKeyCredential) || !(credential.response instanceof AuthenticatorAssertionResponse)) throw new Error('No passkey answered.');
	const response = credential.response;
	return {
		id: credential.id,
		rawId: toText(credential.rawId),
		type: credential.type,
		response: {
			authenticatorData: toText(response.authenticatorData),
			clientDataJSON: toText(response.clientDataJSON),
			signature: toText(response.signature),
			userHandle: toText(response.userHandle)
		},
		extensions: {}
	};
}