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.js CHANGED
@@ -19,6 +19,7 @@ var ApiError = class extends Error {
19
19
  };
20
20
 
21
21
  // src/http.ts
22
+ var SUPERUSERS = "_superusers";
22
23
  function isAbortError(err) {
23
24
  return err instanceof Error && (err.name === "AbortError" || err.message === "Aborted");
24
25
  }
@@ -45,6 +46,8 @@ var HttpClient = class {
45
46
  this.inflight = {};
46
47
  /** Global toggle for the auto-cancellation behaviour (default: on). */
47
48
  this.enableAutoCancellation = true;
49
+ /** A refresh already in flight, so concurrent requests rotate once, not N times. */
50
+ this.refreshInFlight = null;
48
51
  this._baseUrl = baseUrl.replace(/\/+$/, "");
49
52
  this.authStore = authStore;
50
53
  this.connectionId = connectionId;
@@ -54,36 +57,83 @@ var HttpClient = class {
54
57
  get baseUrl() {
55
58
  return this._baseUrl;
56
59
  }
60
+ /**
61
+ * Exchange the stored refresh token for a new access token.
62
+ *
63
+ * The server's `auth-refresh` wants the **refresh** token — in the body, or as the
64
+ * bearer — not the access token this used to send, which is why every refresh
65
+ * attempt 401'd and cleared the session. The collection is the one the session
66
+ * belongs to, or `_superusers` when the store has none (a superuser login).
67
+ *
68
+ * A network failure keeps the session (the next request can retry); only a refusal
69
+ * by the server ends it.
70
+ */
57
71
  async refreshAuth() {
58
- const collection = this.authStore.collectionName;
59
- if (!collection) return null;
72
+ const refreshToken = this.authStore.refreshToken;
73
+ if (!refreshToken) return null;
74
+ if (this.refreshInFlight) {
75
+ const refreshed = await this.refreshInFlight;
76
+ return refreshed ? this.currentAuthResponse() : null;
77
+ }
78
+ this.refreshInFlight = this.performRefresh(refreshToken);
60
79
  try {
61
- const url = this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh";
62
- const headers = {
63
- "Content-Type": "application/json"
64
- };
65
- if (this.authStore.token) {
66
- headers["Authorization"] = "Bearer " + this.authStore.token;
67
- }
68
- const res = await this.defaultFetch(url, {
69
- method: "POST",
70
- headers
71
- });
80
+ const refreshed = await this.refreshInFlight;
81
+ return refreshed ? this.currentAuthResponse() : null;
82
+ } finally {
83
+ this.refreshInFlight = null;
84
+ }
85
+ }
86
+ /** The store's current session, in the shape the old refresh returned. */
87
+ currentAuthResponse() {
88
+ return {
89
+ token: this.authStore.token,
90
+ record: this.authStore.model ?? {}
91
+ };
92
+ }
93
+ async performRefresh(refreshToken) {
94
+ const collection = this.refreshCollection();
95
+ try {
96
+ const res = await this.defaultFetch(
97
+ this.baseUrl + "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
98
+ {
99
+ method: "POST",
100
+ headers: { "Content-Type": "application/json" },
101
+ body: JSON.stringify({ refreshToken })
102
+ }
103
+ );
72
104
  if (!res.ok) {
73
- this.authStore.clear();
74
- return null;
105
+ if (res.status === 400 || res.status === 401) {
106
+ this.authStore.clear();
107
+ }
108
+ return false;
75
109
  }
76
110
  const data = await res.json();
77
- if (data && typeof data.token === "string") {
78
- const record = data["record"];
79
- const model = record && typeof record === "object" ? record : null;
80
- this.authStore.set(data.token, model);
81
- return data;
111
+ if (!data || typeof data.token !== "string") {
112
+ this.authStore.clear();
113
+ return false;
82
114
  }
83
- return null;
115
+ const record = data["record"];
116
+ const model = record && typeof record === "object" ? record : null;
117
+ this.authStore.setCollectionName(
118
+ collection === SUPERUSERS ? null : collection
119
+ );
120
+ this.authStore.setSession(data.token, model, {
121
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
122
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
123
+ });
124
+ return true;
84
125
  } catch {
85
- return null;
126
+ return false;
127
+ }
128
+ }
129
+ /** The auth collection a refresh is addressed to, including superusers. */
130
+ refreshCollection() {
131
+ if (this.authStore.collectionName) return this.authStore.collectionName;
132
+ const model = this.authStore.model;
133
+ if (model && typeof model.collectionName === "string" && model.collectionName) {
134
+ return model.collectionName;
86
135
  }
136
+ return SUPERUSERS;
87
137
  }
88
138
  /**
89
139
  * Globally enable or disable auto-cancellation of duplicated pending requests.
@@ -130,7 +180,7 @@ var HttpClient = class {
130
180
  * (aborted requests throw an `ApiError` with `isAbort === true`).
131
181
  */
132
182
  async request(method, path, body, options) {
133
- if (this.authStore.isExpired && this.authStore.collectionName) {
183
+ if (this.authStore.isExpired && this.authStore.refreshToken) {
134
184
  await this.refreshAuth();
135
185
  }
136
186
  let requestKey = options?.requestKey === void 0 ? options?.cancelKey ?? `${method} ${path}` : options.requestKey;
@@ -221,8 +271,9 @@ var HttpClient = class {
221
271
  }
222
272
  let res = null;
223
273
  const fetcher = options?.fetch ?? this.defaultFetch;
274
+ const send = async () => fetcher(url, init);
224
275
  try {
225
- res = await fetcher(url, init);
276
+ res = await send();
226
277
  } catch (err) {
227
278
  if (isAbortError(err)) {
228
279
  throw new ApiError(
@@ -238,6 +289,27 @@ var HttpClient = class {
238
289
  delete this.cancelControllers[requestKey];
239
290
  }
240
291
  }
292
+ if (res.status === 401 && this.authStore.refreshToken) {
293
+ await res.text().catch(() => {
294
+ });
295
+ const refreshed = await this.refreshAuth();
296
+ if (refreshed) {
297
+ headers["Authorization"] = "Bearer " + this.authStore.token;
298
+ try {
299
+ res = await send();
300
+ } catch (err) {
301
+ if (isAbortError(err)) {
302
+ throw new ApiError(
303
+ "The request was aborted (most likely auto-cancelled by a newer request with the same requestKey)",
304
+ {},
305
+ 0,
306
+ true
307
+ );
308
+ }
309
+ throw err;
310
+ }
311
+ }
312
+ }
241
313
  if (res.status === 204) return null;
242
314
  let bodyText = "";
243
315
  let data = {};
@@ -312,6 +384,7 @@ var AuthStore = class {
312
384
  this._token = "";
313
385
  this._model = null;
314
386
  this._tokenExpiresAt = null;
387
+ this._refreshToken = "";
315
388
  this._collectionName = null;
316
389
  this.listeners = /* @__PURE__ */ new Set();
317
390
  this.storage = storage ?? {
@@ -326,6 +399,15 @@ var AuthStore = class {
326
399
  get token() {
327
400
  return this._token;
328
401
  }
402
+ /**
403
+ * The refresh token for the current session, or empty string.
404
+ *
405
+ * Kept by the store so a session can outlive the access token (15 minutes on the
406
+ * server) even across a reload. Persisted under `auth_refresh_token`.
407
+ */
408
+ get refreshToken() {
409
+ return this._refreshToken;
410
+ }
329
411
  /** The current authenticated user record, or null. */
330
412
  get model() {
331
413
  return this._model;
@@ -360,14 +442,16 @@ var AuthStore = class {
360
442
  * Should be called once at application startup.
361
443
  */
362
444
  async init() {
363
- const [token, model, expiresAt, collectionName] = await Promise.all([
445
+ const [token, model, expiresAt, collectionName, refreshToken] = await Promise.all([
364
446
  this.storage.get("auth_token"),
365
447
  this.storage.get("auth_model"),
366
448
  this.storage.get("auth_expires_at"),
367
- this.storage.get("auth_collection")
449
+ this.storage.get("auth_collection"),
450
+ this.storage.get("auth_refresh_token")
368
451
  ]);
369
452
  if (token) this._token = token;
370
453
  if (expiresAt) this._tokenExpiresAt = parseInt(expiresAt, 10) || null;
454
+ if (refreshToken) this._refreshToken = refreshToken;
371
455
  if (model) {
372
456
  try {
373
457
  this._model = JSON.parse(model);
@@ -382,6 +466,10 @@ var AuthStore = class {
382
466
  }
383
467
  /**
384
468
  * Update the current auth token and model, persist to storage, and notify listeners.
469
+ *
470
+ * Uses the fallback TTL; prefer {@link setSession} with a server auth response,
471
+ * which carries the real `expiresIn` and the refresh token.
472
+ *
385
473
  * @param token The JWT token string.
386
474
  * @param model The authenticated user record, or null for superusers.
387
475
  */
@@ -401,18 +489,44 @@ var AuthStore = class {
401
489
  this.notify();
402
490
  }
403
491
  /**
404
- * Clear all auth state (token, model, expiry, collection) and notify listeners.
492
+ * Record a complete auth response: token, model, refresh token and the access
493
+ * token's real lifetime.
494
+ *
495
+ * `expiresIn` is seconds, the field the server's auth responses carry. Not passing
496
+ * it (an older server) falls back to the historical 7-day assumption.
497
+ *
498
+ * @param token The JWT access token.
499
+ * @param model The authenticated record, or null for a superuser.
500
+ * @param options `refreshToken` and `expiresIn` from the same response.
501
+ */
502
+ setSession(token, model, options) {
503
+ this.set(token, model);
504
+ if (options?.refreshToken) {
505
+ this._refreshToken = options.refreshToken;
506
+ void this.storage.set("auth_refresh_token", options.refreshToken);
507
+ }
508
+ const expiresIn = options?.expiresIn;
509
+ if (typeof expiresIn === "number" && expiresIn > 0) {
510
+ this._tokenExpiresAt = Date.now() + expiresIn * 1e3;
511
+ void this.storage.set("auth_expires_at", String(this._tokenExpiresAt));
512
+ }
513
+ }
514
+ /**
515
+ * Clear all auth state (token, model, expiry, refresh token, collection) and
516
+ * notify listeners.
405
517
  */
406
518
  clear() {
407
519
  this._token = "";
408
520
  this._model = null;
409
521
  this._tokenExpiresAt = null;
522
+ this._refreshToken = "";
410
523
  this._collectionName = null;
411
524
  void Promise.all([
412
525
  this.storage.remove("auth_token"),
413
526
  this.storage.remove("auth_expires_at"),
414
527
  this.storage.remove("auth_model"),
415
- this.storage.remove("auth_collection")
528
+ this.storage.remove("auth_collection"),
529
+ this.storage.remove("auth_refresh_token")
416
530
  ]);
417
531
  this.notify();
418
532
  }
@@ -434,6 +548,13 @@ var AuthStore = class {
434
548
  }
435
549
  }
436
550
  };
551
+ function rememberAuthResponse(store, data, model) {
552
+ if (!data || typeof data.token !== "string" || !data.token) return;
553
+ store.setSession(data.token, model, {
554
+ refreshToken: typeof data.refreshToken === "string" ? data.refreshToken : void 0,
555
+ expiresIn: typeof data.expiresIn === "number" ? data.expiresIn : void 0
556
+ });
557
+ }
437
558
  var memoryStorage = {
438
559
  get(key) {
439
560
  try {
@@ -1502,7 +1623,11 @@ var CollectionService = class _CollectionService {
1502
1623
  );
1503
1624
  if (data && this.authStore) {
1504
1625
  this.authStore.setCollectionName(this.collectionName);
1505
- this.authStore.set(data.token, data.record);
1626
+ rememberAuthResponse(
1627
+ this.authStore,
1628
+ data,
1629
+ data.record
1630
+ );
1506
1631
  }
1507
1632
  return data;
1508
1633
  }
@@ -1513,12 +1638,16 @@ var CollectionService = class _CollectionService {
1513
1638
  async authRefresh(options) {
1514
1639
  const data = await this.http.post(
1515
1640
  this.collectionPath() + "/auth-refresh",
1516
- void 0,
1641
+ { refreshToken: this.authStore?.refreshToken },
1517
1642
  options
1518
1643
  );
1519
1644
  if (data && this.authStore) {
1520
1645
  this.authStore.setCollectionName(this.collectionName);
1521
- this.authStore.set(data.token, data.record);
1646
+ rememberAuthResponse(
1647
+ this.authStore,
1648
+ data,
1649
+ data.record
1650
+ );
1522
1651
  }
1523
1652
  return data;
1524
1653
  }
@@ -1701,7 +1830,11 @@ var CollectionService = class _CollectionService {
1701
1830
  }
1702
1831
  if (this.authStore) {
1703
1832
  this.authStore.setCollectionName(this.collectionName);
1704
- this.authStore.set(data.token, data.record);
1833
+ rememberAuthResponse(
1834
+ this.authStore,
1835
+ data,
1836
+ data.record
1837
+ );
1705
1838
  }
1706
1839
  return data;
1707
1840
  }
@@ -2422,7 +2555,7 @@ var LazypockClient = class {
2422
2555
  const data = await this.http.post("/superusers/setup", { email, password });
2423
2556
  if (data) {
2424
2557
  this.authStore.setCollectionName(null);
2425
- this.authStore.set(data.token, null);
2558
+ rememberAuthResponse(this.authStore, data, null);
2426
2559
  }
2427
2560
  return data;
2428
2561
  }
@@ -2446,7 +2579,11 @@ var LazypockClient = class {
2446
2579
  });
2447
2580
  if (data && data.record) {
2448
2581
  this.authStore.setCollectionName(collection);
2449
- this.authStore.set(data.token, data.record);
2582
+ rememberAuthResponse(
2583
+ this.authStore,
2584
+ data,
2585
+ data.record
2586
+ );
2450
2587
  }
2451
2588
  } else {
2452
2589
  try {
@@ -2462,7 +2599,7 @@ var LazypockClient = class {
2462
2599
  }
2463
2600
  if (data) {
2464
2601
  this.authStore.setCollectionName(null);
2465
- this.authStore.set(data.token, null);
2602
+ rememberAuthResponse(this.authStore, data, null);
2466
2603
  }
2467
2604
  }
2468
2605
  return data;
@@ -2496,7 +2633,7 @@ var LazypockClient = class {
2496
2633
  );
2497
2634
  if (data) {
2498
2635
  this.authStore.setCollectionName(collection);
2499
- this.authStore.set(data.token, data.record);
2636
+ rememberAuthResponse(this.authStore, data, data.record);
2500
2637
  }
2501
2638
  return data;
2502
2639
  }
@@ -2510,12 +2647,12 @@ var LazypockClient = class {
2510
2647
  async authRefresh(collection, options) {
2511
2648
  const data = await this.http.post(
2512
2649
  "/collections/" + encodeURIComponent(collection) + "/auth-refresh",
2513
- void 0,
2650
+ { refreshToken: this.authStore.refreshToken },
2514
2651
  options
2515
2652
  );
2516
2653
  if (data) {
2517
2654
  this.authStore.setCollectionName(collection);
2518
- this.authStore.set(data.token, data.record);
2655
+ rememberAuthResponse(this.authStore, data, data.record);
2519
2656
  }
2520
2657
  return data;
2521
2658
  }