@orbclub/create-app 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -0
  3. package/bin/create-orb-app.js +410 -0
  4. package/bin/node-version.js +6 -0
  5. package/bin/package-manager.js +87 -0
  6. package/bin/sdk-version.js +3 -0
  7. package/package.json +35 -1
  8. package/template/.env.local.example +10 -0
  9. package/template/AGENTS.md +105 -0
  10. package/template/README.md +56 -0
  11. package/template/eslint.config.mjs +11 -0
  12. package/template/gitignore +26 -0
  13. package/template/next.config.ts +25 -0
  14. package/template/package.json +29 -0
  15. package/template/pnpm-workspace.yaml +15 -0
  16. package/template/src/app/.well-known/orb-siwo.json/route.ts +23 -0
  17. package/template/src/app/api/local-sign-in/init/route.ts +12 -0
  18. package/template/src/app/api/local-sign-in/local-sign-in.ts +50 -0
  19. package/template/src/app/api/local-sign-in/status/route.ts +12 -0
  20. package/template/src/app/api/orb/route-validation.ts +123 -0
  21. package/template/src/app/api/orb/user/route.ts +44 -0
  22. package/template/src/app/api/route-security.ts +105 -0
  23. package/template/src/app/api/site-session/bind/route.ts +82 -0
  24. package/template/src/app/api/site-session/binding/route.ts +35 -0
  25. package/template/src/app/api/site-session/end/route.ts +30 -0
  26. package/template/src/app/api/site-session/renew/route.ts +71 -0
  27. package/template/src/app/api/site-session/site-session.ts +152 -0
  28. package/template/src/app/globals.css +196 -0
  29. package/template/src/app/home.tsx +115 -0
  30. package/template/src/app/layout.tsx +24 -0
  31. package/template/src/app/page.tsx +12 -0
  32. package/template/src/lib/orb-session.ts +703 -0
  33. package/template/src/lib/sign-in.ts +61 -0
  34. package/template/src/lib/site-origin.ts +35 -0
  35. package/template/src/lib/use-orb-session.ts +26 -0
  36. package/template/tsconfig.json +30 -0
