Skip to content

Instantly share code, notes, and snippets.

@ncornwell
Created January 22, 2024 16:49
Show Gist options
  • Save ncornwell/0db52b3eeea1fb818e0b15dc8e5598d6 to your computer and use it in GitHub Desktop.
Save ncornwell/0db52b3eeea1fb818e0b15dc8e5598d6 to your computer and use it in GitHub Desktop.
Credential Addition
import { DfnsApiClient } from '@dfns/sdk'
import { WebAuthn } from '@dfns/sdk-webauthn'
import { CreateUserCredentialRequest } from '@dfns/sdk/codegen/Auth'
import { CreateUserCredentialFido2Input, CredentialKind } from '@dfns/sdk/codegen/datamodel/Auth'
import { fromBase64Url, toBase64Url } from '@dfns/sdk/utils'
import dotenv from 'dotenv'
const main = async () => {
dotenv.config()
const signer = new WebAuthn({ rpId: process.env.DFNS_APP_RPID! })
// Need User Login token
const dfnsApi = new DfnsApiClient({
appId: process.env.DFNS_APP_ID!,
authToken: localStorage.getItem('DFNS_AUTH_TOKEN') ?? undefined,
baseUrl: process.env.DFNS_API_URL!,
signer,
})
const newCredentialChallenge = await dfnsApi.auth.createUserCredentialChallenge({ body: { kind: CredentialKind.Fido2 } })
if (newCredentialChallenge.kind === CredentialKind.Fido2) {
const webAuthnChallenge: CredentialCreationOptions = {
publicKey: {
challenge: Buffer.from(newCredentialChallenge.challenge),
pubKeyCredParams: newCredentialChallenge.pubKeyCredParams.map((cred) => ({
alg: cred.alg,
type: 'public-key'
})),
rp: {
name: newCredentialChallenge.rp.name,
id: newCredentialChallenge.rp.id,
},
user: {
displayName: newCredentialChallenge.user.displayName,
id: Buffer.from(newCredentialChallenge.user.id),
name: newCredentialChallenge.user.name,
},
attestation: 'direct',
excludeCredentials: newCredentialChallenge.excludeCredentials.map((cred) => ({
id: fromBase64Url(cred.id),
type: 'public-key'
})),
authenticatorSelection: newCredentialChallenge.authenticatorSelection as AuthenticatorSelectionCriteria,
timeout: 60000,
},
}
const credential = await navigator.credentials.create(webAuthnChallenge) as PublicKeyCredential
const signedChallenge = credential.response as AuthenticatorAssertionResponse
const newCredential: CreateUserCredentialFido2Input = {
credentialKind: CredentialKind.Fido2,
credentialInfo: {
credId: credential.id,
clientData: toBase64Url(Buffer.from(signedChallenge.clientDataJSON)),
attestationData: toBase64Url(Buffer.from(signedChallenge.signature)),
},
challengeIdentifier: newCredentialChallenge.temporaryAuthenticationToken,
credentialName: 'My new credential',
}
const newRequest: CreateUserCredentialRequest = {
body: newCredential,
}
const newCredentialInfo = await dfnsApi.auth.createUserCredential(newRequest)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment