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.

chore: update passkey handling and dependencies

naveenkashcd977e2c4e78
diff --git a/apps/erp/app/routes/api+/passkey.authenticate.verify.ts b/apps/erp/app/routes/api+/passkey.authenticate.verify.ts
index d7e029f949..3fc78ed937 100644
--- a/apps/erp/app/routes/api+/passkey.authenticate.verify.ts
+++ b/apps/erp/app/routes/api+/passkey.authenticate.verify.ts
@@ -2,11 +2,9 @@ import { assertIsPost, error } from "@carbon/auth";
import { signInWithPasskey } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { setCompanyId } from "@carbon/auth/company.server";
-import {
- type StoredCredential,
- verifyPasskeyAuthentication
-} from "@carbon/auth/passkey.server";
+import { verifyPasskeyAuthentication } from "@carbon/auth/passkey.server";
import { setAuthSession } from "@carbon/auth/session.server";
+import type { WebAuthnCredential } from "@simplewebauthn/browser";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import { path } from "~/utils/path";
@@ -50,14 +48,11 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const storedCredential: StoredCredential = {
+ const storedCredential: WebAuthnCredential = {
id: credRow.id,
- userId: credRow.userId,
- publicKey: Buffer.from(credRow.publicKey, "base64"),
+ publicKey: new Uint8Array(Buffer.from(credRow.publicKey, "base64url")),
counter: credRow.counter,
- transports: credRow.transports ?? null,
- aaguid: "",
- credentialName: ""
+ transports: credRow.transports ?? null
};
try {
@@ -67,13 +62,27 @@ export async function action({ request }: ActionFunctionArgs) {
storedCredential
);
- // Update counter + lastUsedAt (fire-and-forget)
- void (serviceRole as any)
+ const returnedHandle = webAuthnResponse.response?.userHandle;
+ if (returnedHandle) {
+ const expectedHandle = Buffer.from(
+ new TextEncoder().encode(credRow.userId)
+ ).toString("base64url");
+ if (returnedHandle !== expectedHandle) {
+ return data(error(null, "userHandle mismatch"), { status: 401 });
+ }
+ }
+
+ const { error: counterError } = await (serviceRole as any)
.from("passkeyCredential")
.update({ counter: newCounter, lastUsedAt: new Date().toISOString() })
.eq("id", credRow.id);
- // Resolve user email for session creation
+ if (counterError) {
+ return data(error(null, "Failed to persist credential state"), {
+ status: 500
+ });
+ }
+
const { data: authUser } = await serviceRole.auth.admin.getUserById(
credRow.userId
);
@@ -81,7 +90,6 @@ export async function action({ request }: ActionFunctionArgs) {
return data(error(null, "User not found"), { status: 404 });
}
- // Create Supabase session via service role
const authSession = await signInWithPasskey(
credRow.userId,
authUser.user.email
@@ -93,7 +101,12 @@ export async function action({ request }: ActionFunctionArgs) {
const sessionCookie = await setAuthSession(request, { authSession });
const companyIdCookie = setCompanyId(authSession.companyId);
- return redirect(redirectTo ?? path.to.authenticatedRoot, {
+ const safeRedirect =
+ redirectTo && redirectTo.startsWith("/") && !redirectTo.startsWith("//")
+ ? redirectTo
+ : path.to.authenticatedRoot;
+
+ return redirect(safeRedirect, {
headers: [
["Set-Cookie", sessionCookie],
["Set-Cookie", companyIdCookie]
diff --git a/apps/erp/app/routes/api+/passkey.register.verify.ts b/apps/erp/app/routes/api+/passkey.register.verify.ts
index 7f00b9689a..1213651d09 100644
--- a/apps/erp/app/routes/api+/passkey.register.verify.ts
+++ b/apps/erp/app/routes/api+/passkey.register.verify.ts
@@ -33,7 +33,7 @@ export async function action({ request }: ActionFunctionArgs) {
.insert({
id: credential.id,
userId,
- publicKey: Buffer.from(credential.publicKey).toString("base64"),
+ publicKey: Buffer.from(credential.publicKey).toString("base64url"),
counter: credential.counter,
transports: credential.transports ?? [],
deviceType: credential.deviceType,
diff --git a/apps/erp/app/routes/x+/account+/profile.tsx b/apps/erp/app/routes/x+/account+/profile.tsx
index 164f1b4b7d..9b32d61991 100644
--- a/apps/erp/app/routes/x+/account+/profile.tsx
+++ b/apps/erp/app/routes/x+/account+/profile.tsx
@@ -59,7 +59,6 @@ type Passkey = {
export async function loader({ request }: LoaderFunctionArgs) {
const { client, userId } = await requirePermissions(request, {});
const serviceRole = getCarbonServiceRole();
-
const [user, passkeysResult] = await Promise.all([
getAccount(client, userId),
(serviceRole as any)
@@ -174,6 +173,11 @@ export async function action({ request }: ActionFunctionArgs) {
if (!credentialId || !credentialName) {
return data(error(null, "Missing fields"), { status: 400 });
}
+ if (credentialName.length > 100) {
+ return data(error(null, "Passkey name must be 100 characters or fewer"), {
+ status: 400
+ });
+ }
const serviceRole = getCarbonServiceRole();
const { error: dbError } = await (serviceRole as any)
diff --git a/packages/auth/package.json b/packages/auth/package.json
index 3d5c1c982b..84fceaebe8 100644
--- a/packages/auth/package.json
+++ b/packages/auth/package.json
@@ -2,6 +2,7 @@
"name": "@carbon/auth",
"devDependencies": {
"@carbon/config": "*",
+ "@simplewebauthn/types": "^12.0.0",
"@carbon/utils": "*",
"@types/react": "^18.2.74",
"tsup": "^8.5.1",
diff --git a/packages/auth/src/services/passkey.server.ts b/packages/auth/src/services/passkey.server.ts
index e4f70dcf63..9472efe392 100644
--- a/packages/auth/src/services/passkey.server.ts
+++ b/packages/auth/src/services/passkey.server.ts
@@ -1,53 +1,10 @@
-/**
- * passkey.server.ts
- *
- * Server-side WebAuthn / Passkey implementation using @simplewebauthn/server.
- *
- * WebAuthn flow overview:
- *
- * REGISTRATION (adding a passkey to an existing account)
- * ┌─────────┐ ┌────────────┐ ┌──────────────┐
- * │ Browser │ │ Our Server │ │ Supabase DB │
- * └────┬────┘ └─────┬──────┘ └──────┬───────┘
- * │ POST /register/options │ │
- * │──────────────────>│ │ │
- * │ │ generateRegistrationOptions() │
- * │ │ store challenge in Redis │
- * │<──────────────────│ return options │ │
- * │ navigator.credentials.create(opts) │ │
- * │ (Touch ID / Face ID / PIN) │ │
- * │ POST /register/verify │ │
- * │──────────────────>│ │ │
- * │ │ verifyRegistrationResponse() │
- * │ │────────────────────────────> │
- * │ │ INSERT credential │
- * │<──────────────────│ { success }│ │
- *
- * AUTHENTICATION (signing in with a passkey)
- * ┌─────────┐ ┌────────────┐ ┌──────────────┐
- * │ Browser │ │ Our Server │ │ Supabase DB │
- * └────┬────┘ └─────┬──────┘ └──────┬───────┘
- * │ POST /authenticate/options │ │
- * │──────────────────>│ │ │
- * │ │ generateAuthenticationOptions()
- * │ │ store challenge in Redis │
- * │<──────────────────│ { options, challengeId } │
- * │ navigator.credentials.get(opts) │ │
- * │ (browser shows passkey picker) │ │
- * │ POST /authenticate/verify │ │
- * │──────────────────>│ │ │
- * │ │ lookup credential by id ────> │
- * │ │ verifyAuthenticationResponse()│
- * │ │ signInWithPasskey(userId) │
- * │<──────────────────│ Set-Cookie (session) │
- */
-
import { redis } from "@carbon/kv";
import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
- verifyRegistrationResponse
+ verifyRegistrationResponse,
+ type WebAuthnCredential
} from "@simplewebauthn/server";
import type {
AuthenticationResponseJSON,
@@ -80,29 +37,8 @@ const ORIGIN =
? VERCEL_URL
: "http://localhost:3000";
-/** How long a challenge lives in Redis before it expires. */
const CHALLENGE_TTL_SECONDS = 300; // 5 minutes
-// ── Types ────────────────────────────────────────────────────────────────────
-
-/**
- * The subset of a passkeyCredential DB row needed to verify an authentication
- * response. Loaded from the database and passed to verifyPasskeyAuthentication.
- */
-export type StoredCredential = {
- /** base64url-encoded credential ID, used to look up the credential. */
- id: string;
- userId: string;
- /** COSE-encoded public key bytes (stored as base64 TEXT in the DB). */
- publicKey: Uint8Array;
- /** Signature counter — incremented by the authenticator on every use. */
- counter: number;
- /** Transport hints (usb, nfc, ble, internal…) used to optimise future allow lists. */
- transports: AuthenticatorTransportFuture[] | null;
- aaguid: string;
- credentialName: string;
-};
-
// ── Challenge storage in Redis ───────────────────────────────────────────────
//
// Challenges are one-time random strings generated by the server and sent to
@@ -137,13 +73,12 @@ export async function storeRegistrationChallenge(
/**
* 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.
+ *
*/
export async function getAndDeleteRegistrationChallenge(
userId: string
): Promise<string | null> {
- const challenge = await redis.get(regChallengeKey(userId));
- if (challenge) await redis.del(regChallengeKey(userId));
- return challenge;
+ return redis.getdel(regChallengeKey(userId));
}
/** Store an authentication challenge keyed by a random challengeId (not userId,
@@ -163,13 +98,12 @@ export async function storeAuthChallenge(
/**
* Retrieve and immediately delete the authentication challenge.
* Returns null if not found or expired.
+ *
*/
export async function getAndDeleteAuthChallenge(
challengeId: string
): Promise<string | null> {
- const challenge = await redis.get(authChallengeKey(challengeId));
- if (challenge) await redis.del(authChallengeKey(challengeId));
- return challenge;
+ return redis.getdel(authChallengeKey(challengeId));
}
// ── Registration ─────────────────────────────────────────────────────────────
@@ -196,8 +130,6 @@ export async function getPasskeyRegistrationOptions(
rpID: RP_ID,
userName: userEmail,
userDisplayName: userDisplayName || userEmail,
- // userID is stored by the authenticator as the "user handle" and echoed back
- // during authentication — we use it to look up the user without needing their email.
userID: new TextEncoder().encode(userId),
attestationType: "none",
excludeCredentials: existingCredentialIds.map((id) => ({
@@ -214,7 +146,6 @@ export async function getPasskeyRegistrationOptions(
supportedAlgorithmIDs: [-7, -257]
});
- // Persist the challenge so we can verify it when the browser responds.
await storeRegistrationChallenge(userId, options.challenge);
return options;
@@ -230,7 +161,6 @@ export async function verifyPasskeyRegistration(
userId: string,
response: RegistrationResponseJSON
) {
- // Consume the challenge — it's single-use.
const challenge = await getAndDeleteRegistrationChallenge(userId);
if (!challenge)
throw new Error("Registration challenge not found or expired");
@@ -244,7 +174,6 @@ export async function verifyPasskeyRegistration(
// hard-fail if the device skipped it (e.g. no biometrics enrolled).
requireUserVerification: false
});
- console.log(verification, "--verification--");
if (!verification.verified || !verification.registrationInfo) {
throw new Error("Registration verification failed");
@@ -253,11 +182,9 @@ export async function verifyPasskeyRegistration(
const { credential, aaguid, credentialDeviceType, credentialBackedUp } =
verification.registrationInfo;
- // The user handle is the userId bytes we encoded into options.userID.
- // Some authenticators echo it back in response.userHandle; if not, we
- // re-derive it from the userId so it's always stored consistently.
- const userHandle =
- response.response.userHandle ?? new TextEncoder().encode(userId);
+ const userHandle = Buffer.from(new TextEncoder().encode(userId)).toString(
+ "base64url"
+ );
return {
id: credential.id,
@@ -306,7 +233,7 @@ export async function getPasskeyAuthenticationOptions(challengeId: string) {
export async function verifyPasskeyAuthentication(
challengeId: string,
response: AuthenticationResponseJSON,
- credential: StoredCredential
+ credential: WebAuthnCredential
) {
const challenge = await getAndDeleteAuthChallenge(challengeId);
if (!challenge)
@@ -331,7 +258,6 @@ export async function verifyPasskeyAuthentication(
}
return {
- /** Updated counter — persist this to the DB to detect cloned authenticators. */
newCounter: verification.authenticationInfo.newCounter
};
}