Skip to content

feat(auth): protect deeplinked screens and return to them after login - #183

Open
fernandatoledo wants to merge 11 commits into
masterfrom
feat/protect-deeplinked-screens-and-return-to
Open

fernandatoledo wants to merge 11 commits into
masterfrom
feat/protect-deeplinked-screens-and-return-to

Conversation

@fernandatoledo

@fernandatoledo fernandatoledo commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Jira board reference:


What does this do?

Deep links into protected screens now send a logged-out user to sign-in, show "Sign in to open this link.", and take them to the linked screen after they log in instead of /, opened on top of the tabs so back returns to the app. feed/[id] and feed/add-post move under the authenticated Stack.Protected guard (they were reachable without a session), and the guarded screen lists now live in src/lib/auth/deep-link-path.ts and are rendered from there. The app scheme is also suffixed per environment (RootstrapApp.development, .qa, .staging; production stays RootstrapApp) so several builds can be installed side by side.


Why did you do this?

Opening a link to a protected screen while logged out lost the target: after login the user always landed on /. Using the same scheme for every environment meant a link could open the wrong installed build.

Who/what does this impact?

  • Incoming links on native: a new src/app/+native-intent.tsx records the link in an in-memory store (src/lib/auth/pending-deep-link.ts) and, when there is no valid session, sends the user straight to the guard's fallback (/sign-in, or /onboarding on first launch) so the protected screen is never pushed. The session check is shared with AuthProvider through hasValidSession(), and when a link finds the stored token expired, syncSession() makes a running AuthProvider drop it too, so the guards and +native-intent agree. Only links that resolve to a protected route are remembered: isReturnToPath() matches an allow-list built from AUTHENTICATED_SCREENS and APP_TAB_SCREENS, so public, auth and unknown routes open unchanged. A test walks src/app and fails when a route file is not classified. The link is dropped on onboarding, when the logged-out user leaves the auth screens, and when a newer link arrives.
  • Route guards in src/app/_layout.tsx: the guards always send an authenticated user to /, and PendingDeepLinkHandler then pushes the pending link once the tabs are showing and the session is valid, so the linked screen keeps a back stack (header back, swipe-back, Android back). Also the sign-in screen (LoginForm gets an optional notice). While auth is hydrating the root layout now renders nothing and keeps the splash, instead of an unguarded <Stack />; the splash is hidden there once auth is ready (it used to be hidden from (app)/_layout.tsx, which never mounts in that window anymore).
  • Native config: dev, qa and staging builds register a new scheme, so existing dev clients must be rebuilt, and links configured outside the app (push payloads, emails, OAuth redirect URIs) need the per-environment scheme. Docs updated in guides/navigation.mdx, agent_docs/architecture.md and REVIEW.md.

Layer 2: Risk Classification

Author applies a risk label when opening the PR. When in doubt, escalate.

Label When to use
risk:low Config, copy, minor UI tweaks. Low blast radius.
risk:medium Feature work, refactors touching multiple files.
risk:high Auth, payments, migrations, security-sensitive code.

Setup

  • Create risk:low, risk:medium, risk:high labels in the repo
  • Add risk criteria to contributing guide or PR template
  • Add reminder in PR template to apply the label before requesting review
  • Define who can override/escalate (suggested: tech lead)

How did you test this?

pnpm check-all passes (lint, type-check, translations, 45 suites / 404 tests). APP_ENV=<env> npx expo config --type public shows the expected scheme for each environment. On the iOS Simulator with a development build (old scheme RootstrapApp) and Maestro:

  • logged out, feed/1 and feed/add-post land on sign-in with the message, both on cold start and with the app running;
  • links to sign-up and forgot-password open normally with no message afterwards, and an unknown route opens the 404 without asking to sign in;
  • with onboarding pending, onboarding wins and the link is discarded.

