Skip to content

Commit

Permalink
✨ webauthn: serialize android response
Browse files Browse the repository at this point in the history
  • Loading branch information
cruzdanilo committed Nov 14, 2023
1 parent 40f9c4e commit 3a97784
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import androidx.credentials.CredentialManager
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetPasswordOption
import androidx.credentials.GetPublicKeyCredentialOption
import androidx.credentials.PublicKeyCredential
import expo.modules.kotlin.exception.Exceptions
import expo.modules.kotlin.functions.Coroutine
import expo.modules.kotlin.modules.Module
Expand All @@ -22,10 +23,10 @@ class ExpoWebauthn : Module() {

AsyncFunction("get") Coroutine { requestJSON: String ->
val activity = appContext.currentActivity ?: throw Exceptions.MissingActivity()
CredentialManager.create(activity).getCredential(
(CredentialManager.create(activity).getCredential(
activity,
GetCredentialRequest(listOf(GetPublicKeyCredentialOption(requestJSON), GetPasswordOption()))
)
).credential as PublicKeyCredential).authenticationResponseJson
}
}
}
25 changes: 21 additions & 4 deletions webauthn/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { encode } from "base64-arraybuffer";
import { encode, decode } from "base64-arraybuffer";

import ExpoWebauthn from "./ExpoWebauthn";

// @ts-expect-error -- polyfill
global.navigator.credentials ??= {
get(options) {
async get(options) {
if (!options?.publicKey) throw new Error("publicKey required");
return ExpoWebauthn.get(stringify(options.publicKey));
return parse(await ExpoWebauthn.get(stringify(options.publicKey)));
},
async create(options) {
if (!options?.publicKey) throw new Error("publicKey required");
return ExpoWebauthn.create(stringify(options.publicKey));
return parse(await ExpoWebauthn.create(stringify(options.publicKey)));
},
} as CredentialsContainer;

Expand All @@ -22,3 +22,20 @@ function stringify(value: unknown) {
return v as unknown;
});
}

function parse(text: string) {
return JSON.parse(text, (key, v) => {
if (
typeof v === "string" &&
(key === "rawId" ||
key === "signature" ||
key === "userHandle" ||
key === "clientDataJSON" ||
key === "authenticatorData" ||
key === "clientExtensionResults")
) {
return decode(v.replace(/-/g, "+").replace(/_/g, "/"));
}
return v as unknown;
}) as PublicKeyCredential;
}

0 comments on commit 3a97784

Please sign in to comment.