Files
Stirling-PDF/frontend/editor/src/saas/hooks/useAutoAnonymousAuth.ts
T
0a50e765b7 Restructure/frontend editor (#6404)
## Move editor under `frontend/editor/`

Pure restructure: `frontend/` becomes the workspace, `frontend/editor/`
holds
  the PDF editor. 1775 file renames + 40 wiring edits. No logic changes.

  ### Why

`frontend/` is currently the editor — its `src/`, `public/`,
`src-tauri/`,
  config files all sit at the root. Promoting `frontend/` to a
workspace and putting the editor in a sibling folder leaves room for
future
apps to drop in alongside it, sharing one `package.json` /
`node_modules` /
  lint config / Storybook.

  ### What moves

  frontend/
  ├── editor/                ← NEW: everything editor-specific
  │   ├── src/               ← was frontend/src/
  │   ├── public/            ← was frontend/public/
  │   ├── src-tauri/         ← was frontend/src-tauri/
│ ├── index.html, vite.config.ts, vitest.config.ts, playwright.config.ts
  │   ├── tsconfig*.json, tailwind.config.js, postcss.config.js
  │   ├── scripts/
  │   ├── .env, .env.desktop, .env.saas
  │   └── DeveloperGuide.md
├── package.json, package-lock.json, node_modules/ ← workspace install
  ├── eslint.config.mjs, .prettierrc, .prettierignore ← shared tooling
  ├── .gitignore
  └── README.md

  ### Wiring edits (40 files)

  - `.taskfiles/frontend.yml`, `desktop.yml`, `e2e.yml`
  - `build.gradle`, `app/core/build.gradle`
- `eslint.config.mjs`, `frontend/package.json`, `.gitignore`,
`.prettierignore`
  - `docker/frontend/Dockerfile`
  - 8 `.github/workflows/*.yml`, plus `.github/dependabot.yml`,
    `.github/config/.files.yaml`, `.github/labeler-config-srvaroa.yml`
  - `scripts/translations/**`
- Docs: `AGENTS.md`, `CLAUDE.md`, `ADDING_TOOLS.md`,
`DeveloperGuide.md`,
`WINDOWS_SIGNING.md`, `devGuide/HowToAddNewLanguage.md`,
`frontend/README.md`,
    `frontend/editor/DeveloperGuide.md`

Plus 3 renamed + edited: `editor/vite.config.ts` (env path +
node_modules
  walk-up), `editor/scripts/setup-env.mts` (renamed from `.ts` for
`import.meta.url`), `editor/scripts/build-provisioner.mjs` (resolve
src-tauri
  relative to script).

  ### Verification

  | Check | Result |
  |---|---|
  | `task frontend:typecheck:all` (6 variants) | exit 0 |
  | `task frontend:lint` (eslint + dpdm) | exit 0 |
  | `task frontend:format:check` | exit 0 |
  | `task frontend:test` | 657 tests pass, 50 files |
| `task frontend:build:{core,proprietary,saas,desktop,prototypes}` | all
green |
| `task desktop:build` | full Tauri pipeline →
`Stirling-PDF_2.11.0_x64_en-US.msi` |
  | `playwright test --list --project=stubbed` | 172 tests discovered |

`task desktop:build` exercises the heaviest path — Rust + WiX + MSI
bundle
against the moved `editor/src-tauri/`. If anything in the restructure
was
  wrong it wouldn't have built.

  ### Test plan

  - [ ] `frontend-validation.yml` green
  - [ ] `e2e-stubbed.yml` green
  - [ ] `tauri-build.yml` green on at least one platform
  - [ ] `check_toml.yml` runs on a translation-touching PR

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:40:34 +01:00

154 lines
4.5 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
import { useLocation } from "react-router-dom";
import { useAuth } from "@app/auth/UseSession";
import { signInAnonymously, supabase } from "@app/auth/supabase";
import { isAuthRoute, isHomeRoute, isToolRoute } from "@app/utils/pathUtils";
interface AutoAnonymousAuthState {
isAutoAuthenticating: boolean;
autoAuthError: string | null;
shouldTriggerAutoAuth: boolean;
}
/**
* Automatically signs in users anonymously on direct tool access when not authenticated.
*/
export function useAutoAnonymousAuth() {
const { session, loading } = useAuth();
const location = useLocation();
const [state, setState] = useState<AutoAnonymousAuthState>({
isAutoAuthenticating: false,
autoAuthError: null,
shouldTriggerAutoAuth: false,
});
const shouldAutoAuthenticate = useCallback((): boolean => {
const currentPath = location.pathname;
if (isAuthRoute(currentPath)) return false;
if (isHomeRoute(currentPath)) return false;
return isToolRoute(currentPath);
}, [location.pathname]);
const waitForToken = useCallback(async (timeoutMs = 7000) => {
// Prefer event-driven approach; fallback to polling if needed
let resolved = false;
const done = (ok: boolean) => {
resolved = true;
return ok;
};
const hasToken = async () => {
const {
data: { session },
} = await supabase.auth.getSession();
return !!session?.access_token;
};
if (await hasToken()) return true;
const unsub = supabase.auth.onAuthStateChange(async (_evt, _session) => {
if (!resolved && (await hasToken())) {
unsub.data.subscription.unsubscribe();
done(true);
}
});
const started = Date.now();
while (!resolved && Date.now() - started < timeoutMs) {
if (await hasToken()) {
unsub.data.subscription.unsubscribe();
return done(true);
}
// gentle backoff
await new Promise((r) => setTimeout(r, 120));
}
try {
unsub.data.subscription.unsubscribe();
} catch (err) {
// Ignore unsubscribe errors during cleanup
console.debug("[useAutoAnonymousAuth] Unsubscribe cleanup error:", err);
}
return done(false);
}, []);
const triggerAnonymousAuth = useCallback(async () => {
if (state.isAutoAuthenticating) return;
setState((prev) => ({
...prev,
isAutoAuthenticating: true,
autoAuthError: null,
}));
try {
console.log("[useAutoAnonymousAuth] anonymous auth starting");
const { error } = await signInAnonymously();
if (error) throw error;
// Wait for a usable token so first API calls won't 401/redirect
const ok = await waitForToken(7000);
if (!ok) {
throw new Error("Timed out waiting for anonymous session token");
}
console.log("[useAutoAnonymousAuth] anonymous auth complete");
setState((prev) => ({
...prev,
isAutoAuthenticating: false,
shouldTriggerAutoAuth: false,
}));
} catch (e) {
console.error("[useAutoAnonymousAuth] anonymous auth failed", e);
setState((prev) => ({
...prev,
isAutoAuthenticating: false,
autoAuthError:
e instanceof Error ? e.message : "Anonymous authentication failed",
}));
}
}, [state.isAutoAuthenticating, waitForToken]);
// Decide whether to auto-auth on mount & whenever location/auth changes
useEffect(() => {
if (loading) return;
if (session) return;
if (state.isAutoAuthenticating) return;
const shouldAuth = shouldAutoAuthenticate();
if (state.shouldTriggerAutoAuth !== shouldAuth) {
setState((prev) => ({ ...prev, shouldTriggerAutoAuth: shouldAuth }));
}
if (shouldAuth) {
console.log("[useAutoAnonymousAuth] tool route detected, auto-auth");
triggerAnonymousAuth();
}
}, [
loading,
session,
state.isAutoAuthenticating,
state.shouldTriggerAutoAuth,
shouldAutoAuthenticate,
triggerAnonymousAuth,
]);
// Clear error if route is no longer a tool route, or once authenticated
useEffect(() => {
if (session || !shouldAutoAuthenticate()) {
setState((prev) => ({
...prev,
autoAuthError: null,
shouldTriggerAutoAuth: false,
}));
}
}, [session, shouldAutoAuthenticate]);
return {
isAutoAuthenticating: state.isAutoAuthenticating,
autoAuthError: state.autoAuthError,
shouldTriggerAutoAuth: state.shouldTriggerAutoAuth,
triggerAnonymousAuth,
};
}