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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: add passkey authentication support
naveenkashbad037953b00
diff --git a/.env.example b/.env.exampleindex 4a57642c76..18c92a2e1d 100644--- a/.env.example+++ b/.env.example@@ -1,4 +1,4 @@-AUTH_PROVIDERS="email,google" # "email" | "google" | "azure"+AUTH_PROVIDERS="email,google,passkey" # "email" | "google" | "azure" | "passkey"CARBON_EDITION="community" # "community" | "cloud" | "enterprise"CLOUDFLARE_TURNSTILE_SITE_KEY="1x00000000000000000000AA"@@ -52,4 +52,4 @@ OPENAI_API_KEY="sk-proj-*****************"GOOGLE_PLACES_API_KEY="*******************"-RATE_LIMIT="5"\ No newline at end of file+RATE_LIMIT="5"diff --git a/apps/erp/app/routes/_public+/login.tsx b/apps/erp/app/routes/_public+/login.tsxindex 30f2719f7e..1dd72a2ec0 100644--- a/apps/erp/app/routes/_public+/login.tsx+++ b/apps/erp/app/routes/_public+/login.tsx@@ -1,5 +1,4 @@import {- AUTH_PROVIDERS,assertIsPost,CarbonEdition,CLOUDFLARE_TURNSTILE_SECRET_KEY,@@ -7,6 +6,7 @@ import {CONTROLLED_ENVIRONMENT,carbonClient,error,+ isAuthProviderEnabled,magicLinkValidator,RATE_LIMIT} from "@carbon/auth";@@ -61,10 +61,14 @@ export async function loader({ request }: LoaderFunctionArgs) {throw redirect(path.to.authenticatedRoot);}- const providers = AUTH_PROVIDERS.split(",");+ const hasOutlookAuth = isAuthProviderEnabled("azure");+ const hasGoogleAuth = isAuthProviderEnabled("google");+ const hasPasskeyAuth = isAuthProviderEnabled("passkey");return {- providers+ hasOutlookAuth,+ hasGoogleAuth,+ hasPasskeyAuth};}@@ -160,9 +164,8 @@ export async function action({ request }: ActionFunctionArgs) {}export default function LoginRoute() {- const { providers } = useLoaderData<typeof loader>();- const hasOutlookAuth = providers.includes("azure");- const hasGoogleAuth = providers.includes("google");+ const { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth } =+ useLoaderData<typeof loader>();const [searchParams] = useSearchParams();const redirectTo = searchParams.get("redirectTo") ?? undefined;@@ -196,6 +199,7 @@ export default function LoginRoute() {// Detect passkey support and start conditional UI (autofill) on mountuseMount(() => {+ if (!hasPasskeyAuth) return;if (!browserSupportsWebAuthn()) return;const checkAndStart = async () => {@@ -384,25 +388,6 @@ export default function LoginRoute() {</Alert>)}- {passkeySupported && (- <Button- type="button"- size="lg"- className="w-full"- onClick={onSignInWithPasskey}- isDisabled={passkeyLoading || fetcher.state !== "idle"}- isLoading={passkeyLoading}- variant="secondary"- leftIcon={<LuFingerprint className="size-4" />}- >- Sign in with Passkey- </Button>- )}- {passkeySupported && (hasGoogleAuth || hasOutlookAuth) && (- <div className="py-1 w-full">- <Separator />- </div>- )}{hasGoogleAuth && (<Buttontype="button"@@ -436,11 +421,26 @@ export default function LoginRoute() {</div>)}+ {hasPasskeyAuth && passkeySupported && (+ <Button+ type="button"+ size="lg"+ className="w-full"+ onClick={onSignInWithPasskey}+ isDisabled={passkeyLoading || fetcher.state !== "idle"}+ isLoading={passkeyLoading}+ variant="secondary"+ leftIcon={<LuFingerprint className="size-4" />}+ >+ Sign in with Passkey+ </Button>+ )}+<Inputname="email"label=""placeholder="Email Address"- autoComplete="email webauthn"+ autoComplete={hasPasskeyAuth ? "email webauthn" : "email"}/><Submitdiff --git a/apps/erp/app/routes/api+/passkey.authenticate.options.ts b/apps/erp/app/routes/api+/passkey.authenticate.options.tsindex 6447e4e32f..fb0874aa11 100644--- a/apps/erp/app/routes/api+/passkey.authenticate.options.ts+++ b/apps/erp/app/routes/api+/passkey.authenticate.options.ts@@ -1,4 +1,4 @@-import { assertIsPost } from "@carbon/auth";+import { assertIsPost, error, isAuthProviderEnabled } from "@carbon/auth";import { getPasskeyAuthenticationOptions } from "@carbon/auth/passkey.server";import { nanoid } from "nanoid";import type { ActionFunctionArgs } from "react-router";@@ -7,6 +7,10 @@ import { data } from "react-router";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);+ if (!isAuthProviderEnabled("passkey")) {+ return data(error(null, "Passkeys are disabled"), { status: 404 });+ }+const challengeId = nanoid();const options = await getPasskeyAuthenticationOptions(challengeId);diff --git a/apps/erp/app/routes/api+/passkey.authenticate.verify.ts b/apps/erp/app/routes/api+/passkey.authenticate.verify.tsindex 3fc78ed937..442033bac4 100644--- a/apps/erp/app/routes/api+/passkey.authenticate.verify.ts+++ b/apps/erp/app/routes/api+/passkey.authenticate.verify.ts@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, isAuthProviderEnabled } from "@carbon/auth";import { signInWithPasskey } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { setCompanyId } from "@carbon/auth/company.server";@@ -12,6 +12,10 @@ import { path } from "~/utils/path";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);+ if (!isAuthProviderEnabled("passkey")) {+ return data(error(null, "Passkeys are disabled"), { status: 404 });+ }+let body: { credential: any; challengeId: string; redirectTo?: string };try {body = await request.json();diff --git a/apps/erp/app/routes/api+/passkey.register.options.ts b/apps/erp/app/routes/api+/passkey.register.options.tsindex e81ee2ed72..82ac925323 100644--- a/apps/erp/app/routes/api+/passkey.register.options.ts+++ b/apps/erp/app/routes/api+/passkey.register.options.ts@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, isAuthProviderEnabled } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getPasskeyRegistrationOptions } from "@carbon/auth/passkey.server";@@ -8,6 +8,10 @@ import { data } from "react-router";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);+ if (!isAuthProviderEnabled("passkey")) {+ return data(error(null, "Passkeys are disabled"), { status: 404 });+ }+const { userId, email } = await requirePermissions(request, {});const serviceRole = getCarbonServiceRole();diff --git a/apps/erp/app/routes/api+/passkey.register.verify.ts b/apps/erp/app/routes/api+/passkey.register.verify.tsindex 1213651d09..25dfd58e12 100644--- a/apps/erp/app/routes/api+/passkey.register.verify.ts+++ b/apps/erp/app/routes/api+/passkey.register.verify.ts@@ -1,4 +1,4 @@-import { assertIsPost, error } from "@carbon/auth";+import { assertIsPost, error, isAuthProviderEnabled } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { verifyPasskeyRegistration } from "@carbon/auth/passkey.server";@@ -8,6 +8,10 @@ import { data } from "react-router";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);+ if (!isAuthProviderEnabled("passkey")) {+ return data(error(null, "Passkeys are disabled"), { status: 404 });+ }+const { userId } = await requirePermissions(request, {});let body: any;diff --git a/apps/erp/app/routes/x+/account+/profile.tsx b/apps/erp/app/routes/x+/account+/profile.tsxindex 799646d913..6eb88e9885 100644--- a/apps/erp/app/routes/x+/account+/profile.tsx+++ b/apps/erp/app/routes/x+/account+/profile.tsx@@ -1,4 +1,9 @@-import { assertIsPost, error, success } from "@carbon/auth";+import {+ assertIsPost,+ error,+ isAuthProviderEnabled,+ success+} from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";@@ -204,17 +209,25 @@ export default function AccountProfile() {const deleteFetcher = useFetcher();const renameFetcher = useFetcher();const { revalidate } = useRevalidator();+ const passkeysEnabled = isAuthProviderEnabled("passkey");const [registering, setRegistering] = useState(false);const [selectedPasskey, setSelectedPasskey] = useState<Passkey | null>(null);const [editedName, setEditedName] = useState("");const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);+ console.log({ passkeysEnabled });const onAddPasskey = async () => {+ if (!passkeysEnabled) {+ toast.error("Passkeys are disabled");+ return;+ }setRegistering(true);try {const optRes = await fetch("/api/passkey/register/options", {method: "POST"});+ console.log(optRes, "--optRes--");+if (!optRes.ok) throw new Error("Failed to get options");const options = await optRes.json();@@ -295,87 +308,99 @@ export default function AccountProfile() {</CardContent></Card>- <Card>- <CardHeader>- <HStack className="justify-between">- <div>- <CardTitle>Passkeys</CardTitle>- <CardDescription>- Sign in with biometrics instead of a magic link. Passkeys are- secured by Face ID, Touch ID, or your device PIN.- </CardDescription>- </div>- <Button- type="button"- variant="secondary"- onClick={onAddPasskey}- isDisabled={registering}- isLoading={registering}- leftIcon={<LuFingerprint className="size-4" />}- >- Add Passkey- </Button>- </HStack>- </CardHeader>- <CardContent>- {passkeys.length === 0 ? (- <p className="text-sm text-muted-foreground">- No passkeys registered yet.- </p>- ) : (- <HStack spacing={2}>- {passkeys.map((pk) => (- <HStack- key={pk.id}- className="justify-between p-3 rounded-md border border-border space-x-4 cursor-pointer hover:bg-muted/40 transition-colors"- onClick={() => openPasskeyDrawer(pk)}+ {passkeysEnabled && (+ <Card>+ <CardHeader>+ <HStack className="justify-between">+ <div>+ <CardTitle>Passkeys</CardTitle>+ <CardDescription>+ Sign in with biometrics instead of a magic link. Passkeys are+ secured by Face ID, Touch ID, or your device PIN.+ {!passkeysEnabled && (+ <span> Passkeys are currently disabled.</span>+ )}+ </CardDescription>+ </div>+ {passkeysEnabled && (+ <Button+ type="button"+ variant="secondary"+ onClick={onAddPasskey}+ isDisabled={registering}+ isLoading={registering}+ leftIcon={<LuFingerprint className="size-4" />}>- <HStack spacing={3} className="items-start">- <LuFingerprint className="size-4 text-muted-foreground shrink-0 mt-1" />- <VStack spacing={0}>- <p className="text-sm font-medium">{pk.credentialName}</p>- <p className="text-xs text-muted-foreground">- Added{" "}- {new Date(pk.createdAt).toLocaleDateString(undefined, {- year: "numeric",- month: "short",- day: "numeric"- })}- {pk.lastUsedAt && (- <>- {" · "}Last used{" "}- {new Date(pk.lastUsedAt).toLocaleDateString(- undefined,- {- year: "numeric",- month: "short",- day: "numeric"- }- )}- </>- )}- {pk.backedUp && " · Synced"}- </p>- </VStack>- </HStack>-- <IconButton- onClick={(e) => {- e.stopPropagation();- setConfirmDeleteId(pk.id);- }}- aria-label="Delete passkey"- type="button"- variant="ghost"- icon={<LuTrash2 />}- className="cursor-pointer"- />- </HStack>- ))}+ Add Passkey+ </Button>+ )}</HStack>- )}- </CardContent>- </Card>+ </CardHeader>+ <CardContent>+ {passkeys.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ No passkeys registered yet.+ </p>+ ) : (+ <HStack spacing={2}>+ {passkeys.map((pk) => (+ <HStack+ key={pk.id}+ className="justify-between p-3 rounded-md border border-border space-x-4 cursor-pointer hover:bg-muted/40 transition-colors"+ onClick={() => openPasskeyDrawer(pk)}+ >+ <HStack spacing={3} className="items-start">+ <LuFingerprint className="size-4 text-muted-foreground shrink-0 mt-1" />+ <VStack spacing={0}>+ <p className="text-sm font-medium">+ {pk.credentialName}+ </p>+ <p className="text-xs text-muted-foreground">+ Added{" "}+ {new Date(pk.createdAt).toLocaleDateString(+ undefined,+ {+ year: "numeric",+ month: "short",+ day: "numeric"+ }+ )}+ {pk.lastUsedAt && (+ <>+ {" · "}Last used{" "}+ {new Date(pk.lastUsedAt).toLocaleDateString(+ undefined,+ {+ year: "numeric",+ month: "short",+ day: "numeric"+ }+ )}+ </>+ )}+ {pk.backedUp && " · Synced"}+ </p>+ </VStack>+ </HStack>++ <IconButton+ onClick={(e) => {+ e.stopPropagation();+ setConfirmDeleteId(pk.id);+ }}+ aria-label="Delete passkey"+ type="button"+ variant="ghost"+ icon={<LuTrash2 />}+ className="cursor-pointer"+ />+ </HStack>+ ))}+ </HStack>+ )}+ </CardContent>+ </Card>+ )}{/* Edit passkey modal */}<Modaldiff --git a/apps/mes/app/routes/_public+/login.tsx b/apps/mes/app/routes/_public+/login.tsxindex d1484c66c1..9157b4a3ac 100644--- a/apps/mes/app/routes/_public+/login.tsx+++ b/apps/mes/app/routes/_public+/login.tsx@@ -1,10 +1,10 @@import {- AUTH_PROVIDERS,assertIsPost,CarbonEdition,CONTROLLED_ENVIRONMENT,carbonClient,error,+ isAuthProviderEnabled,magicLinkValidator,RATE_LIMIT} from "@carbon/auth";@@ -21,11 +21,17 @@ import {Heading,Separator,toast,+ useMount,VStack} from "@carbon/react";import { ItarLoginDisclaimer } from "@carbon/remix";import { Edition } from "@carbon/utils";-import { LuCircleAlert } from "react-icons/lu";+import {+ browserSupportsWebAuthn,+ startAuthentication+} from "@simplewebauthn/browser";+import { useRef, useState } from "react";+import { LuCircleAlert, LuFingerprint } from "react-icons/lu";import type {ActionFunctionArgs,LoaderFunctionArgs,@@ -51,10 +57,14 @@ export async function loader({ request }: LoaderFunctionArgs) {throw redirect(path.to.authenticatedRoot);}- const providers = AUTH_PROVIDERS.split(",");+ const hasOutlookAuth = isAuthProviderEnabled("azure");+ const hasGoogleAuth = isAuthProviderEnabled("google");+ const hasPasskeyAuth = isAuthProviderEnabled("passkey");return {- providers+ hasOutlookAuth,+ hasGoogleAuth,+ hasPasskeyAuth};}@@ -107,9 +117,8 @@ export async function action({ request }: ActionFunctionArgs) {}export default function LoginRoute() {- const { providers } = useLoaderData<typeof loader>();- const hasOutlookAuth = providers.includes("azure");- const hasGoogleAuth = providers.includes("google");+ const { hasOutlookAuth, hasGoogleAuth, hasPasskeyAuth } =+ useLoaderData<typeof loader>();const [searchParams] = useSearchParams();const redirectTo = searchParams.get("redirectTo") ?? undefined;@@ -118,6 +127,109 @@ export default function LoginRoute() {{ success: true } | { success: false; message: string }>();+ const [passkeySupported, setPasskeySupported] = useState(false);+ const [passkeyLoading, setPasskeyLoading] = useState(false);+ const conditionalAbortRef = useRef<AbortController | null>(null);++ // Detect passkey support and start conditional UI (autofill) on mount+ useMount(() => {+ if (!hasPasskeyAuth) return;+ if (!browserSupportsWebAuthn()) return;++ const checkAndStart = async () => {+ const conditionalSupported =+ typeof PublicKeyCredential !== "undefined" &&+ typeof (PublicKeyCredential as any).isConditionalMediationAvailable ===+ "function" &&+ (await (PublicKeyCredential as any).isConditionalMediationAvailable());++ setPasskeySupported(true);++ if (!conditionalSupported) return;++ try {+ const optRes = await fetch("/api/passkey/authenticate/options", {+ method: "POST"+ });+ if (!optRes.ok) return;+ const { challengeId, ...options } = await optRes.json();++ const abortCtrl = new AbortController();+ conditionalAbortRef.current = abortCtrl;++ const credential = await startAuthentication({+ optionsJSON: options,+ useBrowserAutofill: true,+ signal: abortCtrl.signal+ } as any);++ await completePasskeyAuth(credential, challengeId);+ } catch {+ // User dismissed or no passkeys — silently ignore+ }+ };++ checkAndStart();++ return () => {+ conditionalAbortRef.current?.abort();+ };+ });++ const completePasskeyAuth = async (credential: any, challengeId: string) => {+ const verifyRes = await fetch("/api/passkey/authenticate/verify", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ credential, challengeId, redirectTo })+ });++ if (verifyRes.redirected) {+ window.location.href = verifyRes.url;+ return;+ }++ if (!verifyRes.ok) {+ const body = await verifyRes.json().catch(() => ({}));+ if (verifyRes.status === 404 && body.unknownCredential) {+ if (+ typeof (PublicKeyCredential as any).signalUnknownCredential ===+ "function"+ ) {+ await (PublicKeyCredential as any).signalUnknownCredential({+ rpId: window.location.hostname,+ credentialId: body.credentialId+ });+ }+ }+ toast.error(body.message ?? "Passkey sign-in failed");+ }+ };++ const onSignInWithPasskey = async () => {+ if (!passkeySupported) return;+ setPasskeyLoading(true);+ conditionalAbortRef.current?.abort();++ try {+ const optRes = await fetch("/api/passkey/authenticate/options", {+ method: "POST"+ });+ if (!optRes.ok) throw new Error("Failed to get options");+ const { challengeId, ...options } = await optRes.json();++ const credential = await startAuthentication({+ optionsJSON: options+ } as any);+ await completePasskeyAuth(credential, challengeId);+ } catch (e: any) {+ if (e?.name !== "NotAllowedError" && e?.name !== "AbortError") {+ toast.error("Passkey sign-in failed");+ }+ } finally {+ setPasskeyLoading(false);+ }+ };+const onSignInWithGoogle = async () => {const { error } = await carbonClient.auth.signInWithOAuth({provider: "google",@@ -217,8 +329,26 @@ export default function LoginRoute() {<Separator /></div>)}-- <Input name="email" label="" placeholder="Email Address" />+ {hasPasskeyAuth && passkeySupported && (+ <Button+ type="button"+ size="lg"+ className="w-full"+ onClick={onSignInWithPasskey}+ isDisabled={passkeyLoading || fetcher.state !== "idle"}+ isLoading={passkeyLoading}+ variant="secondary"+ leftIcon={<LuFingerprint className="size-4" />}+ >+ Sign in with Passkey+ </Button>+ )}+ <Input+ name="email"+ label=""+ placeholder="Email Address"+ autoComplete={hasPasskeyAuth ? "email webauthn" : "email"}+ /><SubmitisDisabled={fetcher.state !== "idle"}diff --git a/packages/auth/src/config/env.ts b/packages/auth/src/config/env.tsindex 5085c45b88..5479419847 100644--- a/packages/auth/src/config/env.ts+++ b/packages/auth/src/config/env.ts@@ -105,11 +105,18 @@ export function getEnv(* Server env*/+export type AuthProvider = "email" | "google" | "azure" | "passkey";+export const AUTH_PROVIDERS =getEnv("AUTH_PROVIDERS", {isRequired: false,isSecret: false- }) ?? "email,google,azure";+ }) ?? "email,google,azure,passkey";++export function isAuthProviderEnabled(provider: AuthProvider) {+ const AUTH_PROVIDERS_LIST = AUTH_PROVIDERS.split(",").map((p) => p.trim());+ return AUTH_PROVIDERS_LIST.includes(provider);+}const CARBON_EDITION = getEnv("CARBON_EDITION", {isRequired: false,