Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

10.6 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { redis } from "@carbon/kv";
import {
  generateAuthenticationOptions,
  generateRegistrationOptions,
  verifyAuthenticationResponse,
  verifyRegistrationResponse,
  type WebAuthnCredential
} from "@simplewebauthn/server";
import type {
  AuthenticationResponseJSON,
  AuthenticatorTransportFuture,
  RegistrationResponseJSON
} from "@simplewebauthn/types";
import { DOMAIN, ERP_URL, MES_URL, VERCEL_URL } from "../config/env";

// ── RP (Relying Party) configuration ────────────────────────────────────────
//
// The Relying Party is our application. WebAuthn binds passkeys to the RP_ID
// so a passkey registered on "app.carbon.ms" cannot be used on a different domain.
//
// Rules:
//  - RP_ID must be a bare hostname — no protocol, no port.
//  - RP_ID must be an exact match OR a registrable suffix of the page origin.
//    e.g. origin "https://app.carbon.ms" → valid RP_IDs: "app.carbon.ms" or "carbon.ms"
//  - ORIGIN must be the full URL the browser reports (window.location.origin),
//    including protocol and port. Used server-side to verify the attestation origin.

/** The Relying Party identifier — bare hostname, no port. Exported so routes can store it. */
export const RP_ID =
  DOMAIN && !DOMAIN.startsWith("localhost") ? DOMAIN : "localhost";

/** The expected origin(s) sent by the browser during registration/authentication.
 *  Both ERP and MES subdomains share the same RP_ID (the parent DOMAIN), so a
 *  passkey registered on either app works on both — but @simplewebauthn checks
 *  origin exactly, so we pass an array of allowed origins. */
const ORIGIN: string | string[] =
  DOMAIN && !DOMAIN.startsWith("localhost")
    ? [`https://${DOMAIN}`, ERP_URL, MES_URL].filter(
        (url, idx, arr) => !!url && arr.indexOf(url) === idx
      )
    : VERCEL_URL?.startsWith("http")
      ? VERCEL_URL
      : "http://localhost:3000";

const CHALLENGE_TTL_SECONDS = 300; // 5 minutes

// ── Challenge storage in Redis ───────────────────────────────────────────────
//
// Challenges are one-time random strings generated by the server and sent to
// the browser. The browser signs them (along with other data) with the passkey
// private key. The server then verifies the signature against the stored
// challenge to prevent replay attacks.
//
// Challenges are stored in Redis with a 5-minute TTL and deleted immediately
// after the first use (get-and-delete pattern).

function regChallengeKey(userId: string) {
  return `passkey:reg:challenge:${userId}`;
}

function authChallengeKey(challengeId: string) {
  return `passkey:auth:challenge:${challengeId}`;
}

/** Store a registration challenge for the given user. Overwrites any existing one. */
export async function storeRegistrationChallenge(
  userId: string,
  challenge: string
): Promise<void> {
  await redis.set(
    regChallengeKey(userId),
    challenge,
    "EX",
    CHALLENGE_TTL_SECONDS
  );
}

/**
 * Retrieve and immediately delete the registration challenge for a user.
 * Returns null if not found or expired — the caller should treat this as an error.
 * Also returns null (never throws) when Redis is down: @carbon/kv fails soft, so
 * the passkey flow rejects rather than crashing. See verifyPasskeyRegistration.
 */
export async function getAndDeleteRegistrationChallenge(
  userId: string
): Promise<string | null> {
  return redis.getdel(regChallengeKey(userId));
}

/** Store an authentication challenge keyed by a random challengeId (not userId,
 *  since we don't know who the user is yet at this point in the auth flow). */
export async function storeAuthChallenge(
  challengeId: string,
  challenge: string
): Promise<void> {
  await redis.set(
    authChallengeKey(challengeId),
    challenge,
    "EX",
    CHALLENGE_TTL_SECONDS
  );
}

/**
 * Retrieve and immediately delete the authentication challenge.
 * Returns null if not found or expired. Also returns null (never throws) when
 * Redis is down: @carbon/kv fails soft, so the passkey flow rejects rather than
 * crashing. See verifyPasskeyAuthentication.
 */
export async function getAndDeleteAuthChallenge(
  challengeId: string
): Promise<string | null> {
  return redis.getdel(authChallengeKey(challengeId));
}

// ── Registration ─────────────────────────────────────────────────────────────

/**
 * Generate PublicKeyCredentialCreationOptions to send to the browser.
 *
 * Key decisions:
 * - attestationType "none": we don't need device attestation (reduces friction).
 * - authenticatorAttachment "platform": device-bound authenticators only
 *   (Touch ID, Face ID, Windows Hello). Excludes USB security keys.
 * - requireResidentKey true: the passkey is stored on the device (discoverable),
 *   so the user doesn't need to type their email before using it.
 * - excludeCredentials: prevents the same device registering twice for this user.
 */
