eocene-auth-sdk 0.3.0 → 0.4.0

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.0
4
+
5
+ ### Added
6
+
7
+ - **Persistent session recovery.** `AuthClient.restoreSession()` and the matching
8
+ `useAuth()` method restore a usable local access token or use the project-managed
9
+ refresh cookie. Concurrent calls share one refresh flow. `<AuthProvider>` now
10
+ finishes startup recovery before setting `ready` to `true`.
11
+ - **Refresh-cookie logout.** `logout()` starts a credentialed request to revoke the
12
+ server-side refresh session before synchronously clearing local access state.
13
+
14
+ ### Changed
15
+
16
+ - Local tokens that are expired, malformed, missing `exp`, or within one minute of
17
+ expiry are refreshed rather than treated as a successful local restore.
18
+ - Session lifetime and refresh policy come from the server-side project
19
+ `sessionPolicy`; refresh and logout requests include cookies and `projectId`.
20
+
3
21
  ## 0.3.0
4
22
 
5
23
  ### Added
package/README.md CHANGED
@@ -68,17 +68,41 @@ read -rs NPM_TOKEN && export NPM_TOKEN && npm run publish:token
68
68
  The token is only exported to the npm subprocess; the temp `.npmrc` references
69
69
  `${NPM_TOKEN}`, never the literal value.
70
70
 
71
- ### Session expiry
71
+ ### Persistent sessions and startup recovery
72
72
 
73
- Sessions are short-lived and cannot be refreshed. Route the user back to login
74
- when one expires:
73
+ `AuthProvider` automatically restores the session on startup and sets `ready` to
74
+ `true` only after that attempt finishes. A local token with an address is used
75
+ when it is valid for more than one minute; otherwise the SDK calls
76
+ `POST {controlBaseUrl}/auth/session/refresh` with `credentials: 'include'` and the
77
+ configured `projectId`. A missing or rejected refresh cookie leaves the app signed
78
+ out without triggering a redirect. `restoreSession(): Promise<boolean>` is also
79
+ available from `useAuth()` for an explicit retry; concurrent calls share one flow.
80
+
81
+ ```tsx
82
+ const { ready, authenticated, restoreSession } = useAuth()
83
+ ```
84
+
85
+ Access tokens remain in `sessionStorage`. Refresh cookies are managed by Eocene
86
+ per project, and access/refresh lifetime and rotation are controlled by the
87
+ server-side project `sessionPolicy`, not by SDK configuration. The refresh and
88
+ logout endpoints require credentialed CORS: allow the exact application origin and
89
+ `Access-Control-Allow-Credentials` (a wildcard origin is insufficient). Cross-site
90
+ cookies also require browser-compatible `Secure` / `SameSite=None` settings and may
91
+ be blocked by third-party-cookie policy; a same-site proxy avoids that restriction.
92
+
93
+ ### Session expiry and logout
94
+
95
+ A 401 from an access-token request clears local access state and flips
96
+ `authenticated` to `false`, but does not revoke the refresh cookie. Route the user
97
+ back to login when appropriate:
75
98
 
76
99
  ```tsx
77
100
  <AuthProvider config={config} onSessionExpired={() => nav('/login')}>
78
101
  ```
79
102
 
80
- By the time `onSessionExpired` fires, local state is already cleared and
81
- `authenticated` has flipped to `false`.
103
+ `logout()` remains synchronous for local state. It starts the credentialed remote
104
+ revocation request first, then clears the access token and wallet state; the remote
105
+ request is best-effort and failures are not surfaced to the synchronous caller.
82
106
 
83
107
  ### Multi-chain
84
108
 
