Skip to content

feat: invalid domain warning#332

Merged
steveiliop56 merged 8 commits intomainfrom
feat/domain-warning
Sep 1, 2025
Merged

feat: invalid domain warning#332
steveiliop56 merged 8 commits intomainfrom
feat/domain-warning

Conversation

@steveiliop56
Copy link
Copy Markdown
Member

@steveiliop56 steveiliop56 commented Sep 1, 2025

Summary by CodeRabbit

  • New Features
    • Domain-mismatch warning before loading the app with a per-session "Ignore" option.
    • Two-step redirect flow: automatic safe redirect plus a "Redirect me manually" option and clearer untrusted/insecure redirect screens with accessibility alerts.
  • Style
    • Adjusted warning button dark-mode styling.
    • Code elements now wrap to avoid overflow.
  • Localization
    • Updated and reorganized redirect and domain-warning copy; added new labels.
  • Chores
    • Removed CLI flag to disable continue.
    • Removed sanitization dependency; redirects now use URL-based handling with timed navigation and cleanup.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 1, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Removes the CLI flag disable-continue. Replaces backend Domain/DisableContinue with AppURL/RootDomain and exposes them in the context response. Frontend adds a DomainWarning and session-dismissable layout gate, rewrites the /continue flow to use URL parsing and timed auto/manual redirects, updates i18n keys, and removes DOMPurify.

Changes

Cohort / File(s) Summary
CLI Flag Removal
cmd/root.go
Drops the --disable-continue CLI flag definition.
Backend Config & Bootstrap
internal/config/config.go, internal/bootstrap/...
Removes DisableContinue from Config; replaces Domain with AppURL/RootDomain in bootstrap wiring and controller configs; cookieId now derived from AppURL hostname.
Context Controller
internal/controller/context_controller.go
AppContextResponse now exposes appUrl and rootDomain; DisableContinue/Domain removed; Oauth renamed to OAuth.
OAuth/User Controllers & Auth Service
internal/controller/oauth_controller.go, internal/controller/user_controller.go, internal/service/auth_service.go
Renames exported config fields from DomainRootDomain; cookie domain logic and redirect safety checks now use RootDomain.
Middleware
internal/middleware/context_middleware.go
ContextMiddlewareConfig.DomainRootDomain; email construction uses RootDomain.
Utils Rename
internal/utils/app_utils.go
GetUpperDomain renamed to GetRootDomain (same behavior).
Frontend App Context Schema
frontend/src/schemas/app-context-schema.ts
Replaces disableContinue and domain with appUrl and rootDomain in Zod schema.
Layout & Domain Warning UI
frontend/src/components/layout/layout.tsx, frontend/src/components/domain-warning/domain-warning.tsx
Adds DomainWarning component and BaseLayout; Layout shows a sessionStorage-dismissable domain-mismatch alert when appUrl differs from window.location.origin.
Continue Page Flow
frontend/src/pages/continue-page.tsx
Removes DOMPurify; parses redirect using URL; adds validators (protocol, trusted/rootDomain, HTTPS downgrade); auto-redirects (100ms) when safe; reveals manual redirect after 1s; separates untrusted/insecure flows; updates i18n keys.
Frontend Pages: Redirect Timing & Guards
frontend/src/pages/login-page.tsx, frontend/src/pages/logout-page.tsx, frontend/src/pages/totp-page.tsx, frontend/src/pages/unauthorized-page.tsx
Moves early redirect guards to after hooks/mutations, adds useRef timer-based delayed redirects (~500ms) with cleanup effects, and consolidates i18n/loading usage.
i18n Key Rework
frontend/src/lib/i18n/locales/en.json, frontend/src/lib/i18n/locales/en-US.json
Removes legacy continue/untrusted keys; adds continueRedirectManually, continueUntrustedRedirectTitle/Subtitle, domainWarningTitle/Subtitle, ignoreTitle, goToCorrectDomainTitle; placeholders updated to rootDomain/appUrl/currentUrl.
UI / Style Tweaks
frontend/src/components/ui/button.tsx, frontend/src/index.css
Removes dark:bg-amber-600 from warning button variant; adds break-all to code selector to wrap long tokens.
Dependency cleanup
frontend/package.json
Removes dompurify dependency from frontend.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Browser
  participant Layout
  participant DomainWarning
  participant App

  User->>Browser: Load app
  Browser->>Layout: Render with appUrl/rootDomain
  alt origin != configured appUrl AND no session ignore
    Layout->>DomainWarning: Show warning (appUrl, currentUrl)
    User-->>DomainWarning: Click "Ignore"
    DomainWarning->>Layout: onClick() -> sessionStorage.setItem + update state
    Layout->>App: Render content
  else
    Layout->>App: Render content
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant Browser
  participant ContinuePage

  User->>ContinuePage: Navigate with redirect_uri
  ContinuePage->>ContinuePage: Parse redirect_uri (URL) & validate proto/host/rootDomain/https downgrade
  alt valid & trusted
    Note over ContinuePage: schedule auto-redirect (100ms)
    ContinuePage->>Browser: window.location.replace(redirect) (auto)
  else if untrusted or insecure
    ContinuePage->>User: Render alert card (continueUntrusted/insecure)
    User->>ContinuePage: Click proceed
    ContinuePage->>Browser: window.location.assign(redirect) (manual)
  end
  Note over ContinuePage: reveal manual button after 1s if auto pending
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A rabbit sniffs the root and checks each door,
"Is this the app URL or some distant shore?" 🐇
I flash a yellow card, then wait a beat,
Auto-hop quick, or press to make the leap.
Ignore for this session — then onward, fleet. ✨


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c80c37b and 95f8a95.