@@ -0,0 +1,12 @@
1
+ import { getSignInSetup } from "@/lib/sign-in";
2
+
3
+ import { Home } from "./home";
4
+
5
+ // Read the sign-in configuration per request, not at build time.
6
+ export const dynamic = "force-dynamic";
7
+
8
+ export default function HomePage() {
9
+ return (
10
+ <Home appName={__DISPLAY_NAME_JSON__} signInSetup={getSignInSetup()} />
11
+ );
12
+ }
@@ -0,0 +1,703 @@
1
+ import {
2
+ OrbAppsClient,
3
+ OrbConnectDeclinedError,
4
+ OrbConnectTimeoutError,
5
+ OrbNotAvailableError,
6
+ } from "@orbclub/apps-sdk/client";
7
+ import type { OrbAppContext, OrbAuthTokens } from "@orbclub/apps-sdk/client";
8
+ import {
9
+ OrbSignInError,
10
+ getTokenExpiresAt,
11
+ prefersOrbAppLink,
12
+ requestRenewBinding,
13
+ signInWithOrb,
14
+ withSiteSessionLock,
15
+ } from "@orbclub/apps-sdk/site";
16
+
17
+ import { isLoopbackOrigin } from "./sign-in";
18
+ import type { SignInSetup } from "./sign-in";
19
+
20
+ /** The fields of an Orb user the page shows; see /api/orb/user. */
21
+ export type UserProfile = {
22
+ metadata: {
23
+ name?: string | null;
24
+ handle?: string | null;
25
+ address?: string | null;
26
+ rawPicture?: string | null;
27
+ };
28
+ };
29
+
30
+ export type BrowserSignIn =
31
+ | { flow: "site" | "local" }
32
+ | { flow: "none"; message: string };
33
+
34
+ export type QrPrompt = {
35
+ image: string | null;
36
+ deepLink: string | null;
37
+ showAppLink: boolean;
38
+ message: string;
39
+ };
40
+
41
+ export type SessionState = {
42
+ started: boolean;
43
+ context: OrbAppContext | null;
44
+ browserSignIn: BrowserSignIn;
45
+ status: "idle" | "restoring" | "connecting" | "signed-in";
46
+ user: UserProfile | null;
47
+ loadingUser: boolean;
48
+ qr: QrPrompt | null;
49
+ error: string | null;
50
+ };
51
+
52
+ // idToken is null for a browser session restored by this app's server.
53
+ type Session = { idToken: string | null; accessToken: string };
54
+
55
+ type UserResponse = {
56
+ status?: string;
57
+ message?: string;
58
+ msg?: string;
59
+ data?: UserProfile;
60
+ };
61
+
62
+ // Inside Orb, ask the host to renew the grant this long before the access
63
+ // token expires.
64
+ const RENEW_BEFORE_EXPIRY_MS = 60_000;
65
+
66
+ // Browser sessions: this app's server renews them through
67
+ // /api/site-session (ORB_SITE_SESSION_RENEW_BEFORE_MS on the server).
68
+ const SITE_SESSION_ROUTE = "/api/site-session";
69
+ const SITE_RENEW_BEFORE_EXPIRY_MS = 150_000;
70
+ const SITE_RENEW_RETRY_MS = 30_000;
71
+
72
+ const INITIAL_STATE: SessionState = {
73
+ started: false,
74
+ context: null,
75
+ browserSignIn: { flow: "none", message: "" },
76
+ status: "idle",
77
+ user: null,
78
+ loadingUser: false,
79
+ qr: null,
80
+ error: null,
81
+ };
82
+
83
+ function accountOf(token: string): string | undefined {
84
+ return OrbAppsClient.getAccountAddressFromToken(token)?.toLowerCase();
85
+ }
86
+
87
+ // Decodes the token without verifying it: enough to notice a profile switch,
88
+ // never enough to authorize. The server verifies tokens.
89
+ function isSelectedAccount(
90
+ client: OrbAppsClient,
91
+ token: string | null,
92
+ ): boolean {
93
+ const profileId = client.context?.user.profileId?.toLowerCase();
94
+ const account = token ? accountOf(token) : undefined;
95
+ return !!profileId && account === profileId;
96
+ }
97
+
98
+ // Keeps the ID and access tokens only. A refresh token is never stored.
99
+ function toSession(tokens: OrbAuthTokens): Session {
100
+ if (!tokens.accessToken) {
101
+ throw new Error("Orb did not return an access token.");
102
+ }
103
+ return { idToken: tokens.idToken, accessToken: tokens.accessToken };
104
+ }
105
+
106
+ function postJson(path: string, body: Record<string, unknown> = {}) {
107
+ return fetch(`${SITE_SESSION_ROUTE}/${path}`, {
108
+ method: "POST",
109
+ headers: { "content-type": "application/json" },
110
+ body: JSON.stringify(body),
111
+ cache: "no-store",
112
+ credentials: "same-origin",
113
+ });
114
+ }
115
+
116
+ /** The hash of this app's bind secret, sent with the sign-in; or undefined. */
117
+ const requestSiteRenewBinding = () =>
118
+ requestRenewBinding({ url: `${SITE_SESSION_ROUTE}/binding` });
119
+
120
+ /** Whether this app's server can renew the new browser session. */
121
+ function bindOnServer(accessToken: string): Promise<boolean> {
122
+ return withSiteSessionLock(async () => {
123
+ try {
124
+ const response = await postJson("bind", { accessToken });
125
+ const payload = (await response.json()) as { renewable?: unknown };
126
+ return response.ok && payload.renewable === true;
127
+ } catch {
128
+ return false;
129
+ }
130
+ });
131
+ }
132
+
133
+ /** Clears this app's session cookies and ends the session with Orb. */
134
+ async function endOnServer(): Promise<void> {
135
+ try {
136
+ await withSiteSessionLock(() => postJson("end"));
137
+ } catch {
138
+ // Best effort: the page session has already ended.
139
+ }
140
+ }
141
+
142
+ /**
143
+ * The browser session's access token from this app's server, renewed when it
144
+ * is close to expiry. "ended": it cannot be renewed; null: try again later.
145
+ */
146
+ function renewOnServer(): Promise<string | "ended" | null> {
147
+ return withSiteSessionLock(async () => {
148
+ try {
149
+ const response = await postJson("renew");
150
+ if (response.status === 401) return "ended";
151
+ const payload = (await response.json()) as { accessToken?: unknown };
152
+ return response.ok && typeof payload.accessToken === "string"
153
+ ? payload.accessToken
154
+ : null;
155
+ } catch {
156
+ return null;
157
+ }
158
+ });
159
+ }
160
+
161
+ function resolveBrowserSignIn(
162
+ setup: SignInSetup,
163
+ pageOrigin: string,
164
+ ): BrowserSignIn {
165
+ if (setup.flow === "none") return setup;
166
+ if (setup.flow === "local") {
167
+ return isLoopbackOrigin(pageOrigin)
168
+ ? { flow: "local" }
169
+ : {
170
+ flow: "none",
171
+ message: "Open the app on http://localhost to sign in.",
172
+ };
173
+ }
174
+ if (setup.origin !== pageOrigin) {
175
+ return {
176
+ flow: "none",
177
+ message: `Sign-in is set up for ${setup.origin}. Open the app there to sign in.`,
178
+ };
179
+ }
180
+ return { flow: "site" };
181
+ }
182
+
183
+ function describeSignInError(reason: unknown): string {
184
+ if (reason instanceof OrbNotAvailableError) {
185
+ return "The Orb app is not available here.";
186
+ }
187
+ if (reason instanceof OrbConnectTimeoutError) {
188
+ return "Sign-in timed out. Try again.";
189
+ }
190
+ if (reason instanceof OrbConnectDeclinedError) {
191
+ return "Sign-in was declined in the Orb app.";
192
+ }
193
+ if (reason instanceof OrbSignInError) {
194
+ if (reason.reason === "expired") return "The QR code expired. Try again.";
195
+ if (reason.reason === "provisioning") {
196
+ return "Sign in with Orb is still being set up for this site. Try again in a few minutes.";
197
+ }
198
+ if (reason.reason === "unavailable") {
199
+ return "Sign in with Orb is unavailable. Check that /.well-known/orb-siwo.json returns this origin.";
200
+ }
201
+ }
202
+ return reason instanceof Error
203
+ ? reason.message
204
+ : "Sign-in failed. Try again.";
205
+ }
206
+
207
+ /**
208
+ * Orb sign-in state for one page: bridge `connect` inside the Orb app,
209
+ * otherwise browser-site Sign in with Orb or local development sign-in.
210
+ * Tokens stay in memory and are never exposed to the view.
211
+ */
212
+ export class OrbSession {
213
+ private state = INITIAL_STATE;
214
+ private readonly listeners = new Set<() => void>();
215
+ private client: OrbAppsClient | null = null;
216
+ private tokens: Session | null = null;
217
+ // Whether the session was checked against a selected profile; such a
218
+ // session ends when the context no longer names that profile.
219
+ private boundToProfile = false;
220
+ // Bumped to abandon an in-flight sign-in (cancel, sign-out, unmount).
221
+ private attempt = 0;
222
+ private cancelPending: (() => void) | null = null;
223
+ private expiryTimer: ReturnType<typeof setTimeout> | null = null;
224
+ private renewTimer: ReturnType<typeof setTimeout> | null = null;
225
+ // Whether this app's server can renew the current browser session.
226
+ private siteRenewable = false;
227
+
228
+ constructor(private readonly setup: SignInSetup) {}
229
+
230
+ subscribe = (listener: () => void): (() => void) => {
231
+ this.listeners.add(listener);
232
+ return () => this.listeners.delete(listener);
233
+ };
234
+
235
+ getSnapshot = (): SessionState => this.state;
236
+
237
+ getServerSnapshot = (): SessionState => INITIAL_STATE;
238
+
239
+ start(): void {
240
+ const client = new OrbAppsClient();
241
+ this.client = client;
242
+ client.ready();
243
+ this.update({
244
+ started: true,
245
+ context: client.context,
246
+ browserSignIn: resolveBrowserSignIn(this.setup, window.location.origin),
247
+ // stop() abandoned any sign-in in progress.
248
+ ...(this.tokens ? {} : { status: "idle", qr: null }),
249
+ });
250
+
251
+ client.onContextChange((context) => this.handleContextChange(context));
252
+
253
+ // A session kept by stop() stays only while Orb selects its profile;
254
+ // without a context to check, it ends.
255
+ const kept = this.tokens;
256
+ if (kept) {
257
+ const bound = this.boundToProfile;
258
+ if (
259
+ (client.context?.user.profileId || bound) &&
260
+ !isSelectedAccount(client, kept.accessToken)
261
+ ) {
262
+ this.endSession(null);
263
+ } else {
264
+ this.startSession(kept, false);
265
+ this.boundToProfile ||= bound;
266
+ }
267
+ }
268
+
269
+ // Outside Orb, a browser session this app's server can renew survives
270
+ // a reload.
271
+ if (!client.context && this.state.browserSignIn.flow === "site") {
272
+ void this.restoreSite();
273
+ }
274
+
275
+ // The context can arrive after the page loads: restore once it does.
276
+ if (client.context) {
277
+ void this.restore();
278
+ } else {
279
+ const unsubscribe = client.onContextChange(() => {
280
+ unsubscribe();
281
+ void this.restore();
282
+ });
283
+ }
284
+ }
285
+
286
+ // Keeps the session: React can run stop() then start() on the same
287
+ // instance (Strict Mode, Fast Refresh, an <Activity> hidden and shown).
288
+ stop(): void {
289
+ this.abandonSignIn();
290
+ this.clearTimers();
291
+ this.client?.destroy();
292
+ this.client = null;
293
+ }
294
+
295
+ signIn = async (): Promise<void> => {
296
+ const client = this.client;
297
+ if (!client || this.tokens) return;
298
+
299
+ this.abandonSignIn();
300
+ const attempt = this.attempt;
301
+ this.update({ status: "connecting", error: null, qr: null });
302
+
303
+ try {
304
+ const { flow } = this.state.browserSignIn;
305
+ const session = client.context
306
+ ? await this.connectInsideOrb(client)
307
+ : flow === "site"
308
+ ? await this.signInOnSite(attempt)
309
+ : flow === "local"
310
+ ? await this.signInLocally(client, attempt)
311
+ : null;
312
+ if (attempt !== this.attempt) return;
313
+
314
+ if (session) this.startSession(session, true);
315
+ else this.update({ status: "idle", qr: null });
316
+ } catch (reason) {
317
+ // A cancelled or superseded attempt reports nothing.
318
+ if (attempt !== this.attempt) return;
319
+ this.update({
320
+ status: "idle",
321
+ qr: null,
322
+ error: describeSignInError(reason),
323
+ });
324
+ } finally {
325
+ if (attempt === this.attempt) this.cancelPending = null;
326
+ }
327
+ };
328
+
329
+ cancel = (): void => {
330
+ this.abandonSignIn();
331
+ this.update({ status: "idle", qr: null });
332
+ };
333
+
334
+ signOut = async (): Promise<void> => {
335
+ this.abandonSignIn();
336
+ this.endSession(null);
337
+ if (this.state.browserSignIn.flow === "site") await endOnServer();
338
+ try {
339
+ await this.client?.disconnect();
340
+ } catch {
341
+ // Best effort: the page session has already ended.
342
+ }
343
+ };
344
+
345
+ private update(patch: Partial<SessionState>): void {
346
+ this.state = { ...this.state, ...patch };
347
+ for (const listener of this.listeners) listener();
348
+ }
349
+
350
+ private abandonSignIn(): void {
351
+ this.attempt += 1;
352
+ this.cancelPending?.();
353
+ this.cancelPending = null;
354
+ }
355
+
356
+ private clearTimers(): void {
357
+ if (this.expiryTimer) clearTimeout(this.expiryTimer);
358
+ if (this.renewTimer) clearTimeout(this.renewTimer);
359
+ this.expiryTimer = null;
360
+ this.renewTimer = null;
361
+ }
362
+
363
+ private handleContextChange(context: OrbAppContext): void {
364
+ this.update({ context });
365
+
366
+ // Never show a signed-in UI for another account.
367
+ const client = this.client;
368
+ if (
369
+ client &&
370
+ this.tokens &&
371
+ (context.user.profileId || this.boundToProfile) &&
372
+ !isSelectedAccount(client, this.tokens.accessToken)
373
+ ) {
374
+ this.endSession(null);
375
+ void this.restore();
376
+ }
377
+ }
378
+
379
+ /** Restores a browser session from this app's server after a reload. */
380
+ private async restoreSite(): Promise<void> {
381
+ if (this.tokens) return;
382
+
383
+ this.abandonSignIn();
384
+ const attempt = this.attempt;
385
+ this.update({ status: "restoring" });
386
+
387
+ const accessToken = await renewOnServer();
388
+ if (attempt !== this.attempt) return;
389
+ if (accessToken && accessToken !== "ended") {
390
+ this.siteRenewable = true;
391
+ this.startSession({ idToken: null, accessToken }, true);
392
+ } else {
393
+ this.update({ status: "idle" });
394
+ }
395
+ }
396
+
397
+ /**
398
+ * Signs the selected profile back in without showing UI when it already
399
+ * approved this app. On any failure the page shows the sign-in button.
400
+ */
401
+ private async restore(): Promise<void> {
402
+ const client = this.client;
403
+ if (!client || this.tokens) return;
404
+ if (client.context?.features.grantRenewal !== true) return;
405
+
406
+ this.abandonSignIn();
407
+ const attempt = this.attempt;
408
+ this.update({ status: "restoring" });
409
+
410
+ const session = await this.connectSilently(client);
411
+ if (attempt !== this.attempt) return;
412
+ if (session) this.startSession(session, true);
413
+ else this.update({ status: "idle" });
414
+ }
415
+
416
+ private async connectSilently(
417
+ client: OrbAppsClient,
418
+ ): Promise<Session | null> {
419
+ if (client.context?.features.grantRenewal !== true) return null;
420
+
421
+ try {
422
+ const tokens = await client.connect({
423
+ credentials: "id_access_refresh",
424
+ prompt: "none",
425
+ timeout: 30_000,
426
+ });
427
+ // connect answers for the profile selected when the host handles it:
428
+ // keep the answer only if it is still the selected profile.
429
+ return isSelectedAccount(client, tokens.accessToken)
430
+ ? toSession(tokens)
431
+ : null;
432
+ } catch {
433
+ // OrbConnectDeclinedError: not approved for this profile yet.
434
+ // OrbConnectError or OrbConnectTimeoutError: transient.
435
+ return null;
436
+ }
437
+ }
438
+
439
+ private async connectInsideOrb(client: OrbAppsClient): Promise<Session> {
440
+ const profileBefore = client.context?.user.profileId;
441
+ const tokens = await client.connect({ credentials: "id_access_refresh" });
442
+ if (
443
+ (profileBefore || client.context?.user.profileId) &&
444
+ !isSelectedAccount(client, tokens.accessToken)
445
+ ) {
446
+ throw new Error("Your Orb profile changed during sign-in. Try again.");
447
+ }
448
+ return toSession(tokens);
449
+ }
450
+
451
+ // Browser-site Sign in with Orb runs in the page against orbapi.xyz; never
452
+ // proxy it through the server. This origin opts in through
453
+ // /.well-known/orb-siwo.json. The renew binding lets the viewer stay
454
+ // logged in; this app's server then renews the session.
455
+ private async signInOnSite(attempt: number): Promise<Session> {
456
+ this.showQr({ message: "Preparing sign-in..." });
457
+ const renewBinding = await requestSiteRenewBinding();
458
+ if (attempt !== this.attempt) throw new Error("Sign-in cancelled.");
459
+ const { promise, cancel } = signInWithOrb({
460
+ renewBinding,
461
+ onQr: ({ qrCode, deepLink }) => {
462
+ if (attempt !== this.attempt) return;
463
+ this.showQr({
464
+ image: qrCode,
465
+ deepLink,
466
+ message: "Scan with the Orb app to sign in.",
467
+ });
468
+ },
469
+ onProvisioning: () => {
470
+ if (attempt !== this.attempt) return;
471
+ this.showQr({
472
+ message:
473
+ "Setting up Sign in with Orb for this site. The first sign-in can take a few minutes.",
474
+ });
475
+ },
476
+ });
477
+ this.cancelPending = cancel;
478
+
479
+ const result = await promise;
480
+ const renewable = await bindOnServer(result.accessToken);
481
+ if (attempt !== this.attempt) {
482
+ // Abandoned while binding: leave no session a reload would restore.
483
+ if (renewable) await endOnServer();
484
+ throw new Error("Sign-in cancelled.");
485
+ }
486
+ this.siteRenewable = renewable;
487
+ return { idToken: result.idToken, accessToken: result.accessToken };
488
+ }
489
+
490
+ // Local development sign-in for http://localhost, through this app's
491
+ // /api/local-sign-in routes.
492
+ private async signInLocally(
493
+ client: OrbAppsClient,
494
+ attempt: number,
495
+ ): Promise<Session> {
496
+ this.showQr({
497
+ message:
498
+ "Preparing local sign-in. The first one on this machine can take up to two minutes.",
499
+ });
500
+ const { promise, cancel } = client.connectWithQr({
501
+ deliveryMode: "poll",
502
+ credentials: "id_access",
503
+ acknowledgePollingRelayRisk: true,
504
+ qrInitUrl: "/api/local-sign-in/init",
505
+ qrStatusUrl: "/api/local-sign-in/status",
506
+ // Room for first-use setup plus approval on the phone.
507
+ timeout: 300_000,
508
+ onQrCode: (qrCode, deepLink) => {
509
+ if (attempt !== this.attempt) return;
510
+ this.showQr({
511
+ image: qrCode,
512
+ deepLink,
513
+ message: "Scan with the Orb app to sign in.",
514
+ });
515
+ },
516
+ });
517
+ this.cancelPending = cancel;
518
+
519
+ return toSession(await promise);
520
+ }
521
+
522
+ private showQr(prompt: Pick<QrPrompt, "message"> & Partial<QrPrompt>): void {
523
+ this.update({
524
+ qr: {
525
+ image: null,
526
+ deepLink: null,
527
+ ...prompt,
528
+ // A phone cannot scan its own screen: offer the approval link there.
529
+ showAppLink: Boolean(prompt.deepLink) && prefersOrbAppLink(),
530
+ },
531
+ });
532
+ }
533
+
534
+ private startSession(session: Session, loadProfile: boolean): void {
535
+ // A token without a readable expiry can't be ended on time: fail closed.
536
+ const expiresAt = getTokenExpiresAt(session.accessToken);
537
+ if (expiresAt === null) {
538
+ this.endSession(
539
+ "Orb returned a session without an expiry. Sign in again.",
540
+ );
541
+ return;
542
+ }
543
+
544
+ if (expiresAt <= Date.now()) {
545
+ this.endSession("Your Orb session expired. Sign in again.");
546
+ return;
547
+ }
548
+
549
+ this.clearTimers();
550
+ this.tokens = session;
551
+ this.boundToProfile = !!this.client?.context?.user.profileId;
552
+ this.update({
553
+ status: "signed-in",
554
+ qr: null,
555
+ error: null,
556
+ ...(loadProfile ? { user: null } : {}),
557
+ });
558
+ if (loadProfile) void this.loadUser(session);
559
+
560
+ // The page never holds a refresh token: the session lasts as long as
561
+ // the access token (about ten minutes). End it on time; inside Orb, try
562
+ // a silent renewal first, and in a browser ask this app's server.
563
+ const now = Date.now();
564
+ this.expiryTimer = setTimeout(
565
+ () => this.endSession("Your Orb session expired. Sign in again."),
566
+ Math.max(0, expiresAt - now),
567
+ );
568
+ if (this.client?.context?.features.grantRenewal === true) {
569
+ this.renewTimer = setTimeout(
570
+ () => void this.renew(),
571
+ Math.max(0, expiresAt - now - RENEW_BEFORE_EXPIRY_MS),
572
+ );
573
+ } else if (this.siteRenewable) {
574
+ this.renewTimer = setTimeout(
575
+ () => void this.renewSite(),
576
+ Math.max(0, expiresAt - now - SITE_RENEW_BEFORE_EXPIRY_MS),
577
+ );
578
+ }
579
+ }
580
+
581
+ private async renewSite(): Promise<void> {
582
+ const current = this.tokens;
583
+ if (!current || !this.siteRenewable) return;
584
+
585
+ const renewed = await renewOnServer();
586
+ if (this.tokens !== current) return;
587
+ if (renewed === "ended") {
588
+ // The expiry timer ends the session.
589
+ this.siteRenewable = false;
590
+ return;
591
+ }
592
+
593
+ const currentExpiry = getTokenExpiresAt(current.accessToken);
594
+ if (renewed) {
595
+ // Another sign-in in this browser replaced the server's session.
596
+ if (accountOf(renewed) !== accountOf(current.accessToken)) {
597
+ this.siteRenewable = false;
598
+ return;
599
+ }
600
+ const renewedExpiry = getTokenExpiresAt(renewed);
601
+ if (
602
+ renewedExpiry !== null &&
603
+ currentExpiry !== null &&
604
+ renewedExpiry > currentExpiry
605
+ ) {
606
+ this.startSession({ ...current, accessToken: renewed }, false);
607
+ return;
608
+ }
609
+ }
610
+
611
+ // Temporary: try again while the access token is still valid.
612
+ if (
613
+ currentExpiry !== null &&
614
+ currentExpiry - Date.now() > SITE_RENEW_RETRY_MS
615
+ ) {
616
+ this.renewTimer = setTimeout(
617
+ () => void this.renewSite(),
618
+ SITE_RENEW_RETRY_MS,
619
+ );
620
+ }
621
+ }
622
+
623
+ private async renew(): Promise<void> {
624
+ const client = this.client;
625
+ const current = this.tokens;
626
+ if (!client || !current) return;
627
+
628
+ const renewed = await this.connectSilently(client);
629
+ // A cached or barely extended token must not re-arm immediate renewal.
630
+ // Keep the current expiry timer when the host cannot extend the session.
631
+ const renewedExpiry = renewed
632
+ ? getTokenExpiresAt(renewed.accessToken)
633
+ : null;
634
+ const currentExpiry = getTokenExpiresAt(current.accessToken);
635
+ if (
636
+ renewed &&
637
+ renewedExpiry !== null &&
638
+ currentExpiry !== null &&
639
+ renewedExpiry > currentExpiry &&
640
+ renewedExpiry > Date.now() + RENEW_BEFORE_EXPIRY_MS &&
641
+ this.tokens === current &&
642
+ accountOf(renewed.accessToken) === accountOf(current.accessToken)
643
+ ) {
644
+ this.startSession(renewed, false);
645
+ }
646
+ }
647
+
648
+ private endSession(error: string | null): void {
649
+ this.clearTimers();
650
+ this.tokens = null;
651
+ this.boundToProfile = false;
652
+ this.siteRenewable = false;
653
+ this.update({
654
+ status: "idle",
655
+ user: null,
656
+ loadingUser: false,
657
+ qr: null,
658
+ error,
659
+ });
660
+ }
661
+
662
+ private async loadUser(session: Session): Promise<void> {
663
+ const address = OrbAppsClient.getAccountAddressFromToken(
664
+ session.idToken ?? session.accessToken,
665
+ );
666
+ if (!address) {
667
+ this.update({ error: "Could not read your account from Orb." });
668
+ return;
669
+ }
670
+
671
+ const isCurrent = () =>
672
+ !!this.tokens &&
673
+ accountOf(this.tokens.idToken ?? this.tokens.accessToken) ===
674
+ address.toLowerCase();
675
+
676
+ this.update({ loadingUser: true });
677
+ try {
678
+ const response = await fetch("/api/orb/user", {
679
+ method: "POST",
680
+ headers: { "content-type": "application/json" },
681
+ body: JSON.stringify({ address, xAccessToken: session.accessToken }),
682
+ });
683
+ const payload = (await response.json()) as UserResponse;
684
+ if (!response.ok || payload.status !== "SUCCESS" || !payload.data) {
685
+ throw new Error(
686
+ payload.message ?? payload.msg ?? "Could not load your profile.",
687
+ );
688
+ }
689
+ if (isCurrent()) this.update({ user: payload.data });
690
+ } catch (reason) {
691
+ if (isCurrent()) {
692
+ this.update({
693
+ error:
694
+ reason instanceof Error
695
+ ? reason.message
696
+ : "Could not load your profile.",
697
+ });
698
+ }
699
+ } finally {
700
+ if (isCurrent()) this.update({ loadingUser: false });
701
+ }
702
+ }
703
+ }