garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/passkey.ts

raw

/**
 * The admin passkey (src/admin.rs): made once on the person's phone, its public
 * half installed by them as root; afterwards each admin window is a grant this
 * passkey signs. The hub only carries the signature; root checks it.
 */

const KEY_LABEL = 'midas-admin-key-v1'

export const b64url = (b: ArrayBuffer | Uint8Array): string => {
    const bytes = b instanceof Uint8Array ? b : new Uint8Array(b)
    let s = ''
    for (const x of bytes) s += String.fromCharCode(x)
    return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}

export const fromB64url = (s: string): Uint8Array<ArrayBuffer> => {
    const t = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4))
    const out = new Uint8Array(new ArrayBuffer(t.length))
    for (let i = 0; i < t.length; i++) out[i] = t.charCodeAt(i)
    return out
}

/** Whether this browser can use a passkey here: WebAuthn, on the page's own host. */
export function passkeyHere(rpId: string): string | null {
    if (!window.PublicKeyCredential || !navigator.credentials) return 'this browser has no passkeys'
    if (location.hostname !== rpId && !location.hostname.endsWith(`.${rpId}`)) return `open the page on https://${rpId} for its passkey`
    return null
}

/** Make the passkey: its line, for `sudo midas hub admin-enroll '<line>'`. */
export async function makeKey(rpId: string, label: string, existing: string[]): Promise<string> {
    const cred = (await navigator.credentials.create({
        publicKey: {
            rp: {id: rpId, name: 'midas admin'},
            user: {id: crypto.getRandomValues(new Uint8Array(16)), name: 'midas admin', displayName: 'midas admin'},
            challenge: crypto.getRandomValues(new Uint8Array(32)),
            // ES256 only: what root checks (P-256).
            pubKeyCredParams: [{type: 'public-key', alg: -7}],
            authenticatorSelection: {userVerification: 'required', residentKey: 'preferred'},
            excludeCredentials: existing.map((id) => ({type: 'public-key' as const, id: fromB64url(id)})),
            attestation: 'none',
        },
    })) as PublicKeyCredential | null
    if (!cred) throw new Error('no passkey was made')
    const r = cred.response as AuthenticatorAttestationResponse
    if (r.getPublicKeyAlgorithm() !== -7) throw new Error('this passkey is not P-256 (ES256), which the machine checks')
    const spki = r.getPublicKey()
    if (!spki) throw new Error('the browser did not give the public key')
    const name = label.trim().replace(/\s+/g, ' ') || 'phone'
    return `${KEY_LABEL} ${b64url(cred.rawId)} ${b64url(spki)} ${name}`
}

export interface Assertion {
    credential_id: string
    authenticator_data: string
    client_data_json: string
    signature: string
}

/** Sign a grant's challenge with the passkey: the fingerprint or PIN is asked for. */
export async function signGrant(challenge: string, rpId: string, keys: string[]): Promise<Assertion> {
    const cred = (await navigator.credentials.get({
        publicKey: {
            rpId,
            challenge: fromB64url(challenge),
            allowCredentials: keys.map((id) => ({type: 'public-key' as const, id: fromB64url(id)})),
            userVerification: 'required',
            timeout: 120000,
        },
    })) as PublicKeyCredential | null
    if (!cred) throw new Error('nothing was signed')
    const r = cred.response as AuthenticatorAssertionResponse
    return {
        credential_id: b64url(cred.rawId),
        authenticator_data: b64url(r.authenticatorData),
        client_data_json: b64url(r.clientDataJSON),
        signature: b64url(r.signature),
    }
}