📒 Files selected for processing (6)
  • internal/bootstrap/app_bootstrap.go (6 hunks)
  • internal/controller/oauth_controller.go (5 hunks)
  • internal/controller/user_controller.go (4 hunks)
  • internal/middleware/context_middleware.go (3 hunks)
  • internal/service/auth_service.go (3 hunks)
  • internal/utils/app_utils.go (2 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/domain-warning

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov
Copy link
Copy Markdown

codecov Bot commented Sep 1, 2025

Codecov Report

❌ Patch coverage is 0% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 0.00%. Comparing base (17048d9) to head (95f8a95).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/bootstrap/app_bootstrap.go 0.00% 9 Missing ⚠️
internal/controller/oauth_controller.go 0.00% 6 Missing ⚠️
internal/controller/context_controller.go 0.00% 5 Missing ⚠️
internal/controller/user_controller.go 0.00% 3 Missing ⚠️
internal/middleware/context_middleware.go 0.00% 2 Missing ⚠️
internal/service/auth_service.go 0.00% 2 Missing ⚠️
internal/utils/app_utils.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@          Coverage Diff          @@
##            main    #332   +/-   ##
=====================================
  Coverage   0.00%   0.00%           
=====================================
  Files         32      32           
  Lines       2378    2380    +2     
=====================================
- Misses      2378    2380    +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
frontend/src/pages/continue-page.tsx (2)

20-28: Hooks called conditionally; restructure to top-level.

useAppContext, useLocation, useState, useTranslation, useNavigate, and useEffect are placed after early returns, violating Hooks rules and triggering Biome errors. Move all Hooks to the top and gate side-effects logically.

Apply:

 export const ContinuePage = () => {
-  const { isLoggedIn } = useUserContext();
-
-  if (!isLoggedIn) {
-    return <Navigate to="/login" />;
-  }
-
-  const { rootDomain } = useAppContext();
-  const { search } = useLocation();
-  const [loading, setLoading] = useState(false);
-  const [showRedirectButton, setShowRedirectButton] = useState(false);
+  const { isLoggedIn } = useUserContext();
+  const { rootDomain } = useAppContext();
+  const { search } = useLocation();
+  const [loading, setLoading] = useState(false);
+  const [showRedirectButton, setShowRedirectButton] = useState(false);
+  const { t } = useTranslation();
+  const navigate = useNavigate();

-  const { t } = useTranslation();
-  const navigate = useNavigate();
+  const searchParams = new URLSearchParams(search);
+  const redirectURI = searchParams.get("redirect_uri");
+  const sanitizedRedirectURI = redirectURI ? DOMPurify.sanitize(redirectURI) : "";
+  const isRedirectUriValid = !!redirectURI && isValidUrl(sanitizedRedirectURI);
+  const redirectURLObj = isRedirectUriValid ? new URL(sanitizedRedirectURI) : null;
+  const normalizeHost = (h: string) => h.toLowerCase().replace(/\.$/, "");
+  const rd = normalizeHost(rootDomain ?? "");
+  const host = redirectURLObj ? normalizeHost(redirectURLObj.hostname) : "";
+  const isTrusted =
+    redirectURLObj ? host === rd || host.endsWith(`.${rd}`) : false;
+  const isHttpsDowngrade =
+    redirectURLObj
+      ? redirectURLObj.protocol === "http:" && window.location.protocol === "https:"
+      : false;

-  const handleRedirect = () => {
+  const handleRedirect = () => {
     setLoading(true);
-    window.location.href = DOMPurify.sanitize(redirectURI);
+    // replace() avoids polluting history with the interstitial page
+    window.location.replace(sanitizedRedirectURI);
   };
 
-  const redirectURLObj = new URL(redirectURI);
+  // Auto-redirect only when safe and applicable
+  useEffect(() => {
+    if (!isLoggedIn || !isRedirectUriValid || !isTrusted || isHttpsDowngrade) {
+      return;
+    }
+    const t1 = setTimeout(() => {
+      handleRedirect();
+    }, 100);
+    const t2 = setTimeout(() => {
+      setLoading(false);
+      setShowRedirectButton(true);
+    }, 1000);
+    return () => {
+      clearTimeout(t1);
+      clearTimeout(t2);
+    };
+  }, [isLoggedIn, isRedirectUriValid, isTrusted, isHttpsDowngrade]);
 
+  // Early returns after hooks are declared
+  if (!isLoggedIn) {
+    return <Navigate to="/login" />;
+  }
-  const searchParams = new URLSearchParams(search);
-  const redirectURI = searchParams.get("redirect_uri");
-
   if (!redirectURI) {
     return <Navigate to="/logout" />;
   }
 
-  if (!isValidUrl(DOMPurify.sanitize(redirectURI))) {
+  if (!isRedirectUriValid) {
     return <Navigate to="/logout" />;
   }

Also applies to: 40-41, 127-135


75-78: Button label key exists?

These buttons use t("continueTitle") but that key was removed from locales in this PR. Either re-add the key (preferred, see locale comments) or swap to an existing key. Re-adding keeps copy concise (“Continue” vs “Redirect me manually”).

Also applies to: 112-114

🧹 Nitpick comments (9)
frontend/src/index.css (1)

158-160: Prefer break-words over break-all to avoid mid-token breaks in code.

break-all can split URLs/tokens awkwardly. break-words wraps long strings without breaking every character.

-code {
-  @apply relative rounded bg-muted px-[0.2rem] py-[0.1rem] font-mono text-sm font-semibold break-all;
-}
+code {
+  @apply relative rounded bg-muted px-[0.2rem] py-[0.1rem] font-mono text-sm font-semibold break-words;
+}
frontend/src/components/ui/button.tsx (1)

24-26: Dark-mode warning button may lose contrast; consider restoring dark:bg.

Without a dark:bg token, bg-amber-500 is used in dark too; white text may be borderline. Suggest adding dark:bg-amber-600 (and optional dark:hover).

-        warning:
-          "bg-amber-500 text-white shadow-xs hover:bg-amber-400 focus-visible:ring-amber-200/20 dark:focus-visible:ring-amber-400/40",
+        warning:
+          "bg-amber-500 text-white shadow-xs hover:bg-amber-400 focus-visible:ring-amber-200/20 dark:focus-visible:ring-amber-400/40 dark:bg-amber-600 dark:hover:bg-amber-500",
frontend/src/schemas/app-context-schema.ts (1)

7-8: Tighten validation: appUrl should be a URL; rootDomain should be a bare domain.

Prevents malformed values from breaking the domain-warning gate.

-  appUrl: z.string(),
-  rootDomain: z.string(),
+  appUrl: z.string().url(),
+  rootDomain: z
+    .string()
+    .transform((s) => s.trim().toLowerCase())
+    .regex(
+      /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i,
+      "rootDomain must be a domain like example.com",
+    ),
internal/controller/context_controller.go (1)

35-45: Remove unused DisableContinue field from ContextControllerConfig.

 internal/controller/context_controller.go
 type ContextControllerConfig struct {
-  DisableContinue bool
 }
internal/bootstrap/app_bootstrap.go (1)

47-56: Optional: sanity-check AppURL host vs derived domain at startup.

Prevents misconfig where AppURL host doesn’t end with RootDomain.

   // Get domain
   domain, err := utils.GetUpperDomain(app.Config.AppURL)
   if err != nil {
     return err
   }
+  if host, herr := utils.GetHost(app.Config.AppURL); herr == nil && !strings.HasSuffix(host, domain) {
+    return fmt.Errorf("app-url host %q does not match derived root domain %q", host, domain)
+  }
frontend/src/pages/continue-page.tsx (1)

112-121: Severity style consistency.

Consider variant="warning" (not "destructive") for the untrusted-redirect confirm to match the insecure-redirect confirm and convey caution rather than irreversible action.

-          <Button
-            onClick={handleRedirect}
-            loading={loading}
-            variant="destructive"
-          >
+          <Button onClick={handleRedirect} loading={loading} variant="warning">
             {t("continueTitle")}
           </Button>
frontend/src/components/domain-warning/domain-warning.tsx (2)

22-22: Add alert semantics for accessibility

Expose the warning to assistive tech.

Apply this diff:

-    <Card className="min-w-xs sm:min-w-sm">
+    <Card role="alert" aria-live="assertive" className="min-w-xs sm:min-w-sm">

34-38: Offer a “Go to the correct domain” primary action

Improves UX by giving a safe path in addition to “ignore”.

Apply this diff (assumes i18n key goToCorrectDomainTitle exists):

       <CardFooter className="flex flex-col items-stretch">
         <Button onClick={onClick} variant="warning">
           {t("ignoreTitle")}
         </Button>
+        <Button onClick={() => window.location.assign(appUrl)} className="mt-2">
+          {t("goToCorrectDomainTitle")}
+        </Button>
       </CardFooter>
frontend/src/components/layout/layout.tsx (1)

36-40: Consider matching by registrable root domain (eTLD+1) if subdomains are legitimate

If your deployment spans subdomains (e.g., auth.example.com vs. app.example.com), origin mismatch may be too strict.

Options:

  • Use the provided rootDomain from context to allow any subdomain of that root.
  • Otherwise, parse with URL and compare .hostname suffix against rootDomain.
  • Keep the stricter origin check behind a feature flag if necessary.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 17048d9 and 3873bb2.

📒 Files selected for processing (12)
  • cmd/root.go (0 hunks)
  • frontend/src/components/domain-warning/domain-warning.tsx (1 hunks)
  • frontend/src/components/layout/layout.tsx (2 hunks)
  • frontend/src/components/ui/button.tsx (1 hunks)
  • frontend/src/index.css (1 hunks)
  • frontend/src/lib/i18n/locales/en-US.json (2 hunks)
  • frontend/src/lib/i18n/locales/en.json (2 hunks)
  • frontend/src/pages/continue-page.tsx (5 hunks)
  • frontend/src/schemas/app-context-schema.ts (1 hunks)
  • internal/bootstrap/app_bootstrap.go (1 hunks)
  • internal/config/config.go (0 hunks)
  • internal/controller/context_controller.go (4 hunks)
💤 Files with no reviewable changes (2)
  • internal/config/config.go
  • cmd/root.go
🧰 Additional context used
🧬 Code graph analysis (7)
frontend/src/components/domain-warning/domain-warning.tsx (1)
frontend/src/components/ui/card.tsx (10)
  • Card (85-85)
  • CardHeader (86-86)
  • CardTitle (88-88)
  • CardDescription (90-90)
  • CardFooter (87-87)
  • CardTitle (31-39)
  • CardDescription (41-49)
  • Card (5-16)
  • CardHeader (18-29)
  • CardAction (51-62)
internal/bootstrap/app_bootstrap.go (4)
internal/config/config.go (1)
  • Config (17-56)
internal/controller/user_controller.go (2)
  • Domain (24-26)
  • Config (28-32)
internal/controller/proxy_controller.go (1)
  • AppURL (20-22)
internal/middleware/context_middleware.go (1)
  • Domain (14-16)
frontend/src/components/layout/layout.tsx (2)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/components/domain-warning/domain-warning.tsx (1)
  • DomainWarning (17-41)
frontend/src/pages/continue-page.tsx (2)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/pages/totp-page.tsx (1)
  • window (42-46)
frontend/src/lib/i18n/locales/en.json (1)
frontend/src/pages/totp-page.tsx (1)
  • window (42-46)
internal/controller/context_controller.go (3)
internal/config/config.go (1)
  • Config (17-56)
internal/controller/oauth_controller.go (3)
  • Config (29-34)
  • CSRFCookieName (21-27)
  • controller (93-210)
internal/controller/user_controller.go (2)
  • Config (28-32)
  • Domain (24-26)
frontend/src/lib/i18n/locales/en-US.json (1)
frontend/src/pages/totp-page.tsx (2)
  • window (42-46)
  • toast (37-47)
🪛 Biome (2.1.2)
frontend/src/pages/continue-page.tsx

[error] 24-24: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)


[error] 25-25: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)


[error] 26-26: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)


[error] 27-27: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)