The redirect to the link after login was checked on the simulator against a local mock of the sign-in endpoint (the development backend didn't accept the test login):

  • logged out, a link to feed/add-post → sign-in → login → Add Post with a "Feed" back button, and back returns to the tabs; same for feed/1 → Post;

  • logged in with a 60-second token left to expire with the app in the foreground, a link to feed/add-post goes to sign-in with the message instead of opening the screen with a dead token.

  • Tested on iOS

  • Tested on Android

  • Tested on a small device

  • Tested on a real device

  • Tested all flows related with this PR changes

  • Tested accessibility

  • Added tests


Notes:

  • Web is unchanged apart from the guard: +native-intent only runs on native, so on web a logged-out user is still sent to sign-in but the link is not restored.
  • expo-router/testing-library's renderRouter can't run in this repo (transitive react-test-renderer 19.1 vs React 19.3), so the guard tests mock Stack.Protected. A follow-up could align react-test-renderer and add an end-to-end router test for the post-login redirect.

Screenshots / Previews

Logged out: cold start from a link to feed/1 lands on sign-in with the message, a link to sign-up opens normally, a link to sign-in shows no message, and a link to feed/add-post goes straight to sign-in without rendering the protected screen.

deeplink-protected-screens-v2.mp4

Return to the link after login: logged out, a link to feed/add-post opens sign-in with the message, and after signing in the app lands on Add Post. Recorded against a local mock of the sign-in endpoint.

deeplink-login-return-to.mp4

@fernandatoledo fernandatoledo added the risk:high Auth, payments, migrations, security-sensitive code. label Nov 26, 2026
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

💯 Test Coverage

Lines Statements Branches Functions
Coverage: 75%
75.86% (635/837) 73.31% (294/401) 70.35% (235/334)

😎 Tests Results

Tests Skipped Failures Errors Time
458 0 💤 0 ❌ 0 🔥 29.91s ⏱️
👀 Tests Details • (75%)
File% Stmts% Branch% Funcs% LinesUncovered Line #s
All files75.8673.3170.3575.84 
src/app75.797.2954.2875.7 
   _layout.tsx10096100100159
   sign-in.tsx100100100100 
src/app/(app)37.9337.523.0737.93 
   _layout.tsx78.571005078.5717–25
src/app/feed66.661005066.66 
   [id].tsx100100100100 
src/components97.4310087.597.43 
   login-form.tsx10010066.66100 

… routes

- Guards always send an authenticated user to `/`. PendingDeepLinkHandler then
  pushes the pending link on top of `(app)`, so the linked screen keeps a back stack.
- isReturnToPath matches an allow-list of protected routes, so unknown routes open
  the 404 instead of asking for sign-in. A test fails when a route is not classified.
- AuthProvider re-checks the stored token on foreground and when +native-intent
  finds it expired, so the guards and +native-intent agree on the session.
- runtimeVersion uses the fingerprint policy, so updates only reach builds that
  register the same scheme.
- Drop the AppState re-check: logging a user out on foreground with no notice
  is a product decision. Links still sync the session through syncSession().
- Restore the appVersion runtime policy. expo-updates is not installed, and the
  fingerprint hashes extra, which can strand OTAs built from a different env file.
- Make the unmount test fail when the session listener is not removed.
… fix sonar gate

- Store and push the normalized path from toReturnToPath(), so the router
  opens the screen that was validated (/%28app%29/settings opens /settings).
- Move the link handling into rememberProtectedLink() and call it once at
  startup on web, where +native-intent does not run.
- Turn PendingDeepLinkHandler into the useOpenPendingDeepLink hook, clearing
  the typescript:S100 issue that pushed new_minor_violations over the gate.
@fernandatoledo
fernandatoledo marked this pull request as ready for review November 30, 2026 14:49
@fernandatoledo
fernandatoledo requested a review from a team as a code owner November 30, 2026 14:49
@fernandatoledo
fernandatoledo requested review from amaury901130 and asdolo and a balanced review from Copilot November 30, 2026 14:49

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Active issues can clear protected links before sign-in opens on public screens and misinterpret /--/ in queries or fragments, losing the intended post-login destination.

2 open issues
What changed in this PR

Overall Review: ai:serious

This PR extends the template’s centralized authentication routing to protect deep-linked screens and restore their destinations after login.

Changes:

  • Adds protected-route classification, pending-link handling, session synchronization, and a translated sign-in notice.
  • Moves feed screens behind authentication guards and keeps the splash visible during auth hydration.
  • Introduces environment-specific app schemes, with supporting tests and documentation.
File Description
src/​translations/​en.json Adds the deep-link sign-in notice.
src/​lib/​hooks/​use-is-first-time.tsx Exposes synchronous onboarding-state lookup.
src/​lib/​auth/​pending-deep-link.ts Stores and clears the pending destination.
src/​lib/​auth/​get-fallback-route.ts Types fallback routes as router paths.
src/​lib/​auth/​deep-link-path.ts Centralizes route lists and link normalization.
src/​components/​providers/​auth.tsx Shares session validation and synchronization.
src/​components/​login-form.tsx Supports an optional notice.
src/​app/​sign-in.tsx Displays the translated pending-link notice.
src/​app/​+native-intent.tsx Intercepts protected links before native navigation.
src/​app/​(app)/​_layout.tsx Removes tab-level splash handling.
src/​app/​_layout.tsx Integrates guards, link restoration, and splash handling.
REVIEW.md Documents guarded-route and pending-link rules.
env.js Suffixes nonproduction app schemes.
docs/​src/​content/​docs/​guides/​navigation.mdx Documents schemes, link examples, and rebuild requirements.
docs/​src/​content/​docs/​getting-started/​environment-vars-config.mdx Explains environment-specific scheme suffixes.
agent_docs/​architecture.md Describes the protected-link lifecycle.
__tests__/​lib/​hooks/​use-is-first-time.test.tsx Tests synchronous onboarding lookup.
__tests__/​lib/​auth/​pending-deep-link.test.ts Tests pending-link storage and clearing.
__tests__/​lib/​auth/​get-fallback-route.test.ts Adds a trailing blank line only.
__tests__/​lib/​auth/​deep-link-path.test.ts Tests normalization, validation, and route classification.
__tests__/​env.test.ts Tests scheme suffixes across environments.
__tests__/​components/​providers/​auth.test.tsx Tests session validation and synchronization.
__tests__/​components/​login-form.test.tsx Tests optional notice rendering.
__tests__/​app/​sign-in.test.tsx Tests notice lifecycle, login failure, and translation.
__tests__/​app/​root-layout.test.tsx Tests guards, restoration, hydration, and web startup.
__tests__/​app/​native-intent.test.ts Tests incoming-link handling across session states.
__tests__/​app/​_layout.test.tsx Removes obsolete tab-level splash tests.

Review effort: Balanced

Comment thread src/app/_layout.tsx Resolved
Comment thread src/lib/auth/deep-link-path.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔵 Needs a closer look

First-time users with a stored valid session can bypass onboarding through protected links because the native handler and root authenticated guard do not enforce onboarding precedence.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Enforce onboarding before honoring protected links

src/​app/​+native-intent.tsx:14

ai:serious Onboarding is bypassed when isFirstTime is true but a valid session is stored: this early return forwards a protected link unchanged, and the root authenticated guard allows standalone screens such as feed/add-post without checking onboarding. Unlike the tabs, those screens have no onboarding redirect. Check onboarding before accepting a protected link and make the root guard exclude first-time users so native and web both honor onboarding precedence.

2 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

The auth flow still accepts malformed expiries and leaves stale tokens in the interceptor store, allowing invalid sessions and requests to persist.

2 open issues

Review effort: Lite

Comment thread src/components/providers/auth.tsx Resolved
Comment thread src/components/providers/auth.tsx Resolved
@fernandatoledo

Copy link
Copy Markdown
Collaborator Author

Addressed the onboarding-precedence finding from the latest Copilot review (src/app/+native-intent.tsx:14) in 11d7652:

  • rememberProtectedLink now checks onboarding before the session: on first launch a protected link goes to /onboarding and is not remembered, even when a valid session is stored.
  • The root guard for authenticated screens is now isAuthenticated && !isFirstTime, so standalone screens like feed/add-post and feed/[id] redirect to onboarding for first-time users on both native and web. After onboarding, the existing /sign-in redirect sends a logged-in user home.
  • Added tests for a first-time user with a stored session, for both the native intent and the root guards.

@fernandatoledo fernandatoledo added the ai:serious Security concerns, logic errors label Dec 2, 2026
@asdolo
asdolo force-pushed the feat/protect-deeplinked-screens-and-return-to branch from 9180476 to 3a6b631 Compare December 2, 2026 18:52
@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

✅ Good news! We ran Expo Doctor for this PR and everything looks good, Great job!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai:serious Security concerns, logic errors risk:high Auth, payments, migrations, security-sensitive code.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants