tkadkghdlf commited on
Commit
0cb29be
ยท
verified ยท
1 Parent(s): 7d7998b

Sync DemoService f68f5aa130036770ff0822f0b1572d0bf15f82f4

Browse files
main/app/_components/BottomNav.tsx CHANGED
@@ -11,8 +11,7 @@ import {
11
  PROFILE_IMAGE_UPDATED_EVENT,
12
  } from "../_utils/profileImage";
13
  import { motionPresets, subtleTapMotion, tapMotion } from "../_utils/motion";
14
- import { clearStoredSession, restoreSession } from "../_utils/sessionRestore";
15
- import LoginRequiredDialog from "./LoginRequiredDialog";
16
 
17
  const MAIN_COLOR = "#1E40AF";
18
  const INACTIVE_COLOR = "#4B5563";
@@ -103,7 +102,6 @@ export default function BottomNav() {
103
  const dragControls = useDragControls();
104
  const [profileImage, setProfileImage] = useState("");
105
  const [isMyMenuOpen, setIsMyMenuOpen] = useState(false);
106
- const [isLoginRequiredOpen, setIsLoginRequiredOpen] = useState(false);
107
 
108
  useEffect(() => {
109
  const syncProfileImage = () => {
@@ -166,7 +164,7 @@ export default function BottomNav() {
166
  // Let the user sign in again when the session cannot be refreshed.
167
  }
168
 
169
- setIsLoginRequiredOpen(true);
170
  };
171
 
172
  const startRouteSearch = () => {
@@ -430,10 +428,6 @@ export default function BottomNav() {
430
  </motion.div>
431
  ) : null}
432
  </AnimatePresence>
433
- <LoginRequiredDialog
434
- open={isLoginRequiredOpen}
435
- onDismiss={() => setIsLoginRequiredOpen(false)}
436
- />
437
  </>
438
  );
439
  }
 
11
  PROFILE_IMAGE_UPDATED_EVENT,
12
  } from "../_utils/profileImage";
13
  import { motionPresets, subtleTapMotion, tapMotion } from "../_utils/motion";
14
+ import { clearStoredSession, requestLogin, restoreSession } from "../_utils/sessionRestore";
 
15
 
16
  const MAIN_COLOR = "#1E40AF";
17
  const INACTIVE_COLOR = "#4B5563";
 
102
  const dragControls = useDragControls();
103
  const [profileImage, setProfileImage] = useState("");
104
  const [isMyMenuOpen, setIsMyMenuOpen] = useState(false);
 
105
 
106
  useEffect(() => {
107
  const syncProfileImage = () => {
 
164
  // Let the user sign in again when the session cannot be refreshed.
165
  }
166
 
167
+ requestLogin();
168
  };
169
 
170
  const startRouteSearch = () => {
 
428
  </motion.div>
429
  ) : null}
430
  </AnimatePresence>
 
 
 
 
431
  </>
432
  );
433
  }
main/app/_components/LoginRequiredDialog.tsx CHANGED
@@ -2,13 +2,16 @@
2
 
3
  import { useRouter } from "next/navigation";
4
  import MotionDialog from "./MotionDialog";
 
5
 