[error] 40-40: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)


[error] 41-41: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)


[error] 127-127: This hook is being called conditionally, but all hooks must be called in the exact same order in every component render.

Hooks should not be called after an early return.

For React to preserve state between calls, hooks needs to be called unconditionally and always in the same order.
See https://reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level

(lint/correctness/useHookAtTopLevel)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (9)
internal/controller/context_controller.go (2)

18-20: Field rename to OAuth looks good and keeps json:"oauth".

No API change for clients; internal naming aligns with common casing.


92-105: App context response matches frontend schema (appUrl/rootDomain).

Good alignment with the new schema and UI gate.

internal/bootstrap/app_bootstrap.go (1)

182-184: Correctly wiring AppURL and RootDomain.

RootDomain derived from GetUpperDomain and passed consistently.

frontend/src/lib/i18n/locales/en-US.json (1)

54-56: Domain warning copy LGTM.
The new domainWarningTitle/Subtitles and ignoreTitle read clearly and match the new DomainWarning flow.

frontend/src/lib/i18n/locales/en.json (1)

54-56: LGTM on new keys.
Copies align with DomainWarning and untrusted-redirect flows.

frontend/src/pages/continue-page.tsx (1)

145-151: Timeout cleanup and manual fallback LGTM.

The manual button appears after 1s; with the gating/useEffect cleanup above this avoids stray timers on alternate branches.

