Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(auth): check existing emails before sign-up (#1854)
voidada9efb3f164
diff --git a/src/components/AuthenticationStep.tsx b/src/components/AuthenticationStep.tsxindex 8c0efe946..71545b599 100644--- a/src/components/AuthenticationStep.tsx+++ b/src/components/AuthenticationStep.tsx@@ -9,7 +9,7 @@ import {updateLastSignInTime,type SocialProvider,} from "../lib/auth";-import { OPENWHISPR_API_URL } from "../config/constants";+import { discoverEmailAuth } from "../lib/emailAuthDiscovery";import { Button } from "./ui/button";import { Input } from "./ui/input";import { AlertCircle, ArrowRight, Building2, Check, Loader2, ChevronLeft } from "lucide-react";@@ -33,6 +33,11 @@ type SsoDiscovery = {exists: boolean;};+const EXISTING_ACCOUNT_ERROR_CODES = new Set([+ "USER_ALREADY_EXISTS",+ "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL",+]);+function ProviderTile({label,icon: Icon,@@ -228,30 +233,18 @@ export default function AuthenticationStep({setError(null);try {- if (!OPENWHISPR_API_URL) {+ const data = await discoverEmailAuth(email, AUTH_URL);+ if (!data) {+ // No discovery endpoint on this auth server — default to sign-up; an+ // existing email is still caught by the duplicate check at sign-up.setAuthMode("sign-up");return;}-- const response = await fetch(`${OPENWHISPR_API_URL}/api/check-user`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email: email.trim() }),- });-- if (!response.ok) {- throw new Error(t("auth.errors.failedUserCheck"));- }-- const data = (await response.json().catch(() => ({}))) as {- exists?: boolean;- sso?: { available?: boolean; required?: boolean; domain?: string };- };if (data.sso?.available) {const discovery = {- required: data.sso.required === true,+ required: data.sso.required,domain: data.sso.domain || email.trim().split("@")[1] || "your organization",- exists: data.exists === true,+ exists: data.exists,};setSsoDiscovery(discovery);if (discovery.required) await startSSOSignIn(email);@@ -298,6 +291,7 @@ export default function AuthenticationStep({if (result.error) {needsVerificationRef.current = false;if (+ EXISTING_ACCOUNT_ERROR_CODES.has(result.error.code || "") ||errorMessageIncludes(result.error.message, ["already exists", "already registered"])) {setAuthMode("sign-in");diff --git a/src/lib/emailAuthDiscovery.ts b/src/lib/emailAuthDiscovery.tsnew file mode 100644index 000000000..3a30a7863--- /dev/null+++ b/src/lib/emailAuthDiscovery.ts@@ -0,0 +1,67 @@+export interface EmailAuthDiscovery {+ exists: boolean;+ sso?: {+ available: boolean;+ required: boolean;+ domain?: string;+ };+}++const INVALID_DISCOVERY_RESPONSE = "Email account discovery returned an invalid response";++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null;+}++function parseEmailAuthDiscovery(value: unknown): EmailAuthDiscovery {+ // Only `exists` is load-bearing (it routes between sign-in and sign-up), so+ // only it is validated strictly. The sso block is advisory: a missing or+ // malformed one falls back to the plain email flow instead of blocking auth.+ if (!isRecord(value) || typeof value.exists !== "boolean") {+ throw new Error(INVALID_DISCOVERY_RESPONSE);+ }++ const sso = value.sso;+ if (!isRecord(sso) || sso.available !== true) {+ return { exists: value.exists };+ }++ return {+ exists: value.exists,+ sso: {+ available: true,+ required: sso.required === true,+ ...(typeof sso.domain === "string" ? { domain: sso.domain } : {}),+ },+ };+}++export async function discoverEmailAuth(+ email: string,+ authUrl: string+): Promise<EmailAuthDiscovery | null> {+ const response = await fetch(`${authUrl}/api/check-user`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email: email.trim() }),+ });++ // A self-hosted auth server may not implement /api/check-user; report that+ // as "discovery unavailable" so the caller can fall back instead of erroring.+ if (response.status === 404) {+ return null;+ }++ if (!response.ok) {+ throw new Error(`Email account discovery failed with status ${response.status}`);+ }++ let data: unknown;+ try {+ data = await response.json();+ } catch {+ throw new Error(INVALID_DISCOVERY_RESPONSE);+ }++ return parseEmailAuthDiscovery(data);+}diff --git a/test/components/authenticationStep.test.js b/test/components/authenticationStep.test.jsnew file mode 100644index 000000000..fa6d73e54--- /dev/null+++ b/test/components/authenticationStep.test.js@@ -0,0 +1,201 @@+const assert = require("node:assert/strict");+const test = require("node:test");+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");++const AUTH_MODE_INDEX = 0;+const EMAIL_INDEX = 1;+const PASSWORD_INDEX = 2;+const FULL_NAME_INDEX = 3;+const SSO_DISCOVERY_INDEX = 8;+const ERROR_INDEX = 9;++function createHarness(values = {}) {+ return {+ cursor: 0,+ refCursor: 0,+ values,+ refs: {},+ discoveryCalls: [],+ discoveryResult: { exists: false },+ discoveryError: null,+ signupResult: {},+ };+}++function findElement(node, predicate) {+ if (Array.isArray(node)) {+ for (const child of node) {+ const match = findElement(child, predicate);+ if (match) return match;+ }+ return null;+ }+ if (!node || typeof node !== "object") return null;+ if (predicate(node)) return node;+ return findElement(node.props?.children, predicate);+}++async function settleAsyncHandler() {+ await new Promise((resolve) => setImmediate(resolve));+}++test("email authentication discovers accounts before choosing sign-in or sign-up", async (t) => {+ installBrowserGlobals(t, { window: { electronAPI: {} } });+ t.after(() => {+ delete globalThis.__authenticationStepHarness;+ });++ const vite = await createRendererServer(t, {+ cachePrefix: "openwhispr-authentication-step-",+ noExternal: ["react", "react-i18next", "lucide-react"],+ mockModules: {+ react: `+ export default {};+ export function useState(initialValue) {+ const harness = globalThis.__authenticationStepHarness;+ const index = harness.cursor++;+ if (!(index in harness.values)) {+ harness.values[index] = typeof initialValue === "function" ? initialValue() : initialValue;+ }+ return [harness.values[index], (nextValue) => {+ harness.values[index] = typeof nextValue === "function"+ ? nextValue(harness.values[index])+ : nextValue;+ }];+ }+ export function useCallback(callback) { return callback; }+ export function useEffect() {}+ export function useRef(initialValue) {+ const harness = globalThis.__authenticationStepHarness;+ const index = harness.refCursor++;+ if (!(index in harness.refs)) harness.refs[index] = { current: initialValue };+ return harness.refs[index];+ }+ `,+ "/jsx-dev-runtime": `+ export const Fragment = Symbol.for("react.fragment");+ export function jsxDEV(type, props, key) { return { type, props, key }; }+ `,+ "react-i18next": `+ export function useTranslation() {+ return { t(key) { return key; } };+ }+ `,+ "/hooks/useAuth": `+ export function useAuth() {+ return { isLoaded: true, isSignedIn: false, user: null };+ }+ `,+ "/lib/auth": `+ export const AUTH_URL = "https://auth.example.test";+ export const authClient = {+ signUp: {+ async email(payload) {+ const harness = globalThis.__authenticationStepHarness;+ harness.signupPayload = payload;+ return harness.signupResult;+ },+ },+ signIn: { async email() { return {}; } },+ };+ export async function signInWithSocial() { return {}; }+ export async function signInWithSSO() { return {}; }+ export function updateLastSignInTime() {}+ `,+ "/lib/emailAuthDiscovery": `+ export async function discoverEmailAuth(email, authUrl) {+ const harness = globalThis.__authenticationStepHarness;+ harness.discoveryCalls.push({ email, authUrl });+ if (harness.discoveryError) throw harness.discoveryError;+ return harness.discoveryResult;+ }+ `,+ "/utils/logger": `export default { error() {} };`,+ "/utils/platform": `export function getCachedPlatform() { return "linux"; }`,+ "/ForgotPasswordView": `export default function ForgotPasswordView() { return null; }`,+ "/OnboardingShell": `+ export function CompactOnboardingFrame(props) { return props.children; }+ `,+ "/ui/button": `export function Button() { return null; }`,+ "/ui/input": `export function Input() { return null; }`,+ "lucide-react": `+ const Icon = () => null;+ export { Icon as AlertCircle, Icon as ArrowRight, Icon as Building2, Icon as Check,+ Icon as Loader2, Icon as ChevronLeft };+ `,+ },+ });+ const { default: AuthenticationStep } = await vite.ssrLoadModule(+ "/components/AuthenticationStep.tsx"+ );+ const props = { onAuthComplete() {}, onNeedsVerification() {} };++ const render = (harness) => {+ globalThis.__authenticationStepHarness = harness;+ harness.cursor = 0;+ harness.refCursor = 0;+ return AuthenticationStep(props);+ };+ const submitEmail = async (harness) => {+ const form = findElement(render(harness), (node) => node.type === "form");+ assert.ok(form, "email form should render");+ form.props.onSubmit({ preventDefault() {} });+ await settleAsyncHandler();+ };++ const existingAccount = createHarness({ [EMAIL_INDEX]: "[email protected]" });+ existingAccount.discoveryResult = { exists: true };+ await submitEmail(existingAccount);+ assert.equal(existingAccount.values[AUTH_MODE_INDEX], "sign-in");+ assert.deepEqual(existingAccount.discoveryCalls, [+ { email: "[email protected]", authUrl: "https://auth.example.test" },+ ]);++ const newAccount = createHarness({ [EMAIL_INDEX]: "[email protected]" });+ await submitEmail(newAccount);+ assert.equal(newAccount.values[AUTH_MODE_INDEX], "sign-up");++ const missingEndpoint = createHarness({ [EMAIL_INDEX]: "[email protected]" });+ missingEndpoint.discoveryResult = null;+ await submitEmail(missingEndpoint);+ assert.equal(missingEndpoint.values[AUTH_MODE_INDEX], "sign-up");+ assert.equal(missingEndpoint.values[ERROR_INDEX], null);++ const unavailableDiscovery = createHarness({ [EMAIL_INDEX]: "[email protected]" });+ unavailableDiscovery.discoveryError = new Error("offline");+ await submitEmail(unavailableDiscovery);+ assert.equal(unavailableDiscovery.values[AUTH_MODE_INDEX], null);+ assert.equal(unavailableDiscovery.values[ERROR_INDEX], "auth.errors.failedUserCheck");++ const ssoAccount = createHarness({ [EMAIL_INDEX]: "[email protected]" });+ ssoAccount.discoveryResult = {+ exists: true,+ sso: { available: true, required: false, domain: "example.com" },+ };+ await submitEmail(ssoAccount);+ assert.equal(ssoAccount.values[AUTH_MODE_INDEX], null);+ assert.deepEqual(ssoAccount.values[SSO_DISCOVERY_INDEX], {+ exists: true,+ required: false,+ domain: "example.com",+ });++ const duplicateRace = createHarness({+ [AUTH_MODE_INDEX]: "sign-up",+ [EMAIL_INDEX]: "[email protected]",+ [PASSWORD_INDEX]: "password123",+ [FULL_NAME_INDEX]: "Returning User",+ });+ duplicateRace.signupResult = {+ error: {+ code: "USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL",+ message: "A localized duplicate-account response",+ },+ };+ const signupForm = findElement(render(duplicateRace), (node) => node.type === "form");+ assert.ok(signupForm, "sign-up form should render");+ await signupForm.props.onSubmit({ preventDefault() {} });+ assert.equal(duplicateRace.values[AUTH_MODE_INDEX], "sign-in");+ assert.equal(duplicateRace.values[PASSWORD_INDEX], "");+ assert.equal(duplicateRace.values[ERROR_INDEX], "auth.errors.accountExistsSignIn");+});diff --git a/test/lib/emailAuthDiscovery.test.js b/test/lib/emailAuthDiscovery.test.jsnew file mode 100644index 000000000..78e3acf5e--- /dev/null+++ b/test/lib/emailAuthDiscovery.test.js@@ -0,0 +1,96 @@+const assert = require("node:assert/strict");+const test = require("node:test");++const { discoverEmailAuth } = require("../../src/lib/emailAuthDiscovery.ts");++function installFetch(t, implementation) {+ const previousFetch = global.fetch;+ global.fetch = implementation;+ t.after(() => {+ global.fetch = previousFetch;+ });+}++test("email discovery preserves the auth base URL and SSO routing", async (t) => {+ let request;+ installFetch(t, async (input, init) => {+ request = { input, init };+ return new Response(+ JSON.stringify({+ exists: true,+ sso: { available: true, required: false, domain: "example.com" },+ })+ );+ });++ const result = await discoverEmailAuth(+ " [email protected] ",+ "https://auth.example.test/custom/path"+ );++ assert.equal(String(request.input), "https://auth.example.test/custom/path/api/check-user");+ assert.equal(request.init.method, "POST");+ assert.deepEqual(JSON.parse(request.init.body), { email: "[email protected]" });+ assert.deepEqual(result, {+ exists: true,+ sso: { available: true, required: false, domain: "example.com" },+ });+});++test("email discovery accepts the legacy response without SSO metadata", async (t) => {+ installFetch(t, async () => new Response(JSON.stringify({ exists: false })));++ assert.deepEqual(await discoverEmailAuth("[email protected]", "https://auth.example.test"), {+ exists: false,+ });+});++test("email discovery treats the sso block as advisory", async (t) => {+ const lenientCases = [+ [+ { exists: true, sso: { available: true } },+ { exists: true, sso: { available: true, required: false } },+ ],+ [+ { exists: true, sso: { available: true, required: "no", domain: 42 } },+ { exists: true, sso: { available: true, required: false } },+ ],+ [{ exists: false, sso: { available: false } }, { exists: false }],+ [{ exists: true, sso: null }, { exists: true }],+ ];+ let payload;+ installFetch(t, async () => new Response(JSON.stringify(payload)));+ for (const [response, expected] of lenientCases) {+ payload = response;+ assert.deepEqual(+ await discoverEmailAuth("[email protected]", "https://auth.example.test"),+ expected+ );+ }+});++test("email discovery reports a missing endpoint as unavailable", async (t) => {+ installFetch(t, async () => new Response("not found", { status: 404 }));++ assert.equal(await discoverEmailAuth("[email protected]", "https://auth.example.test"), null);+});++test("email discovery rejects failed and malformed responses", async (t) => {+ installFetch(t, async () => new Response("service unavailable", { status: 503 }));+ await assert.rejects(discoverEmailAuth("[email protected]", "https://auth.example.test"), {+ message: "Email account discovery failed with status 503",+ });++ const invalidPayloads = [{}, { exists: "yes" }];+ for (const payload of invalidPayloads) {+ global.fetch = async () => new Response(JSON.stringify(payload));+ await assert.rejects(discoverEmailAuth("[email protected]", "https://auth.example.test"), {+ message: "Email account discovery returned an invalid response",+ });+ }++ global.fetch = async () => new Response("not json");+ await assert.rejects(discoverEmailAuth("[email protected]", "https://auth.example.test"), {+ message: "Email account discovery returned an invalid response",+ });+});