package/dist/index.d.ts CHANGED
@@ -50,9 +50,10 @@ type WaasSignApprovalResult = boolean | {
50
50
  type WaasClientOptions = {
51
51
  controlBaseUrl: string;
52
52
  /**
53
- * Called when the control-plane rejects the session (401). Sessions expire
54
- * after an hour and cannot be refreshed, so the host has to send the user
55
- * through login again.
53
+ * Called when the control-plane rejects the session (401). Access tokens
54
+ * default to one hour. POST /auth/session/refresh can rotate the project
55
+ * refresh cookie or slide a still-valid Bearer token; an expired Bearer
56
+ * token cannot be refreshed.
56
57
  */
57
58
  onSessionExpired?: () => void;
58
59
  };
@@ -308,8 +309,8 @@ type AuthClientOptions = {
308
309
  config: AuthSdkConfig;
309
310
  requestApproval?: (req: WaasSignApprovalRequest) => Promise<WaasSignApprovalResult>;
310
311
  /**
311
- * Called when the control-plane rejects the session (401). Sessions last one
312
- * hour and cannot be refreshed, so hosts should route the user back to login.
312
+ * Called when the control-plane rejects the session (401). Access-token TTL is
313
+ * project-configurable; hosts may restore through the persistent refresh cookie.
313
314
  */
314
315
  onSessionExpired?: () => void;
315
316
  /** Initial EVM chain for the EIP-1193 provider. Default 1 (Ethereum). */
@@ -323,6 +324,7 @@ declare class AuthClient {
323
324
  private provider;
324
325
  private chainId;
325
326
  private active;
327
+ private restorePromise;
326
328
  private requestApproval?;
327
329
  private onSessionExpired?;
328
330
  constructor(options: AuthClientOptions);
@@ -355,7 +357,11 @@ declare class AuthClient {
355
357
  completeOAuthFromHash(hashOrSearch: string): Promise<AuthLoginResult>;
356
358
  takeOAuthReturnPath(): string | null;
357
359
  markActive(on: boolean): void;
360
+ private restoreLocalSession;
361
+ private localSessionNeedsRefresh;
358
362
  restoreIfNeeded(): boolean;
363
+ restoreSession(): Promise<boolean>;
364
+ private performRestoreSession;
359
365
  logout(): void;
360
366
  setPassword(password: string, currentPassword?: string): Promise<void>;
361
367
  clearPassword(password: string): Promise<void>;
@@ -396,6 +402,7 @@ type AuthContextValue = {
396
402
  logout: () => void;
397
403
  markActive: (on: boolean) => void;
398
404
  restoreIfNeeded: () => boolean;
405
+ restoreSession: () => Promise<boolean>;
399
406
  completeOAuthFromHash: (hashOrSearch: string) => Promise<AuthLoginResult>;
400
407
  takeOAuthReturnPath: () => string | null;
401
408
  getProvider: () => WaasEip1193Provider;
@@ -415,9 +422,9 @@ type AuthProviderProps = {
415
422
  components?: AuthSdkComponents;
416
423
  onRequestSignApproval?: (req: WaasSignApprovalRequest) => Promise<WaasSignApprovalResult>;
417
424
  /**
418
- * Called when the session expires (1h, not refreshable). The provider has
419
- * already cleared local state and `authenticated` has flipped to false; use
420
- * this to route the user back to your login screen.
425
+ * Called when the session is rejected (401). The provider has already cleared
426
+ * local access state. Hosts may restore through the persistent refresh cookie;
427
+ * only a failed restore requires the user to connect the signer again.
421
428
  */
422
429
  onSessionExpired?: () => void;
423
430
  children: ReactNode;
package/dist/index.js CHANGED
@@ -2814,7 +2814,7 @@ function createWaasEip1193Provider(client, options) {
2814
2814
 
2815
2815
  // ../eocene-worker/packages/sdk/src/index.ts
2816
2816
  async function http(url, init) {
2817
- const res = await fetch(url, init);
2817
+ const res = await fetch(url, { credentials: "include", ...init });
2818
2818
  const body = await res.json().catch(() => ({}));
2819
2819
  if (!res.ok) {
2820
2820
  throw new WaasHttpError(res.status, url, body);
@@ -3042,6 +3042,24 @@ function getTelegramInitData() {
3042
3042
 
3043
3043
  // src/client/AuthClient.ts
3044
3044
  var SOCIAL_METHODS = ["google", "twitter", "github", "apple", "telegram"];
3045
+ var RESTORE_EXPIRY_BUFFER_MS = 6e4;
3046
+ var RESTORE_REFRESH_WITHIN_MS = 15 * 60 * 1e3;
3047
+ function sessionTokenExpMs(sessionToken) {
3048
+ try {
3049
+ const encoded = sessionToken.split(".")[1];
3050
+ if (!encoded) return null;
3051
+ const base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
3052
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
3053
+ const payload = JSON.parse(atob(padded));
3054
+ return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp * 1e3 : null;
3055
+ } catch {
3056
+ return null;
3057
+ }
3058
+ }
3059
+ function hasUsableSessionToken(sessionToken) {
3060
+ const expMs = sessionTokenExpMs(sessionToken);
3061
+ return expMs != null && expMs > Date.now() + RESTORE_EXPIRY_BUFFER_MS;
3062
+ }
3045
3063
  var AuthClient = class {
3046
3064
  config;
3047
3065
  storageKey;
@@ -3050,6 +3068,7 @@ var AuthClient = class {
3050
3068
  provider = null;
3051
3069
  chainId;
3052
3070
  active = false;
3071
+ restorePromise = null;
3053
3072
  requestApproval;
3054
3073
  onSessionExpired;
3055
3074
  constructor(options) {
@@ -3073,7 +3092,7 @@ var AuthClient = class {
3073
3092
  const saved = loadPersistedState(this.storageKey);
3074
3093
  if (saved?.sessionToken) {
3075
3094
  this.client.hydrate(saved);
3076
- if (saved.address) this.active = true;
3095
+ this.active = Boolean(saved.address && hasUsableSessionToken(saved.sessionToken));
3077
3096
  }
3078
3097
  }
3079
3098
  setRequestApproval(fn) {
@@ -3286,16 +3305,86 @@ var AuthClient = class {
3286
3305
  this.persist();
3287
3306
  }
3288
3307
  }
3289
- restoreIfNeeded() {
3290
- const saved = loadPersistedState(this.storageKey);
3291
- if (!saved?.sessionToken || !saved.address) return false;
3308
+ restoreLocalSession() {
3309
+ const saved = loadPersistedState(this.storageKey) ?? this.client.getState();
3310
+ if (!saved?.sessionToken || !saved.address || !hasUsableSessionToken(saved.sessionToken)) return false;
3292
3311
  this.client.hydrate(saved);
3293
3312
  this.active = true;
3294
3313
  this.provider = null;
3295
3314
  return true;
3296
3315
  }
3316
+ localSessionNeedsRefresh() {
3317
+ const token = loadPersistedState(this.storageKey)?.sessionToken ?? this.client.getState()?.sessionToken;
3318
+ const expMs = token ? sessionTokenExpMs(token) : null;
3319
+ return expMs == null || expMs <= Date.now() + RESTORE_REFRESH_WITHIN_MS;
3320
+ }
3321
+ restoreIfNeeded() {
3322
+ return this.restoreLocalSession();
3323
+ }
3324
+ restoreSession() {
3325
+ if (this.restorePromise) return this.restorePromise;
3326
+ this.restorePromise = this.performRestoreSession().finally(() => {
3327
+ this.restorePromise = null;
3328
+ });
3329
+ return this.restorePromise;
3330
+ }
3331
+ async performRestoreSession() {
3332
+ const restoreLocalIfCurrent = () => this.restoreLocalSession() && !this.localSessionNeedsRefresh();
3333
+ if (restoreLocalIfCurrent()) return true;
3334
+ const restore = async () => {
3335
+ if (restoreLocalIfCurrent()) return true;
3336
+ try {
3337
+ const base = resolveControlAbsoluteUrl(this.config.controlBaseUrl);
3338
+ const url = `${base}/auth/session/refresh`;
3339
+ const body = JSON.stringify({ projectId: this.config.projectId });
3340
+ let res = await fetch(url, {
3341
+ method: "POST",
3342
+ credentials: "include",
3343
+ headers: { "content-type": "application/json" },
3344
+ body
3345
+ });
3346
+ const legacyToken = loadPersistedState(this.storageKey)?.sessionToken;
3347
+ const legacyExpMs = legacyToken ? sessionTokenExpMs(legacyToken) : null;
3348
+ if (res.status === 401 && legacyToken && legacyExpMs != null && legacyExpMs > Date.now()) {
3349
+ res = await fetch(url, {
3350
+ method: "POST",
3351
+ credentials: "include",
3352
+ headers: { "content-type": "application/json", authorization: `Bearer ${legacyToken}` },
3353
+ body
3354
+ });
3355
+ }
3356
+ const result = await res.json().catch(() => ({}));
3357
+ if (!res.ok || !result.sessionToken) throw new Error(`session refresh HTTP ${res.status}`);
3358
+ await this.client.loginWithSessionToken(result.sessionToken);
3359
+ await this.client.ensureWallet();
3360
+ this.persist();
3361
+ this.active = true;
3362
+ this.provider = null;
3363
+ return true;
3364
+ } catch {
3365
+ if (!this.restoreLocalSession()) this.markActive(false);
3366
+ return false;
3367
+ }
3368
+ };
3369
+ if (typeof navigator !== "undefined" && navigator.locks) {
3370
+ return navigator.locks.request(`eocene:restore:${this.storageKey}`, restore);
3371
+ }
3372
+ return restore();
3373
+ }
3297
3374
  logout() {
3298
- this.markActive(false);
3375
+ const base = resolveControlAbsoluteUrl(this.config.controlBaseUrl);
3376
+ try {
3377
+ void fetch(`${base}/auth/session/logout`, {
3378
+ method: "POST",
3379
+ credentials: "include",
3380
+ keepalive: true,
3381
+ headers: { "content-type": "application/json" },
3382
+ body: JSON.stringify({ projectId: this.config.projectId })
3383
+ }).catch(() => {
3384
+ });
3385
+ } finally {
3386
+ this.markActive(false);
3387
+ }
3299
3388
  }
3300
3389
  async setPassword(password, currentPassword) {
3301
3390
  await this.client.setPassword(password, currentPassword);
@@ -3979,13 +4068,16 @@ function AuthProvider({
3979
4068
  );
3980
4069
  const [tick, setTick] = useState(0);
3981
4070
  const [ready, setReady] = useState(false);
4071
+ const mountedRef = useRef(false);
3982
4072
  const sessionExpiredRef = useRef(void 0);
3983
4073
  sessionExpiredRef.current = onSessionExpired;
3984
4074
  const handleSessionExpired = useCallback(() => {
3985
4075
  pendingSignRef.current?.resolve(false);
3986
4076
  pendingSignRef.current = null;
3987
- setPendingSign(null);
3988
- setTick((n) => n + 1);
4077
+ if (mountedRef.current) {
4078
+ setPendingSign(null);
4079
+ setTick((n) => n + 1);
4080
+ }
3989
4081
  sessionExpiredRef.current?.();
3990
4082
  }, []);
3991
4083
  const clientRef = useRef(null);
@@ -3997,26 +4089,52 @@ function AuthProvider({
3997
4089
  onSessionExpired: handleSessionExpired
3998
4090
  });
3999
4091
  }
4092
+ useEffect(() => {
4093
+ mountedRef.current = true;
4094
+ return () => {
4095
+ mountedRef.current = false;
4096
+ };
4097
+ }, []);
4000
4098
  useEffect(() => {
4001
4099
  clientRef.current?.setRequestApproval(approvalFn);
4002
4100
  }, [approvalFn]);
4003
4101
  useEffect(() => {
4004
4102
  const c = clientRef.current;
4005
4103
  if (!c) return;
4006
- if (c.config.controlBaseUrl !== config.controlBaseUrl || c.config.oauthReturnTo !== config.oauthReturnTo) {
4104
+ if (c.config.controlBaseUrl !== config.controlBaseUrl || c.config.oauthReturnTo !== config.oauthReturnTo || c.config.projectId !== config.projectId || c.config.chainId !== config.chainId || c.config.asDeveloper !== config.asDeveloper || c.config.storageKey !== config.storageKey || c.config.oauthPendingKey !== config.oauthPendingKey || c.config.allowDevLoginFallback !== config.allowDevLoginFallback) {
4007
4105
  clientRef.current = new AuthClient({
4008
4106
  config,
4107
+ chainId: config.chainId,
4009
4108
  requestApproval: approvalFn,
4010
4109
  onSessionExpired: handleSessionExpired
4011
4110
  });
4111
+ setReady(false);
4012
4112
  setTick((n) => n + 1);
4013
4113
  }
4014
4114
  }, [config, approvalFn, handleSessionExpired]);
4015
4115
  useEffect(() => {
4016
- clientRef.current?.restoreIfNeeded();
4017
- setReady(true);
4018
- setTick((n) => n + 1);
4019
- }, []);
4116
+ let alive = true;
4117
+ const c = clientRef.current;
4118
+ if (!c) return;
4119
+ setReady(false);
4120
+ void c.restoreSession().then(() => {
4121
+ if (!alive || clientRef.current !== c) return;
4122
+ setTick((n) => n + 1);
4123
+ setReady(true);
4124
+ });
4125
+ return () => {
4126
+ alive = false;
4127
+ };
4128
+ }, [
4129
+ config.controlBaseUrl,
4130
+ config.oauthReturnTo,
4131
+ config.projectId,
4132
+ config.chainId,
4133
+ config.asDeveloper,
4134
+ config.storageKey,
4135
+ config.oauthPendingKey,
4136
+ config.allowDevLoginFallback
4137
+ ]);
4020
4138
  const [availableMethods, setAvailableMethods] = useState(null);
4021
4139
  useEffect(() => {
4022
4140
  let alive = true;
@@ -4030,7 +4148,9 @@ function AuthProvider({
4030
4148
  alive = false;
4031
4149
  };
4032
4150
  }, [config.controlBaseUrl, config.projectId]);
4033
- const bump = useCallback(() => setTick((n) => n + 1), []);
4151
+ const bump = useCallback(() => {
4152
+ if (mountedRef.current) setTick((n) => n + 1);
4153
+ }, []);
4034
4154
  const login = useCallback(
4035
4155
  async (args) => {
4036
4156
  const result = await clientRef.current.login(args.method);
@@ -4060,6 +4180,12 @@ function AuthProvider({
4060
4180
  bump();
4061
4181
  return ok;
4062
4182
  }, [bump]);
4183
+ const restoreSession = useCallback(async () => {
4184
+ const c = clientRef.current;
4185
+ const ok = await c.restoreSession();
4186
+ if (clientRef.current === c) bump();
4187
+ return ok;
4188
+ }, [bump]);
4063
4189
  const completeOAuthFromHash = useCallback(
4064
4190
  async (hashOrSearch) => {
4065
4191
  const result = await clientRef.current.completeOAuthFromHash(hashOrSearch);
@@ -4204,6 +4330,7 @@ function AuthProvider({
4204
4330
  logout,
4205
4331
  markActive,
4206
4332
  restoreIfNeeded,
4333
+ restoreSession,
4207
4334
  completeOAuthFromHash,
4208
4335
  takeOAuthReturnPath,
4209
4336
  getProvider,
@@ -4228,6 +4355,7 @@ function AuthProvider({
4228
4355
  logout,
4229
4356
  markActive,
4230
4357
  restoreIfNeeded,
4358
+ restoreSession,
4231
4359
  completeOAuthFromHash,
4232
4360
  takeOAuthReturnPath,
4233
4361
  getProvider,