~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
159 lines · 5.9 KB Raw History
// The browser's WebAuthn (spec/PASSKEYS.md): its options taken from the
// JSON form the server gives, and its credentials given back in the JSON
// form `toJSON()` makes, byte strings as base64url without padding. Where
// the browser lacks `parse…FromJSON()` or `toJSON()`, the same is done here,
// with each member the browser can give.

// Whether the browser has WebAuthn at all.
export const hasWebAuthn: boolean = 'PublicKeyCredential' in window && !!window.PublicKeyCredential;

// A credential as `toJSON()` gives it, to send as it is.
export type CredentialJSON = Record<string, unknown>;

function encode(bytes: ArrayBuffer): string {
	let binary = '';
	for (const b of new Uint8Array(bytes)) binary += String.fromCharCode(b);
	return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

function decode(text: string): ArrayBuffer {
	const base64 = text.replace(/-/g, '+').replace(/_/g, '/');
	const binary = atob(base64 + '='.repeat((4 - (base64.length % 4)) % 4));
	const bytes = new Uint8Array(binary.length);
	for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
	return bytes.buffer;
}

function descriptors(
	list: PublicKeyCredentialDescriptorJSON[] | undefined
): PublicKeyCredentialDescriptor[] | undefined {
	return list?.map((d) => ({
		type: 'public-key',
		id: decode(d.id),
		...(d.transports ? { transports: d.transports as AuthenticatorTransport[] } : {})
	}));
}

function creationOptions(json: PublicKeyCredentialCreationOptionsJSON): PublicKeyCredentialCreationOptions {
	if (typeof PublicKeyCredential.parseCreationOptionsFromJSON === 'function')
		return PublicKeyCredential.parseCreationOptionsFromJSON(json);
	// The JSON form's strings are the enums' values; its byte strings are decoded.
	const plain = json as unknown as PublicKeyCredentialCreationOptions;
	return {
		...plain,
		challenge: decode(json.challenge),
		user: { ...json.user, id: decode(json.user.id) },
		excludeCredentials: descriptors(json.excludeCredentials)
	};
}

function requestOptions(json: PublicKeyCredentialRequestOptionsJSON): PublicKeyCredentialRequestOptions {
	if (typeof PublicKeyCredential.parseRequestOptionsFromJSON === 'function')
		return PublicKeyCredential.parseRequestOptionsFromJSON(json);
	// The JSON form's strings are the enums' values; its byte strings are decoded.
	const plain = json as unknown as PublicKeyCredentialRequestOptions;
	return {
		...plain,
		challenge: decode(json.challenge),
		allowCredentials: descriptors(json.allowCredentials)
	};
}

// What `toJSON()` gives of the members both kinds of credential have.
function common(c: PublicKeyCredential): CredentialJSON {
	return {
		id: c.id,
		rawId: encode(c.rawId),
		type: c.type,
		clientExtensionResults: c.getClientExtensionResults(),
		...(c.authenticatorAttachment ? { authenticatorAttachment: c.authenticatorAttachment } : {})
	};
}

function registrationJSON(c: PublicKeyCredential): CredentialJSON {
	if (typeof c.toJSON === 'function') return { ...c.toJSON() };
	const r = c.response as AuthenticatorAttestationResponse;
	const key = typeof r.getPublicKey === 'function' ? r.getPublicKey() : null;
	return {
		...common(c),
		response: {
			clientDataJSON: encode(r.clientDataJSON),
			attestationObject: encode(r.attestationObject),
			transports: typeof r.getTransports === 'function' ? r.getTransports() : [],
			...(typeof r.getAuthenticatorData === 'function'
				? { authenticatorData: encode(r.getAuthenticatorData()) }
				: {}),
			...(typeof r.getPublicKeyAlgorithm === 'function'
				? { publicKeyAlgorithm: r.getPublicKeyAlgorithm() }
				: {}),
			...(key ? { publicKey: encode(key) } : {})
		}
	};
}

function authenticationJSON(c: PublicKeyCredential): CredentialJSON {
	if (typeof c.toJSON === 'function') return { ...c.toJSON() };
	const r = c.response as AuthenticatorAssertionResponse;
	return {
		...common(c),
		response: {
			clientDataJSON: encode(r.clientDataJSON),
			authenticatorData: encode(r.authenticatorData),
			signature: encode(r.signature),
			...(r.userHandle ? { userHandle: encode(r.userHandle) } : {})
		}
	};
}

// A credential of WebAuthn's, by its type: a password manager's own may be
// no instance of the browser's class.
const isPublicKey = (c: Credential | null): c is PublicKeyCredential => c?.type === 'public-key';

// What asking the browser to make a passkey gave: the credential, or why
// none was made: `exists` when the device already has one of the account's
// (`InvalidStateError`), `none` for any other failure.
export type Made =
	| { kind: 'made'; credential: CredentialJSON }
	| { kind: 'exists' }
	| { kind: 'none' };

export async function makePasskey(options: PublicKeyCredentialCreationOptionsJSON): Promise<Made> {
	try {
		const c = await navigator.credentials.create({ publicKey: creationOptions(options) });
		if (!isPublicKey(c)) return { kind: 'none' };
		return { kind: 'made', credential: registrationJSON(c) };
	} catch (e) {
		return e instanceof DOMException && e.name === 'InvalidStateError'
			? { kind: 'exists' }
			: { kind: 'none' };
	}
}

// Ask the browser for a passkey to sign in with: its credential, or null
// when it gave none. `conditional` waits on the identifier field's autofill
// rather than asking at once; `signal` ends the asking.
export async function usePasskey(
	options: PublicKeyCredentialRequestOptionsJSON,
	conditional = false,
	signal?: AbortSignal
): Promise<CredentialJSON | null> {
	try {
		const c = await navigator.credentials.get({
			publicKey: requestOptions(options),
			...(conditional ? { mediation: 'conditional' as CredentialMediationRequirement } : {}),
			signal
		});
		return isPublicKey(c) ? authenticationJSON(c) : null;
	} catch {
		return null;
	}
}

// Whether the browser offers passkeys in a field's autofill.
export async function hasPasskeyAutofill(): Promise<boolean> {
	try {
		return hasWebAuthn && (await PublicKeyCredential.isConditionalMediationAvailable?.()) === true;
	} catch {
		return false;
	}
}