frontend/src/components/domain-warning/domain-warning.tsx (2)

21-33: Solid i18n usage with Trans and code components

Reads well and keeps URLs safely wrapped.


35-37: No action needed: Button supports variant="warning"
The buttonVariants definition in button.tsx includes a warning variant, so the fallback to destructive is unnecessary.

frontend/src/components/layout/layout.tsx (1)

7-23: BaseLayout extraction looks good

Keeps language selector and background concerns isolated.

Comment thread frontend/src/components/layout/layout.tsx
Comment thread frontend/src/lib/i18n/locales/en-US.json
Comment thread frontend/src/lib/i18n/locales/en.json
Comment thread frontend/src/pages/continue-page.tsx Outdated
@steveiliop56
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
frontend/src/pages/continue-page.tsx (1)

36-39: Optional: normalize hostnames for UX (case/trailing dot)

Lowercasing and trimming a trailing dot avoids false negatives for legitimate hosts (e.g., EXAMPLE.COM, example.com.) showing as untrusted.

-      ? redirectUriObj.hostname === rootDomain ||
-        redirectUriObj.hostname.endsWith(`.${rootDomain}`)
+      ? normalizeHost(redirectUriObj.hostname) === normalizeHost(rootDomain) ||
+        normalizeHost(redirectUriObj.hostname).endsWith(`.${normalizeHost(rootDomain)}`)
       : false;
+  function normalizeHost(host: string) {
+    return host.toLowerCase().replace(/\.$/, "");
+  }
🧹 Nitpick comments (3)
frontend/src/pages/login-page.tsx (1)

94-105: Autoredirect safety + top-level redirect guard LGTM (minor hooks nit)

  • Skipping OAuth autoredirect when already logged in and routing logged-in users to /logout is consistent with the flow.
  • Minor: consider adding dependencies to the useEffect or an explicit comment to silence exhaustive-deps if intentional.
