lazypock 0.19.0 → 0.19.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.
package/dist/index.d.cts CHANGED
@@ -467,6 +467,7 @@ declare class AuthStore {
467
467
  private _token;
468
468
  private _model;
469
469
  private _tokenExpiresAt;
470
+ private _refreshToken;
470
471
  private _collectionName;
471
472
  private listeners;
472
473
  private storage;
@@ -477,6 +478,13 @@ declare class AuthStore {
477
478
  constructor(storage?: StorageAdapter);
478
479
  /** The current JWT token string, or empty string if not authenticated. */
479
480
  get token(): string;
481
+ /**
482
+ * The refresh token for the current session, or empty string.
483
+ *
484
+ * Kept by the store so a session can outlive the access token (15 minutes on the
485
+ * server) even across a reload. Persisted under `auth_refresh_token`.
486
+ */
487
+ get refreshToken(): string;
480
488
  /** The current authenticated user record, or null. */
481
489
  get model(): AuthModel | null;
482
490
  /** Whether a token exists (does not check expiry). */
@@ -502,12 +510,32 @@ declare class AuthStore {
502
510
  init(): Promise<void>;
503
511
  /**
504
512
  * Update the current auth token and model, persist to storage, and notify listeners.
513
+ *
514
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
515
+ * which carries the real `expiresIn` and the refresh token.
516
+ *
505
517
  * @param token The JWT token string.
506
518
  * @param model The authenticated user record, or null for superusers.
507
519
  */
508
520
  set(token: string, model: AuthModel | null): void;
509
521
  /**
510
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
522
+ * Record a complete auth response: token, model, refresh token and the access
523
+ * token's real lifetime.
524
+ *
525
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
526
+ * it (an older server) falls back to the historical 7-day assumption.
527
+ *
528
+ * @param token The JWT access token.
529
+ * @param model The authenticated record, or null for a superuser.
530
+ * @param options `refreshToken` and `expiresIn` from the same response.
531
+ */
532
+ setSession(token: string, model: AuthModel | null, options?: {
533
+ refreshToken?: string;
534
+ expiresIn?: number;
535
+ }): void;
536
+ /**
537
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
538
+ * notify listeners.
511
539
  */
512
540
  clear(): void;
513
541
  private persistCollectionName;
@@ -549,7 +577,25 @@ declare class HttpClient {
549
577
  constructor(baseUrl: string, authStore: AuthStore, connectionId?: string);
550
578
  /** The API base URL (trailing slash stripped). Used for OAuth2 origin checks. */
551
579
  get baseUrl(): string;
580
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
581
+ private refreshInFlight;
582
+ /**
583
+ * Exchange the stored refresh token for a new access token.
584
+ *
585
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
586
+ * bearer — not the access token this used to send, which is why every refresh
587
+ * attempt 401'd and cleared the session. The collection is the one the session
588
+ * belongs to, or `_superusers` when the store has none (a superuser login).
589
+ *
590
+ * A network failure keeps the session (the next request can retry); only a refusal
591
+ * by the server ends it.
592
+ */
552
593
  private refreshAuth;
594
+ /** The store's current session, in the shape the old refresh returned. */
595
+ private currentAuthResponse;
596
+ private performRefresh;
597
+ /** The auth collection a refresh is addressed to, including superusers. */
598
+ private refreshCollection;
553
599
  /**
554
600
  * Globally enable or disable auto-cancellation of duplicated pending requests.
555
601
  * Fluent — returns `this` for chaining.
package/dist/index.d.ts CHANGED
@@ -467,6 +467,7 @@ declare class AuthStore {
467
467
  private _token;
468
468
  private _model;
469
469
  private _tokenExpiresAt;
470
+ private _refreshToken;
470
471
  private _collectionName;
471
472
  private listeners;
472
473
  private storage;
@@ -477,6 +478,13 @@ declare class AuthStore {
477
478
  constructor(storage?: StorageAdapter);
478
479
  /** The current JWT token string, or empty string if not authenticated. */
479
480
  get token(): string;
481
+ /**
482
+ * The refresh token for the current session, or empty string.
483
+ *
484
+ * Kept by the store so a session can outlive the access token (15 minutes on the
485
+ * server) even across a reload. Persisted under `auth_refresh_token`.
486
+ */
487
+ get refreshToken(): string;
480
488
  /** The current authenticated user record, or null. */
481
489
  get model(): AuthModel | null;
482
490
  /** Whether a token exists (does not check expiry). */
@@ -502,12 +510,32 @@ declare class AuthStore {
502
510
  init(): Promise<void>;
503
511
  /**
504
512
  * Update the current auth token and model, persist to storage, and notify listeners.
513
+ *
514
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
515
+ * which carries the real `expiresIn` and the refresh token.
516
+ *
505
517
  * @param token The JWT token string.
506
518
  * @param model The authenticated user record, or null for superusers.
507
519
  */
508
520
  set(token: string, model: AuthModel | null): void;
509
521
  /**
510
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
522
+ * Record a complete auth response: token, model, refresh token and the access
523
+ * token's real lifetime.
524
+ *
525
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
526
+ * it (an older server) falls back to the historical 7-day assumption.
527
+ *
528
+ * @param token The JWT access token.
529
+ * @param model The authenticated record, or null for a superuser.
530
+ * @param options `refreshToken` and `expiresIn` from the same response.
531
+ */
532
+ setSession(token: string, model: AuthModel | null, options?: {
533
+ refreshToken?: string;
534
+ expiresIn?: number;
535
+ }): void;
536
+ /**
537
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
538
+ * notify listeners.
511
539
  */
512
540
  clear(): void;
513
541
  private persistCollectionName;
@@ -549,7 +577,25 @@ declare class HttpClient {
549
577
  constructor(baseUrl: string, authStore: AuthStore, connectionId?: string);
550
578
  /** The API base URL (trailing slash stripped). Used for OAuth2 origin checks. */
551
579
  get baseUrl(): string;
580
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
581
+ private refreshInFlight;
582
+ /**
583
+ * Exchange the stored refresh token for a new access token.
584
+ *
585
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
586
+ * bearer — not the access token this used to send, which is why every refresh
587
+ * attempt 401'd and cleared the session. The collection is the one the session
588
+ * belongs to, or `_superusers` when the store has none (a superuser login).
589
+ *
590
+ * A network failure keeps the session (the next request can retry); only a refusal
591
+ * by the server ends it.
592
+ */
552
593
  private refreshAuth;
594
+ /** The store's current session, in the shape the old refresh returned. */
595
+ private currentAuthResponse;
596
+ private performRefresh;
597
+ /** The auth collection a refresh is addressed to, including superusers. */
598
+ private refreshCollection;
553
599
  /**
554
600
  * Globally enable or disable auto-cancellation of duplicated pending requests.
555
601
  * Fluent — returns `this` for chaining.
@@ -58,6 +58,7 @@ var Lazypock = (() => {
58
58
  };
59
59
 
60
60
  // src/http.ts
61
+ var SUPERUSERS = "_superusers";
61
62
  function isAbortError(err) {
62
63
  return err instanceof Error && (err.name === "AbortError" || err.message === "Aborted");
63
64
  }
@@ -84,6 +85,8 @@ var Lazypock = (() => {
84
85
  this.inflight = {};
85
86
  /** Global toggle for the auto-cancellation behaviour (default: on). */
86
87
  this.enableAutoCancellation = true;
88
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
89
+ this.refreshInFlight = null;
87
90
  this._baseUrl = baseUrl.replace(/\/+$/, "");
88
91
  this.authStore = authStore;
89
92
  this.connectionId = connectionId;
@@ -93,36 +96,83 @@ var Lazypock = (() => {
93
96
  get baseUrl() {
94
97
  return this._baseUrl;
95
98
  }
99
+ /**
100
+ * Exchange the stored refresh token for a new access token.
101
+ *
102
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
103
+ * bearer — not the access token this used to send, which is why every refresh
104
+ * attempt 401'd and cleared the session. The collection is the one the session
105
+ * belongs to, or `_superusers` when the store has none (a superuser login).
106
+ *
107
+ * A network failure keeps the session (the next request can retry); only a refusal
108
+ * by the server ends it.
109
+ */
96
110
  async refreshAuth() {
97
- const collection = this.authStore.collectionName;
98
- if (!collection) return null;
111
+ const refreshToken = this.authStore.refreshToken;
112
+ if (!refreshToken) return null;
113
+ if (this.refreshInFlight) {
114
+ const refreshed = await this.refreshInFlight;
115
+ return refreshed ? this.currentAuthResponse() : null;
116
+ }
117
+ this.refreshInFlight = this.performRefresh(refreshToken);
99
118
  try {
100
- const url = this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh";
101
- const headers = {
102
- "Content-Type": "application/json"
103
- };
104
- if (this.authStore.token) {
105
- headers["Authorization"] = "Bearer " + this.authStore.token;
106
- }
107
- const res = await this.defaultFetch(url, {
108
- method: "POST",
109
- headers
110
- });
119
+ const refreshed = await this.refreshInFlight;
120
+ return refreshed ? this.currentAuthResponse() : null;
121
+ } finally {
122
+ this.refreshInFlight = null;
123
+ }
124
+ }
125
+ /** The store's current session, in the shape the old refresh returned. */
126
+ currentAuthResponse() {
127
+ return {
128
+ token: this.authStore.token,
129
+ record: this.authStore.model ?? {}
130
+ };
131
+ }
132
+ async performRefresh(refreshToken) {
133
+ const collection = this.refreshCollection();
134
+ try {
135
+ const res = await this.defaultFetch(
136
+ this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
137
+ {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify({ refreshToken })
141
+ }
142
+ );
111
143
  if (!res.ok) {
112
- this.authStore.clear();
113
- return null;
144
+ if (res.status === 400 || res.status === 401) {
145
+ this.authStore.clear();
146
+ }
147
+ return false;
114
148
  }
115
149
  const data = await res.json();
116
- if (data && typeof data.token === "string") {
117
- const record = data["record"];
118
- const model = record && typeof record === "object" ? record : null;
119
- this.authStore.set(data.token, model);
120
- return data;
150
+ if (!data || typeof data.token !== "string") {
151
+ this.authStore.clear();
152
+ return false;
121
153
  }
122
- return null;
154
+ const record = data["record"];
155
+ const model = record && typeof record === "object" ? record : null;
156
+ this.authStore.setCollectionName(
157
+ collection === SUPERUSERS ? null : collection
158
+ );
159
+ this.authStore.setSession(data.token, model, {
160
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
161
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
162
+ });
163
+ return true;
123
164
  } catch {
124
- return null;
165
+ return false;
166
+ }
167
+ }
168
+ /** The auth collection a refresh is addressed to, including superusers. */
169
+ refreshCollection() {
170
+ if (this.authStore.collectionName) return this.authStore.collectionName;
171
+ const model = this.authStore.model;
172
+ if (model && typeof model.collectionName === "string" && model.collectionName) {
173
+ return model.collectionName;
125
174
  }
175
+ return SUPERUSERS;
126
176
  }
127
177
  /**
128
178
  * Globally enable or disable auto-cancellation of duplicated pending requests.
@@ -169,7 +219,7 @@ var Lazypock = (() => {
169
219
  * (aborted requests throw an `ApiError` with `isAbort === true`).
170
220
  */
171
221
  async request(method, path, body, options) {
172
- if (this.authStore.isExpired && this.authStore.collectionName) {
222
+ if (this.authStore.isExpired && this.authStore.refreshToken) {
173
223
  await this.refreshAuth();
174
224
  }
175
225
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
@@ -260,8 +310,9 @@ var Lazypock = (() => {
260
310
  }
261
311
  let res = null;
262
312
  const fetcher = options?.fetch ?? this.defaultFetch;
313
+ const send = async () => fetcher(url, init);
263
314
  try {
264
- res = await fetcher(url, init);
315
+ res = await send();
265
316
  } catch (err) {
266
317
  if (isAbortError(err)) {
267
318
  throw new ApiError(
@@ -277,6 +328,27 @@ var Lazypock = (() => {
277
328
  delete this.cancelControllers[requestKey];
278
329
  }
279
330
  }
331
+ if (res.status === 401 && this.authStore.refreshToken) {
332
+ await res.text().catch(() => {
333
+ });
334
+ const refreshed = await this.refreshAuth();
335
+ if (refreshed) {
336
+ headers["Authorization"] = "Bearer " + this.authStore.token;
337
+ try {
338
+ res = await send();
339
+ } catch (err) {
340
+ if (isAbortError(err)) {
341
+ throw new ApiError(
342
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
343
+ {},
344
+ 0,
345
+ true
346
+ );
347
+ }
348
+ throw err;
349
+ }
350
+ }
351
+ }
280
352
  if (res.status === 204) return null;
281
353
  let bodyText = "";
282
354
  let data = {};
@@ -351,6 +423,7 @@ var Lazypock = (() => {
351
423
  this._token = "";
352
424
  this._model = null;
353
425
  this._tokenExpiresAt = null;
426
+ this._refreshToken = "";
354
427
  this._collectionName = null;
355
428
  this.listeners = /* @__PURE__ */ new Set();
356
429
  this.storage = storage ?? {
@@ -365,6 +438,15 @@ var Lazypock = (() => {
365
438
  get token() {
366
439
  return this._token;
367
440
  }
441
+ /**
442
+ * The refresh token for the current session, or empty string.
443
+ *
444
+ * Kept by the store so a session can outlive the access token (15 minutes on the
445
+ * server) even across a reload. Persisted under `auth_refresh_token`.
446
+ */
447
+ get refreshToken() {
448
+ return this._refreshToken;
449
+ }
368
450
  /** The current authenticated user record, or null. */
369
451
  get model() {
370
452
  return this._model;
@@ -399,14 +481,16 @@ var Lazypock = (() => {
399
481
  * Should be called once at application startup.
400
482
  */
401
483
  async init() {
402
- const [token, model, expiresAt, collectionName] = await Promise.all([
484
+ const [token, model, expiresAt, collectionName, refreshToken] = await Promise.all([
403
485
  this.storage.get("auth_token"),
404
486
  this.storage.get("auth_model"),
405
487
  this.storage.get("auth_expires_at"),
406
- this.storage.get("auth_collection")
488
+ this.storage.get("auth_collection"),
489
+ this.storage.get("auth_refresh_token")
407
490
  ]);
408
491
  if (token) this._token = token;
409
492
  if (expiresAt) this._tokenExpiresAt = parseInt(expiresAt, 10) || null;
493
+ if (refreshToken) this._refreshToken = refreshToken;
410
494
  if (model) {
411
495
  try {
412
496
  this._model = JSON.parse(model);
@@ -421,6 +505,10 @@ var Lazypock = (() => {
421
505
  }
422
506
  /**
423
507
  * Update the current auth token and model, persist to storage, and notify listeners.
508
+ *
509
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
510
+ * which carries the real `expiresIn` and the refresh token.
511
+ *
424
512
  * @param token The JWT token string.
425
513
  * @param model The authenticated user record, or null for superusers.
426
514
  */
@@ -440,18 +528,44 @@ var Lazypock = (() => {
440
528
  this.notify();
441
529
  }
442
530
  /**
443
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
531
+ * Record a complete auth response: token, model, refresh token and the access
532
+ * token's real lifetime.
533
+ *
534
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
535
+ * it (an older server) falls back to the historical 7-day assumption.
536
+ *
537
+ * @param token The JWT access token.
538
+ * @param model The authenticated record, or null for a superuser.
539
+ * @param options `refreshToken` and `expiresIn` from the same response.
540
+ */
541
+ setSession(token, model, options) {
542
+ this.set(token, model);
543
+ if (options?.refreshToken) {
544
+ this._refreshToken = options.refreshToken;
545
+ void this.storage.set("auth_refresh_token", options.refreshToken);
546
+ }
547
+ const expiresIn = options?.expiresIn;
548
+ if (typeof expiresIn === "number" && expiresIn > 0) {
549
+ this._tokenExpiresAt = Date.now() + expiresIn * 1e3;
550
+ void this.storage.set("auth_expires_at", String(this._tokenExpiresAt));
551
+ }
552
+ }
553
+ /**
554
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
555
+ * notify listeners.
444
556
  */
445
557
  clear() {
446
558
  this._token = "";
447
559
  this._model = null;
448
560
  this._tokenExpiresAt = null;
561
+ this._refreshToken = "";
449
562
  this._collectionName = null;
450
563
  void Promise.all([
451
564
  this.storage.remove("auth_token"),
452
565
  this.storage.remove("auth_expires_at"),
453
566
  this.storage.remove("auth_model"),
454
- this.storage.remove("auth_collection")
567
+ this.storage.remove("auth_collection"),
568
+ this.storage.remove("auth_refresh_token")
455
569
  ]);
456
570
  this.notify();
457
571
  }
@@ -473,6 +587,13 @@ var Lazypock = (() => {
473
587
  }
474
588
  }
475
589
  };
590
+ function rememberAuthResponse(store, data, model) {
591
+ if (!data || typeof data.token !== "string" || !data.token) return;
592
+ store.setSession(data.token, model, {
593
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
594
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
595
+ });
596
+ }
476
597
  var memoryStorage = {
477
598
  get(key) {
478
599
  try {
@@ -1541,7 +1662,11 @@ var Lazypock = (() => {
1541
1662
  );
1542
1663
  if (data && this.authStore) {
1543
1664
  this.authStore.setCollectionName(this.collectionName);
1544
- this.authStore.set(data.token, data.record);
1665
+ rememberAuthResponse(
1666
+ this.authStore,
1667
+ data,
1668
+ data.record
1669
+ );
1545
1670
  }
1546
1671
  return data;
1547
1672
  }
@@ -1552,12 +1677,16 @@ var Lazypock = (() => {
1552
1677
  async authRefresh(options) {
1553
1678
  const data = await this.http.post(
1554
1679
  this.collectionPath() + "/auth-refresh",
1555
- void 0,
1680
+ { refreshToken: this.authStore?.refreshToken },
1556
1681
  options
1557
1682
  );
1558
1683
  if (data && this.authStore) {
1559
1684
  this.authStore.setCollectionName(this.collectionName);
1560
- this.authStore.set(data.token, data.record);
1685
+ rememberAuthResponse(
1686
+ this.authStore,
1687
+ data,
1688
+ data.record
1689
+ );
1561
1690
  }
1562
1691
  return data;
1563
1692
  }
@@ -1740,7 +1869,11 @@ var Lazypock = (() => {
1740
1869
  }
1741
1870
  if (this.authStore) {
1742
1871
  this.authStore.setCollectionName(this.collectionName);
1743
- this.authStore.set(data.token, data.record);
1872
+ rememberAuthResponse(
1873
+ this.authStore,
1874
+ data,
1875
+ data.record
1876
+ );
1744
1877
  }
1745
1878
  return data;
1746
1879
  }
@@ -2801,7 +2934,7 @@ ${opts.body}
2801
2934
  const data = await this.http.post("/superusers/setup", { email, password });
2802
2935
  if (data) {
2803
2936
  this.authStore.setCollectionName(null);
2804
- this.authStore.set(data.token, null);
2937
+ rememberAuthResponse(this.authStore, data, null);
2805
2938
  }
2806
2939
  return data;
2807
2940
  }
@@ -2825,7 +2958,11 @@ ${opts.body}
2825
2958
  });
2826
2959
  if (data && data.record) {
2827
2960
  this.authStore.setCollectionName(collection);
2828
- this.authStore.set(data.token, data.record);
2961
+ rememberAuthResponse(
2962
+ this.authStore,
2963
+ data,
2964
+ data.record
2965
+ );
2829
2966
  }
2830
2967
  } else {
2831
2968
  try {
@@ -2841,7 +2978,7 @@ ${opts.body}
2841
2978
  }
2842
2979
  if (data) {
2843
2980
  this.authStore.setCollectionName(null);
2844
- this.authStore.set(data.token, null);
2981
+ rememberAuthResponse(this.authStore, data, null);
2845
2982
  }
2846
2983
  }
2847
2984
  return data;
@@ -2875,7 +3012,7 @@ ${opts.body}
2875
3012
  );
2876
3013
  if (data) {
2877
3014
  this.authStore.setCollectionName(collection);
2878
- this.authStore.set(data.token, data.record);
3015
+ rememberAuthResponse(this.authStore, data, data.record);
2879
3016
  }
2880
3017
  return data;
2881
3018
  }
@@ -2889,12 +3026,12 @@ ${opts.body}
2889
3026
  async authRefresh(collection, options) {
2890
3027
  const data = await this.http.post(
2891
3028
  "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
2892
- void 0,
3029
+ { refreshToken: this.authStore.refreshToken },
2893
3030
  options
2894
3031
  );
2895
3032
  if (data) {
2896
3033
  this.authStore.setCollectionName(collection);
2897
- this.authStore.set(data.token, data.record);
3034
+ rememberAuthResponse(this.authStore, data, data.record);
2898
3035
  }
2899
3036
  return data;
2900
3037
  }