Open History to see the last commit
1import { createAuthClient, type VanillaBetterAuthClient } from "@neon/auth";
2import { Button } from "@base-ui/react/button";
3import { useEffect, useState, type FormEvent } from "react";
4import { Brand, Journal } from "./journal.js";
5
6type Config = { authURL: string; origin: string; realtimeURL: string | null };
7type Auth = VanillaBetterAuthClient & {
8 oauth2: {
9 consent(x: { accept: boolean }): Promise<unknown>;
10 continue(x: { selected: boolean }): Promise<unknown>;
11 publicClient(x: { query: { client_id: string } }): Promise<{
12 data?: { client_name?: string } | null;
13 error?: { message?: string } | null;
14 }>;
15 };
16};
17export type JournalAPI = {
18 read<T>(path: string, body?: unknown): Promise<T>;
19 photo(path: string, signal: AbortSignal): Promise<Blob>;
20 signOut(): Promise<void>;
21};
22type Screen =
23 | { kind: "login" | "consent"; auth: Auth; config: Config }
24 | { kind: "journal"; config: Config; api: JournalAPI }
25 | { kind: "error"; message: string };
26
27const message = (error: unknown) =>
28 error instanceof Error ? error.message : "Could not connect to JOL.";
29function checkAuth(result: unknown) {
30 if (result && typeof result === "object" && "error" in result && result.error)
31 throw new Error(
32 "This sign-in link could not be completed. Return to Jerry and connect again.",
33 );
34}
35function signedFlow() {
36 const query = new URLSearchParams(location.search);
37 return query.has("sig") && query.has("ba_param");
38}
39
40export function App() {
41 const [screen, setScreen] = useState<Screen>();
42 useEffect(() => {
43 let current = true;
44 let closed = false;
45 const show = (value: Screen) => {
46 if (current) setScreen(value);
47 };
48 const expire = (text: string) => {
49 closed = true;
50 show({ kind: "error", message: text });
51 return new Error(text);
52 };
53 async function boot() {
54 const response = await fetch("/public-config");
55 if (!response.ok) throw new Error("Could not open Jerry On Line.");
56 const config: Config = await response.json();
57 const auth = createAuthClient(config.authURL) as Auth;
58 const session = await auth.getSession();
59 if (!current) return;
60 if (session.error) throw new Error("JOL could not check your session.");
61 if (!session.data?.user) return show({ kind: "login", config, auth });
62 if (location.pathname === "/consent")
63 return show({ kind: "consent", config, auth });
64 if (signedFlow()) {
65 checkAuth(await auth.oauth2.continue({ selected: true }));
66 return;
67 }
68
69 const identity = config.authURL + "|" + session.data.user.id;
70 async function authorized(path: string, init?: RequestInit) {
71 if (closed || !current) throw new Error("Session closed");
72 // The SDK puts the JWT on the session, including its warm cache.
73 const { data, error } = await auth.getSession();
74 if (closed || !current) throw new Error("Session closed");
75 if (error) throw new Error("Could not check your session. Try again.");
76 if (
77 !data?.session?.token ||
78 config.authURL + "|" + data.user.id !== identity
79 ) {
80 throw expire("Your session changed. Reconnect to open your journal.");
81 }
82 const headers = new Headers(init?.headers);
83 headers.set("Authorization", "Bearer " + data.session.token);
84 headers.set("X-JOL-Expected-User", identity);
85 const result = await fetch("/api" + path, { ...init, headers });
86 if (result.status === 401)
87 throw expire(
88 "JOL could not verify your session. Try connecting again.",
89 );
90 if (result.status === 409) {
91 const conflict = await result.clone().json();
92 if (conflict.error === "Account changed; reload JOL")
93 throw expire(
94 "Your account changed. Reconnect to open its journal.",
95 );
96 }
97 return result;
98 }
99 const api: JournalAPI = {
100 async read<T>(path: string, body?: unknown) {
101 const result = await authorized(
102 path,
103 body === undefined
104 ? undefined
105 : {
106 method: "POST",
107 headers: { "Content-Type": "application/json" },
108 body: JSON.stringify(body),
109 },
110 );
111 const value = await result.json();
112 if (!result.ok)
113 throw new Error(value.error ?? "Could not reach JOL.");
114 return value as T;
115 },
116 async photo(path, signal) {
117 const result = await authorized(path, { signal });
118 if (!result.ok) throw new Error("Could not open the photograph.");
119 return result.blob();
120 },
121 async signOut() {
122 const result = await auth.signOut();
123 if (result.error) throw new Error("Could not sign out. Try again.");
124 closed = true;
125 location.assign("/");
126 },
127 };
128 await api.read("/me");
129 show({ kind: "journal", config, api });
130 }
131 void boot().catch((error) =>
132 show({ kind: "error", message: message(error) }),
133 );
134 return () => {
135 current = false;
136 closed = true;
137 };
138 }, []);
139
140 if (!screen)
141 return <p className="connecting">Connecting to Jerry On Line…</p>;
142 if (screen.kind === "error")
143 return (
144 <section className="connecting">
145 <p role="alert">{screen.message}</p>
146 <Button onClick={() => location.reload()}>Try again</Button>
147 </section>
148 );
149 if (screen.kind === "journal")
150 return <Journal api={screen.api} realtimeURL={screen.config.realtimeURL} />;
151 return (
152 <Login
153 auth={screen.auth}
154 config={screen.config}
155 consent={screen.kind === "consent"}
156 />
157 );
158}
159
160function Login({
161 auth,
162 config,
163 consent,
164}: {
165 auth: Auth;
166 config: Config;
167 consent: boolean;
168}) {
169 const [signup, setSignup] = useState(false);
170 const [clientName, setClientName] = useState("");
171 const [issue, setIssue] = useState("");
172 const [busy, setBusy] = useState(false);
173 useEffect(() => {
174 if (!consent) return;
175 let current = true;
176 const client_id =
177 new URLSearchParams(location.search).get("client_id") ?? "";
178 void auth.oauth2
179 .publicClient({ query: { client_id } })
180 .then((result) => {
181 if (!result.data?.client_name)
182 throw new Error(
183 "This authorization link is invalid or expired. Return to Jerry and connect again.",
184 );
185 if (current) setClientName(result.data.client_name);
186 })
187 .catch((error) => {
188 if (current) setIssue(message(error));
189 });
190 return () => {
191 current = false;
192 };
193 }, [auth, consent]);
194
195 async function submit(event: FormEvent<HTMLFormElement>) {
196 event.preventDefault();
197 if (busy) return;
198 setBusy(true);
199 setIssue("");
200 const form = new FormData(event.currentTarget);
201 try {
202 if (consent) {
203 checkAuth(await auth.oauth2.consent({ accept: true }));
204 return;
205 }
206 const values = {
207 email: String(form.get("email")),
208 password: String(form.get("password")),
209 };
210 const result = signup
211 ? await auth.signUp.email({
212 ...values,
213 name: String(form.get("name") || "Explorer"),
214 })
215 : await auth.signIn.email(values);
216 if (result.error)
217 throw new Error(result.error.message || "Sign-in failed.");
218 if (result.data && "redirect" in result.data && result.data.redirect)
219 return;
220 if (signedFlow())
221 checkAuth(await auth.oauth2.continue({ selected: true }));
222 else location.assign("/");
223 } catch (error) {
224 setIssue(message(error));
225 } finally {
226 setBusy(false);
227 }
228 }
229
230 async function google() {
231 try {
232 const result = await auth.signIn.social({
233 provider: "google",
234 callbackURL:
235 config.origin + (signedFlow() ? "/login" + location.search : "/"),
236 });
237 if (result.error)
238 throw new Error(result.error.message || "Google sign-in failed.");
239 } catch (error) {
240 setIssue(message(error));
241 }
242 }
243
244 return (
245 <main className="shell">
246 <header className="masthead">
247 <Brand />
248 </header>
249 <section className="notebook login">
250 <div className="small">{new URL(config.origin).host}</div>
251 <h1>
252 {consent
253 ? clientName
254 ? `Connect ${clientName}?`
255 : "Let Jerry connect?"
256 : "Your explorer. On line."}
257 </h1>
258 <p>
259 {consent
260 ? "Jerry can sync the journals you choose and receive directions when you enable remote missions on your Mac."
261 : "Sign in to read Jerry’s field notes and send him his next expedition."}
262 </p>
263 {!consent && (
264 <Button className="primary" onClick={() => void google()}>
265 Continue with Google
266 </Button>
267 )}
268 <form onSubmit={submit}>
269 {!consent && (
270 <>
271 <label>
272 Email
273 <input
274 name="email"
275 type="email"
276 autoComplete="email"
277 required
278 />
279 </label>
280 <label>
281 Password
282 <input
283 name="password"
284 type="password"
285 autoComplete={signup ? "new-password" : "current-password"}
286 minLength={8}
287 required
288 />
289 </label>
290 {signup && (
291 <label>
292 Your name
293 <input name="name" autoComplete="name" />
294 </label>
295 )}
296 </>
297 )}
298 {issue && (
299 <p className="error" role="alert">
300 {issue}
301 </p>
302 )}
303 <div className="actions">
304 <Button
305 className="primary"
306 type="submit"
307 disabled={busy || (consent && !clientName)}
308 >
309 {consent
310 ? "Connect Jerry"
311 : signup
312 ? "Create account"
313 : "Sign in"}
314 </Button>
315 <Button
316 onClick={() => {
317 if (!consent) setSignup(!signup);
318 else
319 void auth.oauth2
320 .consent({ accept: false })
321 .then(checkAuth)
322 .catch((error) => setIssue(message(error)));
323 }}
324 >
325 {consent
326 ? "Decline"
327 : signup
328 ? "Already have an account?"
329 : "Create account"}
330 </Button>
331 </div>
332 </form>
333 <p className="small">
334 {consent
335 ? "Only connect an app you opened yourself. You can disconnect in Jerry’s Settings."
336 : "Your account belongs to this JOL server."}
337 </p>
338 </section>
339 </main>
340 );
341}