-  useEffect(() => {
+  useEffect(() => {
     if (isMounted()) {
       if (
         oauthConfigured &&
         configuredProviders.includes(oauthAutoRedirect) &&
         !isLoggedIn &&
         redirectUri
       ) {
         oauthMutation.mutate(oauthAutoRedirect);
       }
     }
-  }, []);
+  // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, []);

Also applies to: 107-109

frontend/src/pages/continue-page.tsx (2)

30-34: Minor: build URL from the same sanitized string you validated

Keeps validation and parsing in lockstep and avoids surprises if sanitization alters the string.

-  const isValidRedirectUri =
-    redirectUri !== null ? isValidUrl(DOMPurify.sanitize(redirectUri)) : false;
-  const redirectUriObj = isValidRedirectUri
-    ? new URL(redirectUri as string)
-    : null;
+  const sanitizedRedirectUri =
+    redirectUri !== null ? DOMPurify.sanitize(redirectUri) : null;
+  const isValidRedirectUri =
+    sanitizedRedirectUri !== null ? isValidUrl(sanitizedRedirectUri) : false;
+  const redirectUriObj = isValidRedirectUri
+    ? new URL(sanitizedRedirectUri as string)
+    : null;

99-104: Tone of primary action in untrusted flow

Consider variant="warning" instead of destructive to align with the insecure-redirect screen and differentiate danger from confirmation.

-          <Button
-            onClick={handleRedirect}
-            loading={loading}
-            variant="destructive"
-          >
+          <Button onClick={handleRedirect} loading={loading} variant="warning">
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3873bb2 and 4ef5eef.

📒 Files selected for processing (8)
  • frontend/src/components/layout/layout.tsx (2 hunks)
  • frontend/src/lib/i18n/locales/en-US.json (2 hunks)
  • frontend/src/lib/i18n/locales/en.json (2 hunks)
  • frontend/src/pages/continue-page.tsx (4 hunks)
  • frontend/src/pages/login-page.tsx (6 hunks)
  • frontend/src/pages/logout-page.tsx (2 hunks)
  • frontend/src/pages/totp-page.tsx (1 hunks)
  • frontend/src/pages/unauthorized-page.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • frontend/src/lib/i18n/locales/en.json
  • frontend/src/components/layout/layout.tsx
  • frontend/src/lib/i18n/locales/en-US.json
🧰 Additional context used
🧬 Code graph analysis (2)
frontend/src/pages/login-page.tsx (1)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/pages/continue-page.tsx (3)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/lib/utils.ts (1)
  • isValidUrl (8-15)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
frontend/src/pages/totp-page.tsx (1)

50-52: Guard placement LGTM

Moving the redirect guard after mutation creation is fine and keeps the component consistent with the rest of the auth flow.

frontend/src/pages/logout-page.tsx (2)

31-31: Non-async timeout is appropriate

Dropping the unnecessary async wrapper is correct here.


42-44: Late redirect guard LGTM

Deferring the isLoggedIn check until after the mutation definition matches the new pattern across pages.

frontend/src/pages/login-page.tsx (2)

52-54: Use location.replace to avoid extra history entry — good call

Prevents users from navigating back into a transient state.


130-133: Per-provider loading state is clear and correct

Using oauthMutation.variables to scope the spinner to the active provider improves UX.

Also applies to: 144-147, 156-159

frontend/src/pages/unauthorized-page.tsx (2)

15-19: Hook consolidation/readability LGTM

Co-locating t, navigate, and loading state simplifies the component.


31-33: Redirect guard order LGTM

Early exit when both username and ip are absent avoids rendering unnecessary UI.

Comment thread frontend/src/pages/continue-page.tsx
Comment thread frontend/src/pages/continue-page.tsx Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
frontend/src/pages/continue-page.tsx (1)

55-64: LGTM: auto-redirect timers with cleanup.

Thanks for adding proper cleanup; this addresses earlier feedback about clearing timeouts.

Also applies to: 66-69, 70-73, 75-79

🧹 Nitpick comments (3)
frontend/src/pages/logout-page.tsx (1)

31-36: Don't return a cleanup from onSuccess; React Query ignores it.

The returned function is never called by React Query. Either drop the return or manage the timer with a ref + component unmount cleanup.

Apply minimal fix (remove unused cleanup):

-      const redirect = setTimeout(() => {
+      const redirect = window.setTimeout(() => {
         window.location.replace("/login");
       }, 500);
-
-      return () => clearTimeout(redirect);

Robust alternative (outside this hunk): store the ID and clear on unmount.

// add near component top
const logoutRedirectTimer = useRef<number | null>(null);

// inside onSuccess
logoutRedirectTimer.current = window.setTimeout(() => {
  window.location.replace("/login");
}, 500);

// add once in component
useEffect(() => () => {
  if (logoutRedirectTimer.current) clearTimeout(logoutRedirectTimer.current);
}, []);
frontend/src/pages/continue-page.tsx (2)

34-38: Normalize hostnames to avoid false warnings (case, trailing dot).

Hostnames are case-insensitive and may include a trailing dot; normalize both sides before comparison to reduce noise for valid redirects.

-  const isTrustedRedirectUri =
-    redirectUriObj !== null
-      ? redirectUriObj.hostname === rootDomain ||
-        redirectUriObj.hostname.endsWith(`.${rootDomain}`)
-      : false;
+  const isTrustedRedirectUri =
+    redirectUriObj !== null
+      ? (() => {
+          const host = redirectUriObj.hostname.toLowerCase().replace(/\.$/, "");
+          const root = rootDomain.toLowerCase().replace(/\.$/, "");
+          return host === root || host.endsWith(`.${root}`);
+        })()
+      : false;

52-53: Remove non-null assertion with a guard (minor).

Safer and clearer to guard before use.

-  const handleRedirect = () => {
-    setLoading(true);
-    window.location.replace(redirectUriObj!.toString());
-  };
+  const handleRedirect = () => {
+    if (!redirectUriObj) return;
+    setLoading(true);
+    window.location.replace(redirectUriObj.toString());
+  };
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 4ef5eef and 57dd8a6.

⛔ Files ignored due to path filters (1)
  • frontend/bun.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • frontend/package.json (0 hunks)
  • frontend/src/pages/continue-page.tsx (4 hunks)
  • frontend/src/pages/login-page.tsx (7 hunks)
  • frontend/src/pages/logout-page.tsx (2 hunks)
  • frontend/src/pages/totp-page.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • frontend/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/pages/totp-page.tsx
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-01T13:58:41.884Z
Learnt from: steveiliop56
PR: steveiliop56/tinyauth#332
File: frontend/src/pages/continue-page.tsx:30-45
Timestamp: 2025-09-01T13:58:41.884Z
Learning: For redirect URI validation in React applications where the URI is only used for navigation (not DOM rendering), DOMPurify sanitization is unnecessary since React handles DOM sanitization and the URI isn't rendered. The critical security measure is explicit protocol validation to prevent javascript: and data: URL attacks.

Applied to files:

  • frontend/src/pages/continue-page.tsx
📚 Learning: 2025-09-01T13:52:04.446Z
Learnt from: steveiliop56
PR: steveiliop56/tinyauth#332
File: frontend/src/pages/continue-page.tsx:30-45
Timestamp: 2025-09-01T13:52:04.446Z
Learning: The URL constructor in JavaScript does not reject dangerous schemes like `javascript:` or `data:` - it successfully parses them into URL objects with the corresponding protocol property. Additional scheme validation is required to prevent XSS attacks through malicious redirect URIs.

Applied to files:

  • frontend/src/pages/continue-page.tsx
🧬 Code graph analysis (2)
frontend/src/pages/login-page.tsx (1)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/pages/continue-page.tsx (3)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/lib/utils.ts (1)
  • isValidUrl (8-15)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (actions)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (11)
frontend/src/pages/logout-page.tsx (1)

44-46: LGTM: early redirect guard.

Redirecting unauthenticated users to /login here is correct and avoids rendering the page unnecessarily.

frontend/src/pages/login-page.tsx (4)

27-28: LGTM: context destructure changes.


103-104: LGTM: guard oauth auto-redirect when already logged in.


111-113: LGTM: delayed isLoggedIn redirect.

Moving this guard avoids immediate short-circuit before effects are set up.


134-137: LGTM: provider-specific loading state.

Correctly scopes loading to the active provider.

Also applies to: 148-150, 161-163

frontend/src/pages/continue-page.tsx (6)

39-43: LGTM: explicit http/https allowlist for redirects.

Mandatory check; good defense against javascript:/data: schemes.


44-48: LGTM: HTTPS→HTTP downgrade detection.

Clear, user-visible warning path.


81-83: LGTM: auth guard to /login.


85-87: LGTM: invalid/blocked scheme → /logout.


163-167: i18n keys verified across all locales
continueRedirectingTitle and continueRedirectingSubtitle are present in every JSON under frontend/src/lib/i18n/locales.


127-156: variant="warning" is supported by Button. The buttonVariants definition in frontend/src/components/ui/button.tsx includes a warning key, so this usage is correct.

Comment thread frontend/src/pages/login-page.tsx Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
frontend/src/pages/logout-page.tsx (1)

14-14: Good fix: timers are now scoped and cleaned up.

Introducing redirectTimer with a proper unmount cleanup resolves the earlier leak risk and makes redirects predictable.

Also applies to: 24-25, 34-37, 45-50

frontend/src/pages/login-page.tsx (1)

20-20: Timer leak fixed as previously requested — nice follow-through.

Import/useRef + unmount cleanup aligns with the earlier recommendation.

Also applies to: 33-34, 109-115

🧹 Nitpick comments (9)
frontend/src/pages/logout-page.tsx (3)

34-37: Extract the 500ms delay to a shared constant.

Avoid magic numbers and keep redirect timings consistent across pages.

-      redirectTimer.current = window.setTimeout(() => {
+      const REDIRECT_DELAY_MS = 500;
+      redirectTimer.current = window.setTimeout(() => {
         window.location.replace("/login");
-      }, 500);
+      }, REDIRECT_DELAY_MS);

Optionally centralize in a constants module and reuse in login/totp pages.


52-54: Use replace to avoid history bloat.

Small UX nit: add replace so back button won’t return to a dead page.

-    return <Navigate to="/login" />;
+    return <Navigate to="/login" replace />;

90-92: Prevent double-submits explicitly.

If doesn’t disable clicks, add disabled to block repeated mutations.

-        <Button
-          loading={logoutMutation.isPending}
-          onClick={() => logoutMutation.mutate()}
-        >
+        <Button
+          loading={logoutMutation.isPending}
+          disabled={logoutMutation.isPending}
+          onClick={() => logoutMutation.mutate()}
+        >

Please confirm whether loading already disables the button.

frontend/src/pages/totp-page.tsx (2)

39-44: Graceful fallback when redirectUri is missing.

Routing to /continue with an empty redirect_uri can cascade into a logout (per continue-page behavior). Prefer a sane default.

-      redirectTimer.current = window.setTimeout(() => {
-        window.location.replace(
-          `/continue?redirect_uri=${encodeURIComponent(redirectUri ?? "")}`,
-        );
-      }, 500);
+      const nextHref = redirectUri
+        ? `/continue?redirect_uri=${encodeURIComponent(redirectUri)}`
+        : "/";
+      const REDIRECT_DELAY_MS = 500;
+      redirectTimer.current = window.setTimeout(() => {
+        window.location.replace(nextHref);
+      }, REDIRECT_DELAY_MS);

Verify that continue-page still handles the valid-URI path as expected.


59-61: Navigate with replace.

Minor UX polish for non-pending visits.

-  if (!totpPending) {
-    return <Navigate to="/" />;
-  }
+  if (!totpPending) {
+    return <Navigate to="/" replace />;
+  }
frontend/src/pages/login-page.tsx (4)

54-56: Deduplicate magic delay and handle missing redirectUri.

  • Extract the 500ms delay to a constant (shared if possible).
  • If redirectUri is absent, avoid calling OAuth/continue flows that assume it.
-      redirectTimer.current = window.setTimeout(() => {
-        window.location.replace(data.data.url);
-      }, 500);
+      const REDIRECT_DELAY_MS = 500;
+      redirectTimer.current = window.setTimeout(() => {
+        window.location.replace(data.data.url);
+      }, REDIRECT_DELAY_MS);
-      redirectTimer.current = window.setTimeout(() => {
-        window.location.replace(
-          `/continue?redirect_uri=${encodeURIComponent(redirectUri ?? "")}`,
-        );
-      }, 500);
+      const nextHref = redirectUri
+        ? `/continue?redirect_uri=${encodeURIComponent(redirectUri)}`
+        : "/";
+      const REDIRECT_DELAY_MS = 500;
+      redirectTimer.current = window.setTimeout(() => {
+        window.location.replace(nextHref);
+      }, REDIRECT_DELAY_MS);

Confirm backend tolerates empty redirect_uri for OAuth; if not, gate buttons when redirectUri is missing (see next comment).

Also applies to: 80-85


96-107: Auto-redirect effect dependencies.

Running once is fine here, but add a comment to silence hooks-lint or explicitly disable the rule to avoid churn.

Example:

// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => { /* ... */ }, []);

116-118: Use replace on the login guard.

Prevents stacking an extra history entry.

-  if (isLoggedIn) {
-    return <Navigate to="/logout" />;
-  }
+  if (isLoggedIn) {
+    return <Navigate to="/logout" replace />;
+  }

139-142: Disable OAuth buttons when redirectUri is absent.

Prevents GET /api/oauth/url/... with redirect_uri=, if the server expects a value.

-              <OAuthButton
+              <OAuthButton
                 title="Google"
                 icon={<GoogleIcon />}
                 className="w-full"
                 onClick={() => oauthMutation.mutate("google")}
                 loading={
                   oauthMutation.isPending &&
                   oauthMutation.variables === "google"
                 }
-                disabled={oauthMutation.isPending || loginMutation.isPending}
+                disabled={
+                  oauthMutation.isPending ||
+                  loginMutation.isPending ||
+                  !redirectUri
+                }
               />

Apply the same disabled guard to Github/Generic buttons.

Also applies to: 153-155, 166-168

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 57dd8a6 and 0c18a64.

📒 Files selected for processing (3)
  • frontend/src/pages/login-page.tsx (7 hunks)
  • frontend/src/pages/logout-page.tsx (3 hunks)
  • frontend/src/pages/totp-page.tsx (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
frontend/src/pages/logout-page.tsx (2)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/pages/totp-page.tsx (1)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/pages/login-page.tsx (3)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/lib/hooks/use-is-mounted.ts (1)
  • useIsMounted (3-15)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
frontend/src/pages/totp-page.tsx (1)

15-15: Consistent timer pattern with cleanup — looks good.

Matches the login/logout pattern and prevents stray redirects.

Also applies to: 26-27, 39-44, 52-57

@steveiliop56
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 1, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
frontend/src/pages/continue-page.tsx (1)

34-38: Normalize hostnames (lowercase, strip trailing dot) to avoid false warnings

Treat EXAMPLE.COM and example.com. as trusted equivalents of example.com. Improves UX without weakening security.

Apply:

+  const normalizeHost = (h: string) => h.toLowerCase().replace(/\.$/, "");
+  const trustedBase = normalizeHost(rootDomain);
+  const redirectHost = redirectUriObj !== null ? normalizeHost(redirectUriObj.hostname) : "";
-  const isTrustedRedirectUri =
-    redirectUriObj !== null
-      ? redirectUriObj.hostname === rootDomain ||
-        redirectUriObj.hostname.endsWith(`.${rootDomain}`)
-      : false;
+  const isTrustedRedirectUri =
+    redirectUriObj !== null
+      ? redirectHost === trustedBase || redirectHost.endsWith(`.${trustedBase}`)
+      : false;
🧹 Nitpick comments (14)
frontend/src/pages/logout-page.tsx (3)

24-25: Harden timer typing for cross-env compatibility.
Use ReturnType to be safe across DOM/Node typings.

-  const redirectTimer = useRef<number | null>(null);
+  const redirectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

45-51: Good cleanup; tiny null check tweak.
Explicit null check avoids accidental skip if 0 is ever returned.

-      if (redirectTimer.current) clearTimeout(redirectTimer.current);
+      if (redirectTimer.current !== null) clearTimeout(redirectTimer.current);

34-36: Replace assign with replace in logout and continue pages
For consistency and to prevent stale history entries, update in logout-page.tsx and continue-page.tsx:

frontend/src/pages/logout-page.tsx
- window.location.assign("/login");
+ window.location.replace("/login");

Also in frontend/src/pages/continue-page.tsx, change

window.location.assign(redirectUriObj!.toString());

to

window.location.replace(redirectUriObj!.toString());
frontend/src/pages/totp-page.tsx (3)

26-27: Use ReturnType for robust typing.
Keeps types correct in both browser and Node typings.

-  const redirectTimer = useRef<number | null>(null);
+  const redirectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

52-58: Cleanup effect LGTM; minor null check nit.

-      if (redirectTimer.current) clearTimeout(redirectTimer.current);
+      if (redirectTimer.current !== null) clearTimeout(redirectTimer.current);

39-44: Standardize redirect behavior to use replace() across auth flows.
logout-page.tsx (line 35) and continue-page.tsx (line 52) currently call window.location.assign(…); update to window.location.replace(…) to match login-page.tsx and totp-page.tsx.

frontend/src/components/domain-warning/domain-warning.tsx (3)

12-16: Props shape is clear; minor naming nit.
currentUrl appears to be an origin; consider currentOrigin for precision in a future pass (no change required now).


27-27: Slight ARIA enhancement for assertive alert.
Add aria-atomic to ensure screen readers announce a coherent message.

-    <Card role="alert" aria-live="assertive" className="min-w-xs sm:min-w-sm">
+    <Card role="alert" aria-live="assertive" aria-atomic="true" className="min-w-xs sm:min-w-sm">

44-48: Build target URL with URL API to avoid edge cases.
Avoid manual string concat and double slashes; easier param handling.

-          onClick={() =>
-            window.location.assign(
-              `${appUrl}/login?redirect_uri=${encodeURIComponent(redirectUri || "")}`,
-            )
-          }
+          onClick={() => {
+            const url = new URL("/login", appUrl);
+            if (redirectUri) url.searchParams.set("redirect_uri", redirectUri);
+            window.location.assign(url.toString());
+          }}
internal/controller/context_controller.go (1)

94-95: Handle parse failures defensively (even if validated upstream).
Low-cost guard to prevent panics/malformed responses if startup validation changes.

-	appUrl, _ := url.Parse(controller.Config.AppURL) // no need to check error, validated on startup
+	appUrl, err := url.Parse(controller.Config.AppURL) // validated on startup; still guard
+	if err != nil || appUrl.Scheme == "" || appUrl.Host == "" {
+		log.Error().Err(err).Str("appURL", controller.Config.AppURL).Msg("Invalid AppURL")
+		c.JSON(200, AppContextResponse{
+			Status:              200,
+			Message:             "Success",
+			ConfiguredProviders: controller.Config.ConfiguredProviders,
+			Title:               controller.Config.Title,
+			GenericName:         controller.Config.GenericName,
+			AppURL:              controller.Config.AppURL,
+			RootDomain:          controller.Config.RootDomain,
+			ForgotPasswordMessage: controller.Config.ForgotPasswordMessage,
+			BackgroundImage:       controller.Config.BackgroundImage,
+			OAuthAutoRedirect:     controller.Config.OAuthAutoRedirect,
+		})
+		return
+	}
frontend/src/pages/continue-page.tsx (4)

50-53: Prefer replace() and guard redirectUriObj

Replace avoids polluting history/back-loop; add a minimal null guard.

-  const handleRedirect = () => {
-    setLoading(true);
-    window.location.assign(redirectUriObj!.toString());
-  };
+  const handleRedirect = () => {
+    if (!redirectUriObj) return;
+    setLoading(true);
+    window.location.replace(redirectUriObj.toString());
+  };

55-79: Effect deps: either annotate intent or make it lint-clean

If react-hooks/exhaustive-deps is enabled, consider wrapping handleRedirect in useCallback and listing deps, or add an inline disable with rationale to keep it “run-once”.

Example:

-  useEffect(() => {
+  // Intentional: run-once auto-redirect gate
+  // eslint-disable-next-line react-hooks/exhaustive-deps
+  useEffect(() => {
     ...
-  }, []);
+  }, []);

120-124: Use replace: true when cancelling to logout

Avoids returning to the warning page via Back.

-          <Button
-            onClick={() => navigate("/logout")}
+          <Button
+            onClick={() => navigate("/logout", { replace: true })}
             variant="outline"
             disabled={loading}
           >

154-157: Same here: replace on logout

Consistent UX for cancel action.

-          <Button
-            onClick={() => navigate("/logout")}
+          <Button
+            onClick={() => navigate("/logout", { replace: true })}
             variant="outline"
             disabled={loading}
           >
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0c18a64 and c80c37b.

📒 Files selected for processing (9)
  • frontend/src/App.tsx (1 hunks)
  • frontend/src/components/domain-warning/domain-warning.tsx (1 hunks)
  • frontend/src/lib/i18n/locales/en-US.json (2 hunks)
  • frontend/src/lib/i18n/locales/en.json (2 hunks)
  • frontend/src/pages/continue-page.tsx (4 hunks)
  • frontend/src/pages/login-page.tsx (7 hunks)
  • frontend/src/pages/logout-page.tsx (3 hunks)
  • frontend/src/pages/totp-page.tsx (3 hunks)
  • internal/controller/context_controller.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • frontend/src/lib/i18n/locales/en.json
  • frontend/src/pages/login-page.tsx
  • frontend/src/lib/i18n/locales/en-US.json
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-01T13:58:41.884Z
Learnt from: steveiliop56
PR: steveiliop56/tinyauth#332
File: frontend/src/pages/continue-page.tsx:30-45
Timestamp: 2025-09-01T13:58:41.884Z
Learning: For redirect URI validation in React applications where the URI is only used for navigation (not DOM rendering), DOMPurify sanitization is unnecessary since React handles DOM sanitization and the URI isn't rendered. The critical security measure is explicit protocol validation to prevent javascript: and data: URL attacks.

Applied to files:

  • frontend/src/pages/continue-page.tsx
📚 Learning: 2025-09-01T13:52:04.446Z
Learnt from: steveiliop56
PR: steveiliop56/tinyauth#332
File: frontend/src/pages/continue-page.tsx:30-45
Timestamp: 2025-09-01T13:52:04.446Z
Learning: The URL constructor in JavaScript does not reject dangerous schemes like `javascript:` or `data:` - it successfully parses them into URL objects with the corresponding protocol property. Additional scheme validation is required to prevent XSS attacks through malicious redirect URIs.

Applied to files:

  • frontend/src/pages/continue-page.tsx
🧬 Code graph analysis (5)
frontend/src/components/domain-warning/domain-warning.tsx (1)
frontend/src/components/ui/card.tsx (6)
  • Card (85-85)
  • CardTitle (88-88)
  • CardDescription (90-90)
  • CardTitle (31-39)
  • CardDescription (41-49)
  • Card (5-16)
frontend/src/pages/logout-page.tsx (2)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/pages/continue-page.tsx (3)
frontend/src/context/app-context.tsx (1)
  • useAppContext (36-44)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
frontend/src/lib/utils.ts (1)
  • isValidUrl (8-15)
frontend/src/pages/totp-page.tsx (1)
frontend/src/context/user-context.tsx (1)
  • useUserContext (38-48)
internal/controller/context_controller.go (2)
internal/config/config.go (1)
  • Config (17-56)
internal/controller/oauth_controller.go (5)
  • Config (29-34)
  • controller (93-210)
  • controller (45-49)
  • CSRFCookieName (21-27)
  • controller (51-91)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (18)
frontend/src/pages/logout-page.tsx (2)

14-14: Import change looks good.
Adds necessary hooks for timer cleanup.


52-54: Late guard placement LGTM.
Prevents premature unmount before toasts/mutation wiring; replace avoids extra history.

frontend/src/pages/totp-page.tsx (2)

15-15: Import change looks good.
Brings in hooks needed for timer handling.


59-61: Guard relocation LGTM.
Ensures mutation/toast setup before redirecting away.

frontend/src/components/domain-warning/domain-warning.tsx (3)

23-25: URL param extraction LGTM.
Safe parsing with URLSearchParams; encode later is correct.


26-37: Accessible copy rendering LGTM.
Trans usage with code components and i18n keys is clean.


40-42: Ignore button wiring LGTM.
Variant and handler align with session-dismiss flow.

internal/controller/context_controller.go (5)

4-5: Imports align with new behavior.
fmt and net/url are appropriate for URL normalization.


20-20: Field rename preserves API contract.
Go field OAuth with json:"oauth" keeps wire format stable.


30-31: AppURL/RootDomain exposure LGTM.
Matches frontend needs for domain warning and routing.


41-42: Config struct updates LGTM.
Carries app URL and root domain through to controller cleanly.


77-77: Context field usage LGTM.
Assumes utils.Context has OAuth bool; consistent naming reduces confusion.

frontend/src/App.tsx (1)

8-8: Replace-based redirects LGTM.
Prevents redundant history entries for root routing; consistent with page-level guards.

Also applies to: 11-11

frontend/src/pages/continue-page.tsx (5)

39-43: Good: explicit http/https allowlist

Solid defense; blocks javascript:, data:, file:, etc.


44-48: Good: HTTPS→HTTP downgrade detection

Clear, correct check using window.location.protocol.


66-78: Nice: timers are cleared on unmount

Prevents leaks/late state updates.


81-88: Login redirect looks good

Query param is safely encoded; replace prevents back-nav oddities.


90-92: Early reject of invalid/scheme is correct

Cleanly exits flows that shouldn’t proceed.

Comment thread frontend/src/pages/continue-page.tsx
Comment thread internal/controller/context_controller.go
@steveiliop56 steveiliop56 merged commit b9e3571 into main Sep 1, 2025
7 of 8 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Sep 1, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Jan 29, 2026
@Rycochet Rycochet deleted the feat/domain-warning branch April 1, 2026 16:08
@coderabbitai coderabbitai Bot mentioned this pull request Apr 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant