aboutsummaryrefslogtreecommitdiffstats
path: root/lib/passkey.ts
blob: 2875e388b4ad428748c0769dc9da66ff03387149 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888 } /* Comment */
.highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */
.highlight .k { color: #080; font-weight: bold } /* Keyword */
.highlight .ch { color: #888 } /* Comment.Hashbang */
.highlight .cm { color: #888 } /* Comment.Multiline */
.highlight .cp { color: #C00; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888 } /* Comment.Single */
.highlight .cs { color: #C00; font-weight: bold; background-color: #FFF0F0 } /* Comment.Special */
.highlight .gd { color: #000; background-color: #FDD } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #A00 } /* Generic.Error */
.highlight .gh { color: #333 } /* Generic.Heading */
.highlight .gi { color: #000; background-color: #DFD } /* Generic.Inserted */
.highlight .go { color: #888 } /* Generic.Output */
.highlight .gp { color: #555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666 } /* Generic.Subheading */
.highlight .gt { color: #A00 } /* Generic.Traceback */
.highlight .kc { color: #080; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #080; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #080; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #080 } /* Keyword.Pseudo */
.highlight .kr { color: #080; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #00D; font-weight: bold } /* Literal.Number */
.highlight .s { color: #D20; background-color: #FFF0F0 } /* Literal.String */
.highlight .na { color: #369 } /* Name.Attribute */
.highlight .nb { color: #038 } /* Name.Builtin */
.highlight .nc { color: #B06; font-weight: bold } /* Name.Class */
.highlight .no { color: #036; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555 } /* Name.Decorator */
.highlight .ne { color: #B06; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #06B; font-weight: bold } /* Name.Function */
.highlight .nl { color: #369; font-style: italic } /* Name.Label */
.highlight .nn { color: #B06; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #369; font-weight: bold } /* Name.Property */
.highlight .nt { color: #B06; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #369 } /* Name.Variable */
.highlight .ow { color: #080 } /* Operator.Word */
.highlight .w { color: #BBB } /* Text.Whitespace */
.highlight .mb { color: #00D; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #00D; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #00D; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #00D; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #00D; font-weight: bold } /* Literal.Number.Oct */
.highlight .
import {
  generateRegistrationOptions,
  verifyRegistrationResponse,
  generateAuthenticationOptions,
  verifyAuthenticationResponse,
} from "@simplewebauthn/server";
// @ts-ignore
import type { AuthenticatorTransportFuture } from "@simplewebauthn/types";
import { db, g, s } from "$lib/db";
import { fail } from "$lib/utils";
import { v4 } from "uuid";

const rpName = "coinos";
const androidOrigin =
  "android:apk-key-hash:DaYNHto1fsy7jrhOfRaDDy4HCRNqFo8H0gf3DmW7bOw";

function getRpID(origin: string) {
  try {
    return new URL(origin).hostname;
  } catch {
    return "localhost";
  }
}

function getExpectedOrigins(origin: string) {
  return [origin, androidOrigin];
}

export async function generatePasskeyRegistration(user: any, origin: string) {
  const rpID = getRpID(origin);
  const passkeys = user.passkeys || [];

  const options = await generateRegistrationOptions({
    rpName,
    rpID,
    userName: user.username,
    userID: new TextEncoder().encode(user.id) as any,
    attestationType: "none",
    excludeCredentials: passkeys.map((p: any) => ({
      id: p.credentialID,
      transports: p.transports as AuthenticatorTransportFuture[],
    })),
    authenticatorSelection: {
      residentKey: "required",
      userVerification: "preferred",
    },
  });

  await db.set(`challenge:${user.id}`, options.challenge, { EX: 300 });

  return options;
}

export async function verifyPasskeyRegistration(user: any, response: any, origin: string) {
  const rpID = getRpID(origin);
  const expectedChallenge = await db.get(`challenge:${user.id}`);
  if (!expectedChallenge) fail("Challenge expired");

  const verification = await verifyRegistrationResponse({
    response,
    expectedChallenge: expectedChallenge as string,
    expectedOrigin: getExpectedOrigins(origin),
    expectedRPID: rpID,
  });

  if (!verification.verified || !verification.registrationInfo) {
    fail("Passkey verification failed");
  }

  await db.del(`challenge:${user.id}`);

  const { credential } = verification.registrationInfo;

  const cred = {
    credentialID: credential.id,
    credentialPublicKey: Buffer.from(credential.publicKey).toString("base64url"),
    counter: credential.counter,
    transports: response.response.transports || [],
    createdAt: Date.now(),
  };

  await db.set(`passkey:${credential.id}`, user.id);

  return cred;
}

export async function generatePasskeyLogin(origin: string) {
  const rpID = getRpID(origin);

  const options = await generateAuthenticationOptions({
    rpID,
    userVerification: "preferred",
  });

  const challengeId = v4();
  await db.set(`challenge:passkey:${challengeId}`, options.challenge, { EX: 300 });

  return { ...options, challengeId };
}

export async function verifyPasskeyLogin(response: any, challengeId: string, origin: string) {
  const rpID = getRpID(origin);
  const userId = await db.get(`passkey:${response.id}`);
  if (!userId) fail("Passkey not recognized");

  const user = await g(`user:${userId}`);
  if (!user) fail("User not found");

  const passkeys = user.passkeys || [];
  const passkey = passkeys.find((p: any) => p.credentialID === response.id);
  if (!passkey) fail("Passkey not found");

  const expectedChallenge = await db.get(`challenge:passkey:${challengeId}`);
  if (!expectedChallenge) fail("Challenge expired");

  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge: expectedChallenge as string,
    expectedOrigin: getExpectedOrigins(origin),
    expectedRPID: rpID,
    requireUserVerification: false,
    credential: {
      id: passkey.credentialID,
      publicKey: Buffer.from(passkey.credentialPublicKey, "base64url") as any,
      counter: passkey.counter,
      transports: passkey.transports as AuthenticatorTransportFuture[],
    } as any,
  });

  if (!verification.verified) fail("Passkey authentication failed");

  await db.del(`challenge:passkey:${challengeId}`);

  passkey.counter = verification.authenticationInfo.newCounter;
  await s(`user:${user.id}`, user);

  return user;
}