6
  export default function LoginRequiredDialog({
7
  open,
8
  onDismiss,
 
9
  }: {
10
  open: boolean;
11
  onDismiss: () => void;
 
12
  }) {
13
  const router = useRouter();
14
 
@@ -20,10 +23,12 @@ export default function LoginRequiredDialog({
20
  panelClassName="w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl"
21
  >
22
  <h2 id="login-required-title" className="text-lg font-bold text-black">
23
- ๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ด์š”
24
  </h2>
25
  <p className="mt-2 text-sm leading-6 text-[#525252]">
26
- ๋กœ๊ทธ์ธ ํ›„ ์ด์šฉํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋กœ๊ทธ์ธ ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ• ๊นŒ์š”?
 
 
27
  </p>
28
  <div className="mt-6 flex gap-3">
29
  <button
@@ -36,7 +41,10 @@ export default function LoginRequiredDialog({
36
  <button
37
  type="button"
38
  className="min-h-11 flex-1 rounded-lg bg-[#111111] px-4 text-sm font-bold text-white transition hover:bg-[#111111]"
39
- onClick={() => router.push("/login")}
 
 
 
40
  >
41
  ๋กœ๊ทธ์ธํ•˜๊ธฐ
42
  </button>
 
2
 
3
  import { useRouter } from "next/navigation";
4
  import MotionDialog from "./MotionDialog";
5
+ import { clearStoredSession } from "../_utils/sessionRestore";
6
 
7
  export default function LoginRequiredDialog({
8
  open,
9
  onDismiss,
10
+ reason = "missing",
11
  }: {
12
  open: boolean;
13
  onDismiss: () => void;
14
+ reason?: "missing" | "expired";
15
  }) {
16
  const router = useRouter();
17
 
 
23
  panelClassName="w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl"
24
  >
25
  <h2 id="login-required-title" className="text-lg font-bold text-black">
26
+ {reason === "expired" ? "๋กœ๊ทธ์ธ์ด ๋งŒ๋ฃŒ๋˜์—ˆ์–ด์š”" : "๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ด์š”"}
27
  </h2>
28
  <p className="mt-2 text-sm leading-6 text-[#525252]">
29
+ {reason === "expired"
30
+ ? "๋กœ๊ทธ์ธ ์ƒํƒœ๊ฐ€ ๋งŒ๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ๊ณ„์† ์ด์šฉํ•˜๋ ค๋ฉด ๋‹ค์‹œ ๋กœ๊ทธ์ธํ•ด ์ฃผ์„ธ์š”."
31
+ : "๋กœ๊ทธ์ธ ํ›„ ์ด์šฉํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋กœ๊ทธ์ธ ํ™”๋ฉด์œผ๋กœ ์ด๋™ํ• ๊นŒ์š”?"}
32
  </p>
33
  <div className="mt-6 flex gap-3">
34
  <button
 
41
  <button
42
  type="button"
43
  className="min-h-11 flex-1 rounded-lg bg-[#111111] px-4 text-sm font-bold text-white transition hover:bg-[#111111]"
44
+ onClick={() => {
45
+ clearStoredSession();
46
+ router.push("/login");
47
+ }}
48
  >
49
  ๋กœ๊ทธ์ธํ•˜๊ธฐ
50
  </button>
main/app/_components/SessionGuard.tsx CHANGED
@@ -1,73 +1,130 @@
1
  "use client";
2
 
3
- import { useCallback, useEffect, useState, type ReactNode } from "react";
4
  import { usePathname, useRouter } from "next/navigation";
5
- import { clearStoredSession, restoreSession } from "../_utils/sessionRestore";
 
 
 
 
 
 
 
 
 
6
  import LoginRequiredDialog from "./LoginRequiredDialog";
7
 
8
- const PUBLIC_PATHS = new Set(["/", "/login", "/signup", "/password-reset", "/lobby"]);
 
9
 
10
- /**
11
- * Session verification is intentionally non-blocking: the current application
12
- * surface stays mounted while tokens are checked/refreshed. The lobby is public,
13
- * but every other page is covered by the login-required dialog when its session
14
- * cannot be restored.
15
- */
16
  export default function SessionGuard({ children }: { children: ReactNode }) {
17
  const pathname = usePathname();
18
  const router = useRouter();
19
  const isPublic = PUBLIC_PATHS.has(pathname);
20
- const [isLoginRequiredOpen, setIsLoginRequiredOpen] = useState(false);
 
21
 
22
- const blockProtectedPage = useCallback(() => {
23
- clearStoredSession();
24
- setIsLoginRequiredOpen(true);
25
- }, []);
26
-
27
- const verify = useCallback(async () => {
28
- if (isPublic) return;
29
- try {
30
- const valid = await restoreSession();
31
- if (!valid) blockProtectedPage();
32
- } catch {
33
- // An expired session that cannot be refreshed must not keep protected
34
- // screens usable behind cached client data.
35
- blockProtectedPage();
36
- }
37
- }, [blockProtectedPage, isPublic]);
38
 
39
  useEffect(() => {
40
- if (isPublic) {
41
- setIsLoginRequiredOpen(false);
42
- }
43
- void verify();
44
  if (isPublic) return;
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  const retry = () => void verify();
47
  const visible = () => {
48
  if (document.visibilityState === "visible") retry();
49
  };
50
- const interval = window.setInterval(retry, 5 * 60 * 1000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
 
 
 
 
52
  window.addEventListener("online", retry);
53
  window.addEventListener("focus", retry);
54
  document.addEventListener("visibilitychange", visible);
 
 
 
55
  return () => {
 
 
56
  window.clearInterval(interval);
 
 
 
 
57
  window.removeEventListener("online", retry);
58
  window.removeEventListener("focus", retry);
59
  document.removeEventListener("visibilitychange", visible);
60
  };
61
- }, [isPublic, verify]);
62
 
63
  return (
64
  <>
65
  {children}
66
  <LoginRequiredDialog
67
- open={!isPublic && isLoginRequiredOpen}
 
68
  onDismiss={() => {
69
- setIsLoginRequiredOpen(false);
70
- router.replace("/lobby");
 
71
  }}
72
  />
73
  </>
 
1
  "use client";
2
 
3
+ import { useEffect, useRef, useState, type ReactNode } from "react";
4
  import { usePathname, useRouter } from "next/navigation";
5
+ import {
6
+ clearStoredSession,
7
+ getAccessTokenExpiry,
8
+ getStoredAccessToken,
9
+ restoreSession,
10
+ SESSION_CHANGED_EVENT,
11
+ SESSION_EXPIRED_EVENT,
12
+ LOGIN_REQUIRED_EVENT,
13
+ } from "../_utils/sessionRestore";
14
+ import { installSessionFetchObserver } from "../_utils/sessionFetch";
15
  import LoginRequiredDialog from "./LoginRequiredDialog";
16
 
17
+ const PUBLIC_PATHS = new Set(["/", "/login", "/signup", "/password-reset"]);
18
+ type LoginReason = "missing" | "expired";
19
 
 
 
 
 
 
 
20
  export default function SessionGuard({ children }: { children: ReactNode }) {
21
  const pathname = usePathname();
22
  const router = useRouter();
23
  const isPublic = PUBLIC_PATHS.has(pathname);
24
+ const [loginReason, setLoginReason] = useState<LoginReason | null>(null);
25
+ const allowGuestLobby = useRef(false);
26
 
27
+ useEffect(() => installSessionFetchObserver(), []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  useEffect(() => {
30
+ setLoginReason(null);
 
 
 
31
  if (isPublic) return;
32
 
33
+ let cancelled = false;
34
+ let checking = false;
35
+ let timer: ReturnType<typeof setTimeout> | undefined;
36
+ const snapshot = () => JSON.stringify([getStoredAccessToken(), localStorage.getItem("refresh_token")]);
37
+ let lastSession = snapshot();
38
+
39
+ const schedule = (delay: number) => {
40
+ clearTimeout(timer);
41
+ timer = setTimeout(() => void verify(), Math.min(Math.max(delay, 1000), 2_147_483_647));
42
+ };
43
+
44
+ const verify = async (force = false) => {
45
+ if (cancelled || checking) return;
46
+ checking = true;
47
+ const before = snapshot();
48
+ const hadSession = Boolean(getStoredAccessToken() || localStorage.getItem("refresh_token"));
49
+ try {
50
+ const valid = await restoreSession(force);
51
+ if (cancelled) return;
52
+ if (!valid) {
53
+ if (snapshot() !== before) { schedule(1000); return; }
54
+ clearTimeout(timer);
55
+ if (hadSession) clearStoredSession();
56
+ if (!(pathname === "/lobby" && allowGuestLobby.current)) {
57
+ setLoginReason(current => current ?? (hadSession ? "expired" : "missing"));
58
+ }
59
+ return;
60
+ }
61
+ allowGuestLobby.current = false;
62
+ setLoginReason(null);
63
+ const expiry = getAccessTokenExpiry(getStoredAccessToken());
64
+ schedule(expiry === null ? 30_000 : expiry - Date.now() - 60_000);
65
+ } catch {
66
+ // Keep credentials during connection failures and concurrent login/logout.
67
+ if (!cancelled) schedule(15_000);
68
+ } finally {
69
+ lastSession = snapshot();
70
+ checking = false;
71
+ }
72
+ };
73
+
74
  const retry = () => void verify();
75
  const visible = () => {
76
  if (document.visibilityState === "visible") retry();
77
  };
78
+ const expired = () => {
79
+ allowGuestLobby.current = false;
80
+ setLoginReason("expired");
81
+ };
82
+ const requested = () => {
83
+ allowGuestLobby.current = false;
84
+ setLoginReason(current => current ?? "missing");
85
+ };
86
+ const storage = (event: StorageEvent) => {
87
+ if (event.key === null || event.key === "access_token" || event.key === "refresh_token") retry();
88
+ };
89
+ // Same-tab token removals do not fire a browser storage event.
90
+ const interval = window.setInterval(() => {
91
+ if (snapshot() !== lastSession) retry();
92
+ }, 1000);
93
 
94
+ window.addEventListener(SESSION_EXPIRED_EVENT, expired);
95
+ window.addEventListener(LOGIN_REQUIRED_EVENT, requested);
96
+ window.addEventListener(SESSION_CHANGED_EVENT, retry);
97
+ window.addEventListener("storage", storage);
98
  window.addEventListener("online", retry);
99
  window.addEventListener("focus", retry);
100
  document.addEventListener("visibilitychange", visible);
101
+ // Verify on every route, including the lobby; don't trust token presence alone.
102
+ void verify(true);
103
+
104
  return () => {
105
+ cancelled = true;
106
+ clearTimeout(timer);
107
  window.clearInterval(interval);
108
+ window.removeEventListener(SESSION_EXPIRED_EVENT, expired);
109
+ window.removeEventListener(LOGIN_REQUIRED_EVENT, requested);
110
+ window.removeEventListener(SESSION_CHANGED_EVENT, retry);
111
+ window.removeEventListener("storage", storage);
112
  window.removeEventListener("online", retry);
113
  window.removeEventListener("focus", retry);
114
  document.removeEventListener("visibilitychange", visible);
115
  };
116
+ }, [isPublic, pathname]);
117
 
118
  return (
119
  <>
120
  {children}
121
  <LoginRequiredDialog
122
+ open={!isPublic && loginReason !== null}
123
+ reason={loginReason ?? "missing"}
124
  onDismiss={() => {
125
+ allowGuestLobby.current = true;
126
+ setLoginReason(null);
127
+ if (pathname !== "/lobby") router.replace("/lobby");
128
  }}
129
  />
130
  </>
main/app/_components/SignupLocationPermission.tsx ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { getAppPosition } from "../_utils/nativeLocation";
5
+ import { storeLocationConsent, type LocationConsent } from "../_utils/locationConsent";
6
+
7
+ export default function SignupLocationPermission() {
8
+ const [consent, setConsent] = useState<LocationConsent | null>(null);
9
+ const [status, setStatus] = useState<"idle" | "requesting" | "granted" | "error">("idle");
10
+ const [message, setMessage] = useState("");
11
+ const requestVersion = useRef(0);
12
+
13
+ useEffect(() => () => { requestVersion.current += 1; }, []);
14
+
15
+ const requestPermission = async () => {
16
+ const version = ++requestVersion.current;
17
+ setConsent("allowed");
18
+ storeLocationConsent("allowed");
19
+ setStatus("requesting");
20
+ setMessage("");
21
+ try {
22
+ await getAppPosition();
23
+ if (version !== requestVersion.current) return;
24
+ setStatus("granted");
25
+ setMessage("์œ„์น˜ ๊ถŒํ•œ์„ ํ—ˆ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ๋กœ๋น„์—์„œ ํ˜„์žฌ ์ง€์—ญ์˜ ๋‚ ์”จ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์–ด์š”.");
26
+ } catch (error) {
27
+ if (version !== requestVersion.current) return;
28
+ const code = (error as GeolocationPositionError)?.code;
29
+ const reason = error instanceof Error ? error.message : "";
30
+ setConsent("declined");
31
+ storeLocationConsent("declined");
32
+ setStatus("error");
33
+ setMessage(code === 1 || reason === "denied" || reason === "blocked"
34
+ ? "์œ„์น˜ ๊ถŒํ•œ์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ๊ฐ€์ž…์€ ๊ณ„์†ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋‚˜์ค‘์— ๋ธŒ๋ผ์šฐ์ € ๋˜๋Š” ์•ฑ ์„ค์ •์—์„œ ํ—ˆ์šฉํ•  ์ˆ˜ ์žˆ์–ด์š”."
35
+ : "ํ˜„์žฌ ์œ„์น˜๋ฅผ ํ™•์ธํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ๊ฐ€์ž…์€ ๊ณ„์†ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์œ„์น˜ ์„œ๋น„์Šค๋ฅผ ์ผœ๊ณ  ๋กœ๋น„์—์„œ ๋‹ค์‹œ ์‹œ๋„ํ•  ์ˆ˜ ์žˆ์–ด์š”.");
36
+ }
37
+ };
38
+
39
+ const declinePermission = () => {
40
+ requestVersion.current += 1;
41
+ setConsent("declined");
42
+ storeLocationConsent("declined");
43
+ setStatus("idle");
44
+ setMessage("์œ„์น˜ ๊ถŒํ•œ ์—†์ด๋„ ํšŒ์›๊ฐ€์ž…ํ•  ์ˆ˜ ์žˆ์–ด์š”. ๋กœ๋น„์—์„œ ์›ํ•  ๋•Œ ๋‹ค์‹œ ํ—ˆ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.");
45
+ };
46
+
47
+ const clearSelection = () => {
48
+ requestVersion.current += 1;
49
+ setConsent(null);
50
+ storeLocationConsent("declined");
51
+ setStatus("idle");
52
+ setMessage("");
53
+ };
54
+
55
+ return (
56
+ <fieldset className="w-full min-w-0 rounded-xl border border-black/10 bg-[#fafafa] p-4" aria-describedby="signup-location-description">
57
+ <legend className="px-1 text-sm font-bold text-black">์œ„์น˜ ๊ถŒํ•œ ํ—ˆ์šฉ <span className="font-normal text-[#666]">(์„ ํƒ)</span></legend>
58
+ <ul className="list-disc space-y-1 pl-5 text-sm leading-6 text-[#525252]">
59
+ <li>ํ˜„์žฌ ์œ„์น˜๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋กœ๋น„์— ์ง€์—ญ๋ณ„ ๋‚ ์”จ๋ฅผ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค.</li>
60
+ <li>๋‚ด ์ฃผ๋ณ€ ๋Ÿฌ๋‹ ๊ฒฝ๋กœ๋ฅผ ์ถ”์ฒœํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.</li>
61
+ </ul>
62
+ <p id="signup-location-description" className="mt-2 text-xs leading-5 text-[#666]">
63
+ ํ—ˆ์šฉํ•จ์„ ์„ ํƒํ•˜๋ฉด ํ•„์š”ํ•œ ๊ฒฝ์šฐ ๋ธŒ๋ผ์šฐ์ € ๋˜๋Š” ์•ฑ์˜ ์œ„์น˜ ๊ถŒํ•œ ์ฐฝ์ด ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.
64
+ ํ—ˆ์šฉํ•˜์ง€ ์•Š์•„๋„ ํšŒ์›๊ฐ€์ž…ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
65
+ </p>
66
+ <div className="mt-3 flex flex-wrap items-center gap-x-6 gap-y-2">
67
+ <label className="inline-flex min-h-11 cursor-pointer items-center gap-2 text-sm text-black">
68
+ <span className="relative inline-flex h-4 w-4 shrink-0">
69
+ <input type="checkbox" name="signupLocationConsent" value="allowed" checked={consent === "allowed"}
70
+ onChange={event => { if (event.target.checked) void requestPermission(); else clearSelection(); }}
71
+ disabled={status === "requesting"}
72
+ className="peer m-0 h-4 w-4 cursor-pointer appearance-none rounded-[2px] border border-solid border-black bg-white focus-visible:ring-2 focus-visible:ring-black focus-visible:ring-offset-2 disabled:opacity-50" />
73
+ <svg aria-hidden="true" viewBox="0 0 16 16" className="pointer-events-none absolute inset-0 hidden h-4 w-4 text-black peer-checked:block">
74
+ <path d="m3.5 8 3 3 6-6" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
75
+ </svg>
76
+ </span>
77
+ ํ—ˆ์šฉํ•จ
78
+ </label>
79
+ <label className="inline-flex min-h-11 cursor-pointer items-center gap-2 text-sm text-black">
80
+ <span className="relative inline-flex h-4 w-4 shrink-0">
81
+ <input type="checkbox" name="signupLocationConsent" value="declined" checked={consent === "declined"}
82
+ onChange={event => { if (event.target.checked) declinePermission(); else clearSelection(); }}
83
+ className="peer m-0 h-4 w-4 cursor-pointer appearance-none rounded-[2px] border border-solid border-black bg-white focus-visible:ring-2 focus-visible:ring-black focus-visible:ring-offset-2" />
84
+ <svg aria-hidden="true" viewBox="0 0 16 16" className="pointer-events-none absolute inset-0 hidden h-4 w-4 text-black peer-checked:block">
85
+ <path d="m3.5 8 3 3 6-6" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
86
+ </svg>
87
+ </span>
88
+ ํ—ˆ์šฉ ์•ˆ ํ•จ
89
+ </label>
90
+ </div>
91
+ {status === "requesting" || message ? (
92
+ <p role="status" className="mt-2 break-words text-sm leading-6 text-[#525252]">
93
+ {status === "requesting" ? "์œ„์น˜ ๊ถŒํ•œ์„ ํ™•์ธํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค..." : message}
94
+ </p>
95
+ ) : null}
96
+ </fieldset>
97
+ );
98
+ }
main/app/_utils/locationConsent.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export type LocationConsent = "allowed" | "declined";
2
+ export const LOCATION_CONSENT_KEY = "rts:location-consent";
3
+ let currentConsent: LocationConsent | null = null;
4
+
5
+ export function readLocationConsent(): LocationConsent | null {
6
+ if (typeof window === "undefined") return null;
7
+ try {
8
+ const stored = localStorage.getItem(LOCATION_CONSENT_KEY);
9
+ return stored === "allowed" || stored === "declined" ? stored : currentConsent;
10
+ } catch { return currentConsent; }
11
+ }
12
+
13
+ export function storeLocationConsent(consent: LocationConsent): void {
14
+ currentConsent = consent;
15
+ try { localStorage.setItem(LOCATION_CONSENT_KEY, consent); } catch { /* Keep the choice for this visit. */ }
16
+ }
main/app/_utils/sessionFetch.ts ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { expireStoredSession, getStoredAccessToken, restoreSession } from "./sessionRestore";
2
+
3
+ /** Observe authenticated API failures across pages, including background requests. */
4
+ export function installSessionFetchObserver(): () => void {
5
+ const originalFetch = window.fetch;
6
+ const apiOrigin = new URL(process.env.NEXT_PUBLIC_API_BASE_URL || location.origin, location.origin).origin;
7
+
8
+ const sessionFetch: typeof fetch = async (input, init) => {
9
+ const request = input instanceof Request ? input.clone() : input;
10
+ const url = new URL(input instanceof Request ? input.url : String(input), location.origin);
11
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
12
+ const token = headers.get("Authorization")?.match(/^Bearer\s+(.+)$/i)?.[1];
13
+ const shouldCheck = token && url.origin === apiOrigin && url.pathname.startsWith("/api/v1/") &&
14
+ !/^\/api\/v1\/auth\/(refresh|session)(?:\/|$)/.test(url.pathname) &&
15
+ !url.pathname.endsWith("/logout");
16
+
17
+ const response = await originalFetch.call(window, input, init);
18
+ if (!shouldCheck || response.status !== 401 || getStoredAccessToken() !== token) return response;
19
+
20
+ try {
21
+ if (!await restoreSession(true)) {
22
+ if (getStoredAccessToken() === token) expireStoredSession();
23
+ return response;
24
+ }
25
+ } catch {
26
+ // A network failure is not proof that the session has expired.
27
+ return response;
28
+ }
29
+
30
+ const refreshedToken = getStoredAccessToken();
31
+ if (!refreshedToken) return response;
32
+ headers.set("Authorization", `Bearer ${refreshedToken}`);
33
+ const retry = await originalFetch.call(window, request, { ...init, headers });
34
+ if (retry.status === 401 && getStoredAccessToken() === refreshedToken) expireStoredSession();
35
+ return retry;
36
+ };
37
+
38
+ window.fetch = sessionFetch;
39
+ return () => {
40
+ if (window.fetch === sessionFetch) window.fetch = originalFetch;
41
+ };
42
+ }
main/app/_utils/sessionRestore.ts CHANGED
@@ -1,14 +1,36 @@
1
  import { clearNativeWearRelayAuth, syncNativeWearRelayAuth } from "./nativeWearBridge";
2
 
3
  let pending: Promise<boolean> | null = null;
4
- // This is only a renewal scheduling hint. Protected APIs still validate JWTs.
5
- export function hasUsableAccessToken(token: string | null): boolean {
6
- if (!token) return false;
 
 
 
 
 
 
 
 
 
 
 
 
7
  try {
8
  const encoded = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
9
  const payload = JSON.parse(atob(encoded));
10
- return typeof payload.exp === "number" && Number.isFinite(payload.exp) && payload.exp * 1000 > Date.now() + 60000;
11
- } catch { return false; }
 
 
 
 
 
 
 
 
 
 
12
  }
13
 
14
  export function clearStoredSession(): void {
@@ -17,6 +39,12 @@ export function clearStoredSession(): void {
17
  localStorage.removeItem("refresh_token");
18
  localStorage.removeItem("session_verified_at");
19
  document.cookie = "access_token=; Path=/; Max-Age=0; SameSite=Lax";
 
 
 
 
 
 
20
  }
21
 
22
  export function restoreSession(force = false): Promise<boolean> {
@@ -55,6 +83,7 @@ async function restore(force = false): Promise<boolean> {
55
  localStorage.setItem("session_verified_at", String(Date.now()));
56
  document.cookie = `access_token=${data.access_token}; Path=/; Max-Age=${data.expires_in ?? 3600}; SameSite=Lax${location.protocol === "https:" ? "; Secure" : ""}`;
57
  syncNativeWearRelayAuth();
 
58
  return true;
59
  } finally { clearTimeout(timeout); }
60
  }
 
1
  import { clearNativeWearRelayAuth, syncNativeWearRelayAuth } from "./nativeWearBridge";
2
 
3
  let pending: Promise<boolean> | null = null;
4
+ export const SESSION_CHANGED_EVENT = "rts:session-changed";
5
+ export const SESSION_EXPIRED_EVENT = "rts:session-expired";
6
+ export const LOGIN_REQUIRED_EVENT = "rts:login-required";
7
+
8
+ export function requestLogin(): void {
9
+ window.dispatchEvent(new Event(LOGIN_REQUIRED_EVENT));
10
+ }
11
+
12
+ export function getStoredAccessToken(): string | null {
13
+ return localStorage.getItem("access_token") ||
14
+ document.cookie.split("; ").find(value => value.startsWith("access_token="))?.slice(13) || null;
15
+ }
16
+
17
+ export function getAccessTokenExpiry(token: string | null): number | null {
18
+ if (!token) return null;
19
  try {
20
  const encoded = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
21
  const payload = JSON.parse(atob(encoded));
22
+ return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1000 : null;
23
+ } catch { return null; }
24
+ }
25
+
26
+ export function notifySessionChanged(): void {
27
+ window.dispatchEvent(new Event(SESSION_CHANGED_EVENT));
28
+ }
29
+
30
+ // This is only a renewal scheduling hint. Protected APIs still validate JWTs.
31
+ export function hasUsableAccessToken(token: string | null): boolean {
32
+ const expiry = getAccessTokenExpiry(token);
33
+ return expiry !== null && expiry > Date.now() + 60000;
34
  }
35
 
36
  export function clearStoredSession(): void {
 
39
  localStorage.removeItem("refresh_token");
40
  localStorage.removeItem("session_verified_at");
41
  document.cookie = "access_token=; Path=/; Max-Age=0; SameSite=Lax";
42
+ notifySessionChanged();
43
+ }
44
+
45
+ export function expireStoredSession(): void {
46
+ clearStoredSession();
47
+ window.dispatchEvent(new Event(SESSION_EXPIRED_EVENT));
48
  }
49
 
50
  export function restoreSession(force = false): Promise<boolean> {
 
83
  localStorage.setItem("session_verified_at", String(Date.now()));
84
  document.cookie = `access_token=${data.access_token}; Path=/; Max-Age=${data.expires_in ?? 3600}; SameSite=Lax${location.protocol === "https:" ? "; Secure" : ""}`;
85
  syncNativeWearRelayAuth();
86
+ notifySessionChanged();
87
  return true;
88
  } finally { clearTimeout(timeout); }
89
  }
main/app/lobby/page.tsx CHANGED
@@ -8,9 +8,9 @@ import { FLOW_KEYS, issueUiFlowPermit } from "../_utils/uiFlowGuard";
8
  import { requestNativeAppExit } from "../_utils/nativeWearBridge";
9
  import { prepareCoursePreview } from "../_utils/coursePreview";
10
  import { getAppPosition } from "../_utils/nativeLocation";
 
11
  import { storeRecentRoutePreview } from "../_utils/recentRoutePreview";
12
- import { clearStoredSession, restoreSession } from "../_utils/sessionRestore";
13
- import LoginRequiredDialog from "../_components/LoginRequiredDialog";
14
 
15
  // The lobby is a glanceable home screen. Show the latest pair side by side;
16
  // the complete route history remains available from the "์ „์ฒด" action.
@@ -493,10 +493,10 @@ export default function Page() {
493
  const [isRecentLoading, setIsRecentLoading] = useState(true);
494
  const [isExitDialogOpen, setIsExitDialogOpen] = useState(false);
495
  const [weatherState, setWeatherState] = useState<WeatherState>(INITIAL_WEATHER);
 
496
  const [sceneClock, setSceneClock] = useState(() => new Date());
497
  const [isExitRequested, setIsExitRequested] = useState(false);
498
  const [exitRequestError, setExitRequestError] = useState<string | null>(null);
499
- const [isLoginRequiredOpen, setIsLoginRequiredOpen] = useState(false);
500
  const apiBase =
501
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8000";
502
  const weather = WEATHER_TEXT[weatherState.condition];
@@ -547,12 +547,15 @@ export default function Page() {
547
 
548
  let isMounted = true;
549
 
550
- const cachedWeather = readWeatherCache();
 
 
551
  if (cachedWeather && Date.now() - cachedWeather.savedAt < WEATHER_CACHE_MAX_AGE_MS) {
552
  setWeatherState(cachedWeather.weather);
553
  }
554
 
555
  const loadWeather = async () => {
 
556
  let latitude = SEOUL_WEATHER_COORDS.latitude;
557
  let longitude = SEOUL_WEATHER_COORDS.longitude;
558
  let status: WeatherLoadStatus = "fallback";
@@ -561,6 +564,7 @@ export default function Page() {
561
  try {
562
  // Use the phone's native location bridge in the TWA and the browser
563
  // geolocation API on the web. Both paths ask for permission when needed.
 
564
  const position = await getAppPosition();
565
  latitude = position.coords.latitude;
566
  longitude = position.coords.longitude;
@@ -609,7 +613,7 @@ export default function Page() {
609
  return () => {
610
  isMounted = false;
611
  };
612
- }, []);
613
 
614
  useEffect(() => {
615
  const token =
@@ -723,7 +727,7 @@ export default function Page() {
723
  // signing in again.
724
  }
725
 
726
- setIsLoginRequiredOpen(true);
727
  };
728
 
729
  const startRouteSearch = () => {
@@ -832,6 +836,18 @@ export default function Page() {
832
  ? `ํ˜„์žฌ ์œ„์น˜ ๋ฏธํ™•์ธ ยท ${weatherState.locationName} ๊ธฐ์ค€ ๋‚ ์”จ`
833
  : `${weatherState.locationName} ํ˜„์žฌ ๋‚ ์”จ`}
834
  </p>
 
 
 
 
 
 
 
 
 
 
 
 
835
  </div>
836
  <div className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-white/90 bg-white/80 px-2.5 shadow-sm lg:h-11 lg:px-3">
837
  <WeatherIcon condition={weatherState.condition} className={`h-5 w-5 ${WEATHER_ICON_TONE[weatherState.condition]}`} />
@@ -1037,10 +1053,6 @@ export default function Page() {
1037
  </div>
1038
  </MotionDialog>
1039
 
1040
- <LoginRequiredDialog
1041
- open={isLoginRequiredOpen}
1042
- onDismiss={() => setIsLoginRequiredOpen(false)}
1043
- />
1044
  </main>
1045
  );
1046
  }
 
8
  import { requestNativeAppExit } from "../_utils/nativeWearBridge";
9
  import { prepareCoursePreview } from "../_utils/coursePreview";
10
  import { getAppPosition } from "../_utils/nativeLocation";
11
+ import { readLocationConsent, storeLocationConsent } from "../_utils/locationConsent";
12
  import { storeRecentRoutePreview } from "../_utils/recentRoutePreview";
13
+ import { clearStoredSession, requestLogin, restoreSession } from "../_utils/sessionRestore";
 
14
 
15
  // The lobby is a glanceable home screen. Show the latest pair side by side;
16
  // the complete route history remains available from the "์ „์ฒด" action.
 
493
  const [isRecentLoading, setIsRecentLoading] = useState(true);
494
  const [isExitDialogOpen, setIsExitDialogOpen] = useState(false);
495
  const [weatherState, setWeatherState] = useState<WeatherState>(INITIAL_WEATHER);
496
+ const [weatherReloadKey, setWeatherReloadKey] = useState(0);
497
  const [sceneClock, setSceneClock] = useState(() => new Date());
498
  const [isExitRequested, setIsExitRequested] = useState(false);
499
  const [exitRequestError, setExitRequestError] = useState<string | null>(null);
 
500
  const apiBase =
501
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8000";
502
  const weather = WEATHER_TEXT[weatherState.condition];
 
547
 
548
  let isMounted = true;
549
 
550
+ const locationDeclined = readLocationConsent() === "declined";
551
+ // Do not reuse a previous location's weather after the user opts out.
552
+ const cachedWeather = locationDeclined ? null : readWeatherCache();
553
  if (cachedWeather && Date.now() - cachedWeather.savedAt < WEATHER_CACHE_MAX_AGE_MS) {
554
  setWeatherState(cachedWeather.weather);
555
  }
556
 
557
  const loadWeather = async () => {
558
+ if (isMounted) setWeatherState(previous => ({ ...previous, status: "loading" }));
559
  let latitude = SEOUL_WEATHER_COORDS.latitude;
560
  let longitude = SEOUL_WEATHER_COORDS.longitude;
561
  let status: WeatherLoadStatus = "fallback";
 
564
  try {
565
  // Use the phone's native location bridge in the TWA and the browser
566
  // geolocation API on the web. Both paths ask for permission when needed.
567
+ if (locationDeclined) throw new Error("location_consent_declined");
568
  const position = await getAppPosition();
569
  latitude = position.coords.latitude;
570
  longitude = position.coords.longitude;
 
613
  return () => {
614
  isMounted = false;
615
  };
616
+ }, [weatherReloadKey]);
617
 
618
  useEffect(() => {
619
  const token =
 
727
  // signing in again.
728
  }
729
 
730
+ requestLogin();
731
  };
732
 
733
  const startRouteSearch = () => {
 
836
  ? `ํ˜„์žฌ ์œ„์น˜ ๋ฏธํ™•์ธ ยท ${weatherState.locationName} ๊ธฐ์ค€ ๋‚ ์”จ`
837
  : `${weatherState.locationName} ํ˜„์žฌ ๋‚ ์”จ`}
838
  </p>
839
+ {weatherState.status === "fallback" ? (
840
+ <button
841
+ type="button"
842
+ onClick={() => {
843
+ storeLocationConsent("allowed");
844
+ setWeatherReloadKey(value => value + 1);
845
+ }}
846
+ className="mt-2 rounded-full border border-black/15 bg-white/80 px-3 py-1.5 text-xs font-bold text-[#16211B]"
847
+ >
848
+ ํ˜„์žฌ ์œ„์น˜ ๋‚ ์”จ ๋‹ค์‹œ ํ™•์ธ
849
+ </button>
850
+ ) : null}
851
  </div>
852
  <div className="flex h-9 shrink-0 items-center gap-2 rounded-full border border-white/90 bg-white/80 px-2.5 shadow-sm lg:h-11 lg:px-3">
853
  <WeatherIcon condition={weatherState.condition} className={`h-5 w-5 ${WEATHER_ICON_TONE[weatherState.condition]}`} />
 
1053
  </div>
1054
  </MotionDialog>
1055
 
 
 
 
 
1056
  </main>
1057
  );
1058
  }
main/app/login/page.tsx CHANGED
@@ -17,6 +17,7 @@ import {
17
  } from "../_utils/googleIdentity";
18
  import { pushAuthStateToWatch } from "../_utils/watchAuthSync";
19
  import { syncNativeWearRelayAuth } from "../_utils/nativeWearBridge";
 
20
  import {
21
  ACTIVE_RUN_LOGIN_PROMPT_KEY,
22
  ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY,
@@ -59,9 +60,13 @@ export default function Page() {
59
  }, []);
60
 
61
  useEffect(() => {
62
- if (localStorage.getItem("refresh_token") || localStorage.getItem("access_token")) {
63
- router.replace("/lobby");
64
- }
 
 
 
 
65
  }, [router]);
66
 
67
  const getErrorMessage = (detail: unknown, fallback: string) => {
@@ -107,6 +112,7 @@ export default function Page() {
107
  const maxAgeSeconds = Math.max(60, data.expires_in ?? 60 * 60);
108
  document.cookie = `access_token=${data.access_token}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax`;
109
  syncNativeWearRelayAuth();
 
110
  try {
111
  await pushAuthStateToWatch(data.access_token);
112
  } catch (watchSyncError) {
 
17
  } from "../_utils/googleIdentity";
18
  import { pushAuthStateToWatch } from "../_utils/watchAuthSync";
19
  import { syncNativeWearRelayAuth } from "../_utils/nativeWearBridge";
20
+ import { clearStoredSession, notifySessionChanged, restoreSession } from "../_utils/sessionRestore";
21
  import {
22
  ACTIVE_RUN_LOGIN_PROMPT_KEY,
23
  ACTIVE_RUN_REDIRECT_SUPPRESSION_KEY,
 
60
  }, []);
61
 
62
  useEffect(() => {
63
+ let cancelled = false;
64
+ void restoreSession().then(valid => {
65
+ if (cancelled) return;
66
+ if (valid) router.replace("/lobby");
67
+ else clearStoredSession();
68
+ }).catch(() => {});
69
+ return () => { cancelled = true; };
70
  }, [router]);
71
 
72
  const getErrorMessage = (detail: unknown, fallback: string) => {
 
112
  const maxAgeSeconds = Math.max(60, data.expires_in ?? 60 * 60);
113
  document.cookie = `access_token=${data.access_token}; Path=/; Max-Age=${maxAgeSeconds}; SameSite=Lax`;
114
  syncNativeWearRelayAuth();
115
+ notifySessionChanged();
116
  try {
117
  await pushAuthStateToWatch(data.access_token);
118
  } catch (watchSyncError) {
main/app/signup/page.tsx CHANGED
@@ -3,6 +3,7 @@
3
  import { useState } from "react";
4
  import Link from "next/link";
5
  import { useRouter } from "next/navigation";
 
6
 
7
  type VerificationTone = "success" | "error" | "info" | null;
8
 
@@ -461,6 +462,8 @@ export default function Page() {
461
  ))}
462
  </div>
463
 
 
 
464
  {errorMessage ? (
465
  <p className="w-full text-sm text-red-600">{errorMessage}</p>
466
  ) : null}
 
3
  import { useState } from "react";
4
  import Link from "next/link";
5
  import { useRouter } from "next/navigation";
6
+ import SignupLocationPermission from "../_components/SignupLocationPermission";
7
 
8
  type VerificationTone = "success" | "error" | "info" | null;
9
 
 
462
  ))}
463
  </div>
464
 
465
+ <SignupLocationPermission />
466
+
467
  {errorMessage ? (
468
  <p className="w-full text-sm text-red-600">{errorMessage}</p>
469
  ) : null}
tools/test-session-guard.cjs ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Session regressions use mocked tokens/APIs and a fake clock, never real accounts.
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const vm = require('node:vm');
6
+ const ts = require('../main/node_modules/typescript');
7
+
8
+ const root = path.resolve(__dirname, '../main/app');
9
+ const jwt = (exp, sub = 'fixture') => `fixture.${Buffer.from(JSON.stringify({ exp, sub })).toString('base64url')}.fixture`;
10
+ const flush = async () => { for (let i = 0; i < 25; i++) await Promise.resolve(); };
11
+ function findElement(tree, predicate) {
12
+ if (!tree || typeof tree !== 'object') return undefined;
13
+ if (predicate(tree)) return tree;
14
+ for (const child of [tree.props?.children].flat()) {
15
+ const match = findElement(child, predicate);
16
+ if (match) return match;
17
+ }
18
+ }
19
+
20
+ function fixture(pathname = '/lobby') {
21
+ let now = Date.now();
22
+ class ClockDate extends Date { static now() { return now; } }
23
+ const values = new Map();
24
+ const localStorage = {
25
+ getItem: key => values.get(key) ?? null,
26
+ setItem: (key, value) => values.set(key, value),
27
+ removeItem: key => values.delete(key),
28
+ };
29
+ const location = { origin: 'http://localhost:3000', protocol: 'http:' };
30
+ const document = new EventTarget();
31
+ let cookie = '';
32
+ Object.defineProperty(document, 'cookie', {
33
+ get: () => cookie,
34
+ set: value => { cookie = value.includes('Max-Age=0') ? '' : value.split(';')[0]; },
35
+ });
36
+ document.visibilityState = 'visible';
37
+ const window = new EventTarget();
38
+ const timers = new Map();
39
+ const intervals = new Map();
40
+ let id = 0;
41
+ const setTimeout = (callback, delay) => { const key = ++id; timers.set(key, { callback, delay }); return key; };
42
+ const clearTimeout = key => timers.delete(key);
43
+ window.setInterval = callback => { const key = ++id; intervals.set(key, callback); return key; };
44
+ window.clearInterval = key => intervals.delete(key);
45
+ const states = [];
46
+ const effects = [];
47
+ const refs = [];
48
+ let cursor = 0;
49
+ let refCursor = 0;
50
+ const react = {
51
+ useState(initial) {
52
+ const key = cursor++;
53
+ if (!(key in states)) states[key] = initial;
54
+ return [states[key], next => { states[key] = typeof next === 'function' ? next(states[key]) : next; }];
55
+ },
56
+ useRef(initial) { const key = refCursor++; return refs[key] ??= { current: initial }; },
57
+ useEffect: effect => effects.push(effect),
58
+ };
59
+ const modules = new Map();
60
+ const context = vm.createContext({
61
+ console, URL, Headers, Request, Response, AbortController, Event, Date: ClockDate,
62
+ window, document, localStorage, location, atob, setTimeout, clearTimeout,
63
+ process: { env: { NEXT_PUBLIC_API_BASE_URL: 'http://localhost:8000' } },
64
+ fetch: (...args) => window.fetch(...args),
65
+ });
66
+ function load(filename) {
67
+ const absolute = path.resolve(root, filename);
68
+ if (modules.has(absolute)) return modules.get(absolute);
69
+ const exports = {};
70
+ modules.set(absolute, exports);
71
+ const code = ts.transpileModule(fs.readFileSync(absolute, 'utf8'), {
72
+ compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2020 },
73
+ }).outputText;
74
+ const requireFixture = name => {
75
+ if (name === 'react') return react;
76
+ if (name === 'react/jsx-runtime') return { jsx: (type, props) => ({ type, props }), jsxs: (type, props) => ({ type, props }), Fragment: 'Fragment' };
77
+ if (name === 'next/navigation') return { usePathname: () => pathname, useRouter: () => ({ replace: value => { result.redirect = value; } }) };
78
+ if (name.endsWith('nativeWearBridge')) return { syncNativeWearRelayAuth() {}, clearNativeWearRelayAuth() {} };
79
+ if (name.endsWith('nativeLocation')) return { getAppPosition: () => result.position() };
80
+ if (name === './LoginRequiredDialog') return { default: 'LoginRequiredDialog' };
81
+ const target = path.resolve(path.dirname(absolute), name);
82
+ const extension = fs.existsSync(target + '.ts') ? '.ts' : '.tsx';
83
+ return load(path.relative(root, target + extension));
84
+ };
85
+ vm.runInContext(`(function(require, exports) { ${code}\n})`, context, { filename: absolute })(requireFixture, exports);
86
+ return exports;
87
+ }
88
+ const result = { window, localStorage, timers, intervals, states, effects, load,
89
+ advance(milliseconds) { now += milliseconds; },
90
+ position: async () => { throw { code: 1 }; },
91
+ render(component) { cursor = 0; refCursor = 0; return component({ children: null }); },
92
+ mount() { return effects.splice(0).map(effect => effect()); },
93
+ seed(token = jwt(Date.now() / 1000 + 3600)) {
94
+ localStorage.setItem('access_token', token); localStorage.setItem('refresh_token', 'refresh-fixture');
95
+ },
96
+ };
97
+ return result;
98
+ }
99
+
100
+ (async () => {
101
+ {
102
+ const f = fixture();
103
+ const guard = f.load('_components/SessionGuard.tsx').default;
104
+ f.window.fetch = async () => { throw Error('no API for missing session'); };
105
+ f.render(guard); const cleanup = f.mount(); await flush();
106
+ assert.equal(f.states[0], 'missing', 'unauthenticated lobby opens immediately');
107
+ const tree = f.render(guard);
108
+ tree.props.children[1].props.onDismiss(); await flush();
109
+ assert.equal(f.states[0], null, 'later dismisses without reopening on the lobby');
110
+ f.load('_utils/sessionRestore.ts').requestLogin();
111
+ assert.equal(f.states[0], 'missing', 'protected actions reuse the same global dialog');
112
+ cleanup.forEach(fn => fn?.());
113
+ console.log('PASS unauthenticated lobby and dismiss');
114
+ }
115
+ {
116
+ const f = fixture('/signup');
117
+ f.window.fetch = async () => Response.json({});
118
+ f.render(f.load('_components/SessionGuard.tsx').default); const cleanup = f.mount(); await flush();
119
+ assert.equal(f.states[0], null, 'signup does not require login');
120
+ cleanup.forEach(fn => fn?.());
121
+ console.log('PASS public signup remains accessible');
122
+ }
123
+ {
124
+ const f = fixture(); f.seed();
125
+ let rejected = false;
126
+ const renewed = jwt(Date.now() / 1000 + 120);
127
+ f.window.fetch = async () => rejected ? new Response(null, { status: 401 }) : Response.json({ access_token: renewed, refresh_token: 'new-refresh' });
128
+ f.render(f.load('_components/SessionGuard.tsx').default); const cleanup = f.mount(); await flush();
129
+ assert.equal(f.states[0], null);
130
+ const expiryTimer = [...f.timers.values()].find(timer => timer.delay < 65_000);
131
+ assert.ok(expiryTimer, 'expiry check is scheduled before the token expires, not five minutes later');
132
+ rejected = true; f.advance(61_000); expiryTimer.callback(); await flush();
133
+ assert.equal(f.states[0], 'expired');
134
+ assert.equal(f.localStorage.getItem('access_token'), null);
135
+ cleanup.forEach(fn => fn?.());
136
+ console.log('PASS idle expiry and rejected refresh open re-login');
137
+ }
138
+ {
139
+ const f = fixture(); f.seed();
140
+ let expired = 0;
141
+ f.window.addEventListener('rts:session-expired', () => expired++);
142
+ f.window.fetch = async () => new Response(null, { status: 401 });
143
+ f.load('_utils/sessionFetch.ts').installSessionFetchObserver();
144
+ await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${f.localStorage.getItem('access_token')}` } });
145
+ assert.equal(expired, 1); assert.equal(f.localStorage.getItem('access_token'), null);
146
+ console.log('PASS API 401 immediately invalidates an unrecoverable session');
147
+ }
148
+ {
149
+ const f = fixture(); f.seed();
150
+ const old = f.localStorage.getItem('access_token');
151
+ const renewed = jwt(Date.now() / 1000 + 7200);
152
+ const calls = [];
153
+ f.window.fetch = async (input, init) => {
154
+ const url = String(input); calls.push({ url, auth: new Headers(init?.headers).get('Authorization') });
155
+ if (url.endsWith('/refresh')) return Response.json({ access_token: renewed, refresh_token: 'renewed' });
156
+ return new Headers(init?.headers).get('Authorization') === `Bearer ${old}` ? new Response(null, { status: 401 }) : Response.json({ ok: true });
157
+ };
158
+ f.load('_utils/sessionFetch.ts').installSessionFetchObserver();
159
+ const response = await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${old}` } });
160
+ assert.equal(response.status, 200); assert.equal(calls.length, 3); assert.equal(calls[2].auth, `Bearer ${renewed}`);
161
+ console.log('PASS successful refresh retries the API with the new token');
162
+ }
163
+ {
164
+ const f = fixture(); f.seed(); const token = f.localStorage.getItem('access_token');
165
+ let expired = 0; f.window.addEventListener('rts:session-expired', () => expired++);
166
+ f.window.fetch = async input => {
167
+ if (String(input).endsWith('/refresh')) throw Error('offline');
168
+ return new Response(null, { status: 401 });
169
+ };
170
+ f.load('_utils/sessionFetch.ts').installSessionFetchObserver();
171
+ await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${token}` } });
172
+ await f.window.fetch('http://localhost:8000/api/v1/auth/login');
173
+ assert.equal(expired, 0); assert.equal(f.localStorage.getItem('access_token'), token);
174
+ console.log('PASS connection errors and failed public login do not clear sessions');
175
+ }
176
+ {
177
+ const f = fixture(); f.seed(); const old = f.localStorage.getItem('access_token');
178
+ const current = jwt(Date.now() / 1000 + 3600, 'other-account');
179
+ f.window.fetch = async () => { f.localStorage.setItem('access_token', current); return new Response(null, { status: 401 }); };
180
+ f.load('_utils/sessionFetch.ts').installSessionFetchObserver();
181
+ await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${old}` } });
182
+ assert.equal(f.localStorage.getItem('access_token'), current);
183
+ console.log('PASS stale requests cannot clear a new account session');
184
+ }
185
+ {
186
+ const f = fixture('/signup'); const component = f.load('_components/SignupLocationPermission.tsx').default;
187
+ const choose = (tree, value, checked = true) => findElement(tree, node => node.type === 'input' && node.props.value === value).props.onChange({ target: { checked } });
188
+ let tree = f.render(component);
189
+ let locationCalls = 0;
190
+ f.position = async () => { locationCalls++; throw { code: 1 }; };
191
+ choose(tree, 'declined'); await flush();
192
+ assert.equal(locationCalls, 0, 'declining must not trigger a platform permission request');
193
+ assert.equal(f.localStorage.getItem('rts:location-consent'), 'declined');
194
+ tree = f.render(component); choose(tree, 'allowed'); await flush();
195
+ assert.equal(f.states[0], 'declined'); assert.equal(f.states[1], 'error'); assert.match(f.states[2], /๊ฐ€์ž…์€ ๊ณ„์†/);
196
+ f.position = async () => ({ coords: { latitude: 0, longitude: 0 } });
197
+ tree = f.render(component); choose(tree, 'allowed'); await flush();
198
+ assert.equal(f.states[0], 'allowed'); assert.equal(f.states[1], 'granted'); assert.match(f.states[2], /๋กœ๋น„/);
199
+ let finish;
200
+ f.position = () => new Promise(resolve => { finish = resolve; });
201
+ tree = f.render(component); choose(tree, 'allowed');
202
+ tree = f.render(component); choose(tree, 'declined');
203
+ finish({ coords: { latitude: 0, longitude: 0 } }); await flush();
204
+ assert.equal(f.states[0], 'declined'); assert.equal(f.states[1], 'idle');
205
+ assert.equal(f.localStorage.getItem('rts:location-consent'), 'declined', 'a late permission result must not override opting out');
206
+ tree = f.render(component);
207
+ assert.equal(findElement(tree, node => node.type === 'input' && node.props.value === 'allowed').props.checked, false);
208
+ assert.equal(findElement(tree, node => node.type === 'input' && node.props.value === 'declined').props.checked, true);
209
+ choose(tree, 'declined', false); await flush();
210
+ assert.equal(f.states[0], null, 'unchecking an option clears the choice without granting permission');
211
+ console.log('PASS signup allow/decline, system denial, retry and opting out during a request');
212
+ }
213
+ })().catch(error => { console.error(error); process.exitCode = 1; });