export async function getPasskeyRegistrationOptions(
  userId: string,
  userEmail: string,
  userDisplayName: string,
  existingCredentialIds: string[]
) {
  const options = await generateRegistrationOptions({
    rpName: "Carbon",
    rpID: RP_ID,
    userName: userEmail,
    userDisplayName: userDisplayName || userEmail,
    userID: new Uint8Array(
      new TextEncoder().encode(userId)
    ) as unknown as Uint8Array<ArrayBuffer>,
    attestationType: "none",
    excludeCredentials: existingCredentialIds.map((id) => ({
      id,
      type: "public-key"
    })),
    authenticatorSelection: {
      authenticatorAttachment: "platform",
      requireResidentKey: true,
      residentKey: "required",
      userVerification: "required"
    },
    // -7 = ECDSA P-256, -257 = RSA PKCS#1 v1.5 SHA-256
    supportedAlgorithmIDs: [-7, -257]
  });

  await storeRegistrationChallenge(userId, options.challenge);

  return options;
}

/**
 * Verify the registration response from the browser and extract the credential
 * data to persist in the database.
 *
 * Throws if the challenge is missing/expired or if verification fails.
 */
export async function verifyPasskeyRegistration(
  userId: string,
  response: RegistrationResponseJSON
) {
  const challenge = await getAndDeleteRegistrationChallenge(userId);
  if (!challenge)
    throw new Error("Registration challenge not found or expired");

  const verification = await verifyRegistrationResponse({
    response,
    expectedChallenge: challenge,
    expectedOrigin: ORIGIN,
    expectedRPID: RP_ID,
    requireUserVerification: true
  });

  if (!verification.verified || !verification.registrationInfo) {
    throw new Error("Registration verification failed");
  }

  const { credential, aaguid, credentialDeviceType, credentialBackedUp } =
    verification.registrationInfo;

  const userHandle = Buffer.from(new TextEncoder().encode(userId)).toString(
    "base64url"
  );

  return {
    id: credential.id,
    publicKey: credential.publicKey,
    counter: credential.counter,
    transports:
      (response.response.transports as AuthenticatorTransportFuture[]) || null,
    deviceType: credentialDeviceType,
    backedUp: credentialBackedUp,
    aaguid: aaguid || "",
    credentialName: getCredentialName(aaguid),
    userHandle,
    rpId: RP_ID
  };
}

// ── Authentication ───────────────────────────────────────────────────────────

/**
 * Generate PublicKeyCredentialRequestOptions to send to the browser.
 *
 * allowCredentials is intentionally empty — this triggers "discoverable credential"
 * mode, where the browser shows a picker of all passkeys the user has for this RP,
 * without requiring them to type their email first.
 *
 * The challengeId is a random ID we generate and send alongside the options so
 * the verify endpoint can retrieve the right challenge from Redis.
 */
export async function getPasskeyAuthenticationOptions(challengeId: string) {
  const options = await generateAuthenticationOptions({
    rpID: RP_ID,
    allowCredentials: [],
    userVerification: "required"
  });

  await storeAuthChallenge(challengeId, options.challenge);

  return options;
}

/**
 * Verify the authentication response from the browser.
 * Returns the new counter value so the caller can update the DB.
 * Throws if the challenge is missing/expired or verification fails.
 */
export async function verifyPasskeyAuthentication(
  challengeId: string,
  response: AuthenticationResponseJSON,
  credential: WebAuthnCredential
) {
  const challenge = await getAndDeleteAuthChallenge(challengeId);
  if (!challenge)
    throw new Error("Authentication challenge not found or expired");

  const verification = await verifyAuthenticationResponse({
    response,
    expectedChallenge: challenge,
    expectedOrigin: ORIGIN,
    expectedRPID: RP_ID,
    requireUserVerification: true,
    credential: {
      id: credential.id,
      publicKey: credential.publicKey,
      counter: credential.counter,
      transports: credential.transports || undefined
    }
  });

  if (!verification.verified) {
    throw new Error("Authentication verification failed");
  }

  return {
    newCounter: verification.authenticationInfo.newCounter
  };
}

// ── AAGUID → provider name ───────────────────────────────────────────────────
//
// AAGUID (Authenticator Attestation GUID) is a UUID that identifies the make
// and model of the authenticator. We use it to display a friendly name like
// "iCloud Keychain" instead of a raw credential ID.
//
// Source: https://passkeydeveloper.github.io/passkey-authenticator-aaguids/

const AAGUID_NAMES: Record<string, string> = {
  "ea9b8d66-4d01-1d21-3ce4-b6b48cb575d4": "Google Password Manager",
  "adce0002-35bc-c60a-648b-0b25f1f05503": "Chrome on Mac",
  "fbfc3007-154e-4ecc-8c0b-6e020557d7bd": "iCloud Keychain",
  "08987058-cadc-4b81-b6e1-30de50dcbe96": "Windows Hello"
  // "b93fd961-f2e6-462f-b122-82002247de78": "Android Fingerprint",
  // "6d44ba9b-f6ec-2e49-b930-0c8fe920cb73": "Chrome on Android",
  // "17290f1e-c212-34d0-1423-365d729f09d9": "Chrome on iPhone",
  // "f8a011f3-8c0a-4d15-8006-17111f9edc7d": "Security Key"
};

export function getCredentialName(aaguid?: string): string {
  if (!aaguid) return "Passkey";
  return AAGUID_NAMES[aaguid] || "Passkey";
}