tempest-react-sdk 0.76.0 → 0.78.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/README.md +2 -2
- package/bin/create-tempest-app.e2e.test.mjs +112 -0
- package/bin/create-tempest-app.mjs +69 -28
- package/bin/lib/alias/collect.mjs +20 -3
- package/bin/lib/alias/index.mjs +12 -1
- package/bin/lib/alias/index.test.mjs +24 -0
- package/bin/lib/component/generate.mjs +191 -0
- package/bin/lib/component/generate.test.mjs +336 -0
- package/bin/lib/css/analyze.test.mjs +21 -1
- package/bin/lib/css/collect.mjs +14 -0
- package/bin/lib/css/extract.mjs +63 -5
- package/bin/lib/css/extract.test.mjs +110 -1
- package/bin/lib/css/fix.e2e.test.mjs +50 -0
- package/bin/lib/css/index.mjs +6 -1
- package/bin/lib/fs/contain.mjs +50 -0
- package/bin/lib/icons/generate.mjs +28 -3
- package/bin/lib/icons/generate.test.mjs +57 -1
- package/bin/lib/openapi/escape.mjs +224 -0
- package/bin/lib/openapi/generate.encode.test.mjs +120 -0
- package/bin/lib/openapi/generate.hostile.test.mjs +621 -0
- package/bin/lib/openapi/generate.mjs +129 -18
- package/bin/lib/openapi/generate.test.mjs +7 -2
- package/bin/lib/openapi/schema-to-zod.mjs +43 -4
- package/bin/tempest-gen.test.mjs +188 -0
- package/bin/tempest.mjs +263 -6
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +203 -58
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/refresh-queue.cjs +1 -1
- package/dist/auth/refresh-queue.cjs.map +1 -1
- package/dist/auth/refresh-queue.js +13 -6
- package/dist/auth/refresh-queue.js.map +1 -1
- package/dist/br/pix.cjs +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js +85 -72
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +19 -4
- package/dist/components/Chat/ChatAttachments.cjs +1 -1
- package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
- package/dist/components/Chat/ChatAttachments.js +46 -38
- package/dist/components/Chat/ChatAttachments.js.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/CodeBlock/tokenize.cjs +1 -1
- package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
- package/dist/components/CodeBlock/tokenize.js +54 -25
- package/dist/components/CodeBlock/tokenize.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +7 -5
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +171 -90
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/components/Toast/Toast.module.cjs +1 -1
- package/dist/components/Toast/Toast.module.cjs.map +1 -1
- package/dist/components/Toast/Toast.module.js +7 -3
- package/dist/components/Toast/Toast.module.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js +77 -51
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/data/create-data-provider.cjs +1 -1
- package/dist/data/create-data-provider.cjs.map +1 -1
- package/dist/data/create-data-provider.js +32 -21
- package/dist/data/create-data-provider.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +81 -73
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/errors.cjs +1 -1
- package/dist/http/errors.cjs.map +1 -1
- package/dist/http/errors.js +39 -35
- package/dist/http/errors.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +141 -105
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +5 -6
- package/dist/http/retry.js.map +1 -1
- package/dist/oauth/callback.cjs +2 -0
- package/dist/oauth/callback.cjs.map +1 -0
- package/dist/oauth/callback.js +42 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/use-oauth-callback.cjs +1 -1
- package/dist/oauth/use-oauth-callback.cjs.map +1 -1
- package/dist/oauth/use-oauth-callback.js +13 -20
- package/dist/oauth/use-oauth-callback.js.map +1 -1
- package/dist/push/use-push-subscription.cjs +1 -1
- package/dist/push/use-push-subscription.cjs.map +1 -1
- package/dist/push/use-push-subscription.js +42 -42
- package/dist/push/use-push-subscription.js.map +1 -1
- package/dist/push/web-push-client.cjs +1 -1
- package/dist/push/web-push-client.cjs.map +1 -1
- package/dist/push/web-push-client.js +23 -3
- package/dist/push/web-push-client.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +68 -23
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/styles/component/Toast.css +6 -1
- package/dist/styles/feedback.css +6 -1
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +272 -60
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache-inspect.cjs.map +1 -1
- package/dist/sw/cache-inspect.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +91 -64
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw/credential-headers.cjs +2 -0
- package/dist/sw/credential-headers.cjs.map +1 -0
- package/dist/sw/credential-headers.js +17 -0
- package/dist/sw/credential-headers.js.map +1 -0
- package/dist/sw/session-data.cjs +2 -0
- package/dist/sw/session-data.cjs.map +1 -0
- package/dist/sw/session-data.js +17 -0
- package/dist/sw/session-data.js.map +1 -0
- package/dist/sw.cjs +1 -1
- package/dist/sw.d.ts +309 -23
- package/dist/sw.js +7 -5
- package/dist/telemetry/app-error-queue.cjs +1 -1
- package/dist/telemetry/app-error-queue.cjs.map +1 -1
- package/dist/telemetry/app-error-queue.js +19 -14
- package/dist/telemetry/app-error-queue.js.map +1 -1
- package/dist/telemetry/app-error-reporter.cjs +1 -1
- package/dist/telemetry/app-error-reporter.cjs.map +1 -1
- package/dist/telemetry/app-error-reporter.js +75 -34
- package/dist/telemetry/app-error-reporter.js.map +1 -1
- package/dist/telemetry/app-error-transport.cjs +1 -1
- package/dist/telemetry/app-error-transport.cjs.map +1 -1
- package/dist/telemetry/app-error-transport.js +16 -3
- package/dist/telemetry/app-error-transport.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +1183 -64
- package/dist/tempest-react-sdk.js +160 -156
- package/dist/utils/csv.cjs +3 -3
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js +18 -14
- package/dist/utils/csv.js.map +1 -1
- package/dist/utils/owner-fingerprint.cjs +2 -0
- package/dist/utils/owner-fingerprint.cjs.map +1 -0
- package/dist/utils/owner-fingerprint.js +18 -0
- package/dist/utils/owner-fingerprint.js.map +1 -0
- package/dist/utils/safe-url.cjs +2 -0
- package/dist/utils/safe-url.cjs.map +1 -0
- package/dist/utils/safe-url.js +39 -0
- package/dist/utils/safe-url.js.map +1 -0
- package/dist/vite/tempest-csp.cjs +2 -2
- package/dist/vite/tempest-csp.cjs.map +1 -1
- package/dist/vite/tempest-csp.js +130 -64
- package/dist/vite/tempest-csp.js.map +1 -1
- package/dist/vite.d.ts +23 -5
- package/dist/webrtc/peer-link.cjs +1 -1
- package/dist/webrtc/peer-link.cjs.map +1 -1
- package/dist/webrtc/peer-link.js +2 -10
- package/dist/webrtc/peer-link.js.map +1 -1
- package/dist/webrtc/peer-mesh.cjs +1 -1
- package/dist/webrtc/peer-mesh.cjs.map +1 -1
- package/dist/webrtc/peer-mesh.js +110 -72
- package/dist/webrtc/peer-mesh.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/src/pwa.tsx +22 -0
- package/template-pwa/src/sw.ts +27 -14
- package/dist/components/Markdown/markdown-url.cjs +0 -2
- package/dist/components/Markdown/markdown-url.cjs.map +0 -1
- package/dist/components/Markdown/markdown-url.js +0 -28
- package/dist/components/Markdown/markdown-url.js.map +0 -1
|
@@ -1,77 +1,222 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { isDevBuild as e } from "../utils/dev-mode.js";
|
|
2
|
+
import { SessionSupersededError as t } from "../http/errors.js";
|
|
3
|
+
import { createApiClient as n } from "../http/api-client.js";
|
|
4
|
+
import { createAuthStore as r } from "./create-auth-store.js";
|
|
5
|
+
import { createRefreshQueue as i } from "./refresh-queue.js";
|
|
4
6
|
//#region src/auth/create-tempest-auth.ts
|
|
5
|
-
|
|
7
|
+
var a = 1e4;
|
|
8
|
+
function o(e, t) {
|
|
9
|
+
return e.length === 0 ? Promise.resolve() : new Promise((n) => {
|
|
10
|
+
let r = setTimeout(n, t);
|
|
11
|
+
Promise.allSettled(e).then(() => {
|
|
12
|
+
clearTimeout(r), n();
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function s(e) {
|
|
6
17
|
let t = e ?? {};
|
|
7
18
|
return {
|
|
8
19
|
token: t.access_token,
|
|
9
20
|
refreshToken: t.refresh_token
|
|
10
21
|
};
|
|
11
22
|
}
|
|
12
|
-
function
|
|
13
|
-
let { baseURL:
|
|
14
|
-
name:
|
|
15
|
-
storage:
|
|
16
|
-
}),
|
|
17
|
-
function
|
|
18
|
-
return typeof window > "u" ? null :
|
|
19
|
-
}
|
|
20
|
-
function
|
|
21
|
-
return
|
|
22
|
-
}
|
|
23
|
-
function
|
|
24
|
-
let t =
|
|
25
|
-
t && (e ? t.setItem(
|
|
26
|
-
}
|
|
27
|
-
let
|
|
28
|
-
async function
|
|
29
|
-
if (!
|
|
30
|
-
let e =
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
23
|
+
function c(c) {
|
|
24
|
+
let { baseURL: l, prefix: u, loginPath: d = "/api/auth/login", refreshPath: ee = "/api/auth/refresh", logoutPath: f, onLogoutError: te, mePath: p, storeName: m = "tempest-auth", storage: h = "local", withCredentials: g = !1, csrf: _, fetcher: v, parseTokens: y = s, parseUser: b, refreshBody: x = (e) => e ? { refresh_token: e } : void 0, retry: ne, redirectTo: S, onSessionEnd: C } = c, w = r({
|
|
25
|
+
name: m,
|
|
26
|
+
storage: h
|
|
27
|
+
}), T = `${m}-refresh`;
|
|
28
|
+
function E() {
|
|
29
|
+
return typeof window > "u" ? null : h === "session" ? window.sessionStorage : window.localStorage;
|
|
30
|
+
}
|
|
31
|
+
function D() {
|
|
32
|
+
return E()?.getItem(T) ?? null;
|
|
33
|
+
}
|
|
34
|
+
function O(e) {
|
|
35
|
+
let t = E();
|
|
36
|
+
t && (e ? t.setItem(T, e) : t.removeItem(T));
|
|
37
|
+
}
|
|
38
|
+
let k = () => w.getState(), A = () => k().token;
|
|
39
|
+
async function j() {
|
|
40
|
+
if (!p) return k().user;
|
|
41
|
+
let e = M, n;
|
|
42
|
+
try {
|
|
43
|
+
n = await $.get(p, { skipAuthRetry: !0 });
|
|
44
|
+
} catch (n) {
|
|
45
|
+
throw M === e ? n : new t();
|
|
46
|
+
}
|
|
47
|
+
if (M !== e) throw new t();
|
|
48
|
+
return k().setUser(n), n;
|
|
49
|
+
}
|
|
50
|
+
let M = 0, N = Promise.resolve(), P = 0, F = /* @__PURE__ */ new Set(), I = /* @__PURE__ */ new Set(), L = /* @__PURE__ */ new Set(), R = /* @__PURE__ */ new Set();
|
|
51
|
+
function z(e) {
|
|
52
|
+
let t = e.then(() => void 0, () => void 0);
|
|
53
|
+
return L.add(t), t.then(() => L.delete(t)), e;
|
|
54
|
+
}
|
|
55
|
+
function B(t) {
|
|
56
|
+
e() && console.warn("[tempest-react-sdk] createTempestAuth: logoutPath revocation failed", t);
|
|
57
|
+
try {
|
|
58
|
+
te?.(t);
|
|
59
|
+
} catch {
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function V(e) {
|
|
64
|
+
let t = (async () => {
|
|
65
|
+
try {
|
|
66
|
+
await e();
|
|
67
|
+
} catch (e) {
|
|
68
|
+
B(e);
|
|
69
|
+
}
|
|
70
|
+
})();
|
|
71
|
+
return I.add(t), t.then(() => I.delete(t)), t;
|
|
72
|
+
}
|
|
73
|
+
function H(e, t) {
|
|
74
|
+
f && !g && t && V(() => U(e).post(f, { body: x(t) }));
|
|
75
|
+
}
|
|
76
|
+
function U(e) {
|
|
77
|
+
return n({
|
|
78
|
+
baseURL: l,
|
|
79
|
+
prefix: u,
|
|
80
|
+
withCredentials: g,
|
|
81
|
+
csrf: _,
|
|
82
|
+
fetcher: v,
|
|
83
|
+
getToken: () => e
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
function W() {
|
|
87
|
+
M += 1, K = i(G);
|
|
88
|
+
}
|
|
89
|
+
async function G() {
|
|
90
|
+
let e = M;
|
|
91
|
+
R.add(e);
|
|
92
|
+
try {
|
|
93
|
+
let n;
|
|
94
|
+
try {
|
|
95
|
+
n = await z($.post(ee, {
|
|
96
|
+
body: x(D()),
|
|
97
|
+
skipAuth: !0
|
|
98
|
+
}));
|
|
99
|
+
} catch (n) {
|
|
100
|
+
throw M === e ? n : new t();
|
|
101
|
+
}
|
|
102
|
+
let { token: r, refreshToken: i } = y(n);
|
|
103
|
+
if (M !== e) throw H(r ?? null, i), new t();
|
|
104
|
+
k().setToken(r), i && O(i);
|
|
105
|
+
} finally {
|
|
106
|
+
R.delete(e);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
let K = i(G);
|
|
110
|
+
function q(e) {
|
|
111
|
+
let t = A();
|
|
112
|
+
return t === null ? !1 : e.token === null || e.token !== t;
|
|
113
|
+
}
|
|
114
|
+
function J() {
|
|
115
|
+
return A() === null && D() === null;
|
|
116
|
+
}
|
|
117
|
+
async function Y() {
|
|
118
|
+
if (!(F.size > 0 && P === 0 && (await Promise.allSettled([...F]), A() !== null))) throw Error("anonymous 401 with no session");
|
|
119
|
+
}
|
|
120
|
+
async function X(e) {
|
|
121
|
+
if (e.epoch !== null && e.epoch !== M) throw new t();
|
|
122
|
+
if (q(e)) {
|
|
123
|
+
if (e.token === null) throw Error("anonymous 401 under a live session");
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
return e.token === null && J() ? R.has(M) ? K() : Y() : K();
|
|
127
|
+
}
|
|
128
|
+
async function Z(e, n) {
|
|
129
|
+
if (n.epoch !== null && n.epoch !== M) throw new t();
|
|
130
|
+
q(n) || n.token === null && J() || await se();
|
|
131
|
+
}
|
|
132
|
+
async function re(e) {
|
|
133
|
+
I.size > 0 && await o([...I], a);
|
|
134
|
+
let t = ie(e);
|
|
135
|
+
F.add(t);
|
|
136
|
+
try {
|
|
137
|
+
return await t;
|
|
138
|
+
} finally {
|
|
139
|
+
F.delete(t);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
async function ie(e) {
|
|
143
|
+
let n = M, r = await z($.post(d, {
|
|
35
144
|
body: e,
|
|
36
145
|
skipAuth: !0
|
|
37
|
-
}), { token:
|
|
38
|
-
|
|
39
|
-
let
|
|
40
|
-
|
|
146
|
+
})), { token: i, refreshToken: a } = y(r);
|
|
147
|
+
if (M !== n) throw H(i ?? null, a), new t();
|
|
148
|
+
let { done: o } = Q("switch"), s = M;
|
|
149
|
+
if (await o.catch(() => void 0), M !== s) throw new t();
|
|
150
|
+
k().setToken(i), O(a ?? null);
|
|
151
|
+
let c = b?.(r);
|
|
152
|
+
return c == null ? j() : (k().setUser(c), c);
|
|
41
153
|
}
|
|
42
|
-
function
|
|
43
|
-
|
|
154
|
+
function Q(e) {
|
|
155
|
+
let { user: t, token: n } = k(), r = n !== null || t !== null || D() !== null;
|
|
156
|
+
if ((r || e !== "expired") && W(), k().logout(), O(null), !r) return {
|
|
157
|
+
live: r,
|
|
158
|
+
done: e === "switch" || P === 0 ? N : Promise.resolve()
|
|
159
|
+
};
|
|
160
|
+
if (!C) return {
|
|
161
|
+
live: r,
|
|
162
|
+
done: Promise.resolve()
|
|
163
|
+
};
|
|
164
|
+
let i = U(n);
|
|
165
|
+
P += 1;
|
|
166
|
+
let a = (async () => {
|
|
167
|
+
try {
|
|
168
|
+
await C({
|
|
169
|
+
reason: e,
|
|
170
|
+
user: t,
|
|
171
|
+
token: n,
|
|
172
|
+
api: i
|
|
173
|
+
});
|
|
174
|
+
} finally {
|
|
175
|
+
--P;
|
|
176
|
+
}
|
|
177
|
+
})();
|
|
178
|
+
return N = a.then(() => void 0, () => void 0), {
|
|
179
|
+
live: r,
|
|
180
|
+
done: a.then(() => void 0)
|
|
181
|
+
};
|
|
44
182
|
}
|
|
45
|
-
function
|
|
46
|
-
|
|
183
|
+
function ae() {
|
|
184
|
+
if (!f) return null;
|
|
185
|
+
let e = f, { token: t, user: n } = k(), r = D();
|
|
186
|
+
if (!g && t === null && n === null && r === null) return null;
|
|
187
|
+
let i = g ? [...L] : [];
|
|
188
|
+
return V(async () => (await o(i, a), U(t).post(e, { body: x(r) })));
|
|
47
189
|
}
|
|
48
|
-
|
|
49
|
-
let e =
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
190
|
+
function oe() {
|
|
191
|
+
let e = ae(), { done: t } = Q("logout");
|
|
192
|
+
return e ? Promise.all([e, t]).then(() => void 0) : t;
|
|
193
|
+
}
|
|
194
|
+
async function se() {
|
|
195
|
+
let { live: e, done: t } = Q("expired");
|
|
196
|
+
await t.catch(() => void 0), e && S && typeof window < "u" && window.location.assign(S);
|
|
197
|
+
}
|
|
198
|
+
let $ = n({
|
|
199
|
+
baseURL: l,
|
|
200
|
+
prefix: u,
|
|
201
|
+
withCredentials: g,
|
|
202
|
+
csrf: _,
|
|
203
|
+
fetcher: v,
|
|
204
|
+
getToken: A,
|
|
205
|
+
getSessionEpoch: () => M,
|
|
206
|
+
refresh: X,
|
|
207
|
+
retry: ne,
|
|
208
|
+
onUnauthorized: Z
|
|
64
209
|
});
|
|
65
210
|
return {
|
|
66
|
-
useAuthStore:
|
|
67
|
-
api:
|
|
68
|
-
login:
|
|
69
|
-
logout:
|
|
70
|
-
refresh:
|
|
71
|
-
getToken:
|
|
211
|
+
useAuthStore: w,
|
|
212
|
+
api: $,
|
|
213
|
+
login: re,
|
|
214
|
+
logout: oe,
|
|
215
|
+
refresh: () => K(),
|
|
216
|
+
getToken: A
|
|
72
217
|
};
|
|
73
218
|
}
|
|
74
219
|
//#endregion
|
|
75
|
-
export {
|
|
220
|
+
export { c as createTempestAuth };
|
|
76
221
|
|
|
77
222
|
//# sourceMappingURL=create-tempest-auth.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-tempest-auth.js","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient } from \"../http\";\nimport type { ApiClient, CsrfOptions, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /**\n * CSRF token for every write, forwarded to `createApiClient`'s `csrf`. Off\n * by default; `true` echoes the `csrf_token` cookie as `X-CSRF-Token`.\n *\n * The pair to `withCredentials`: once the refresh token lives in a cookie,\n * the browser attaches it to a `POST /auth/refresh` that another site\n * triggers. Login and refresh carry the header too — they go out with\n * `skipAuth`, and the CSRF header does not follow auth.\n */\n csrf?: boolean | CsrfOptions;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /** Clear the session (and the stored refresh token). */\n logout: () => void;\n /** Refresh the access token (deduplicated across concurrent callers). */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * auth.logout();\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n csrf,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n /**\n * Load the current user, without letting a `401` end the session.\n *\n * `skipAuthRetry` is what keeps this one client honest: the call is\n * authenticated, but a `401` here surfaces instead of triggering a refresh\n * and `onUnauthorized`. That was the behaviour of the throwaway client this\n * used to build per invocation, and it is the reason the preset needed\n * three clients before 0.66.0.\n */\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const user = await api.get<TUser>(mePath, { skipAuthRetry: true });\n state().setUser(user);\n return user;\n }\n\n async function login(credentials: TCredentials): Promise<TUser | null> {\n const data = await api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n function logout(): void {\n state().logout();\n writeRefreshToken(null);\n }\n\n /**\n * Clear the session and, when `redirectTo` is set, leave the page.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation.\n */\n function endSession(): void {\n logout();\n if (redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const refresh = createRefreshQueue(async () => {\n const data = await api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n });\n const { token, refreshToken } = parseTokens(data);\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n });\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n refresh,\n retry,\n onUnauthorized: () => endSession(),\n });\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":";;;;AAmGA,SAAS,EAAmB,GAAyD;CACjF,IAAM,IAAK,KAAQ,CAAC;CACpB,OAAO;EAAE,OAAO,EAAE;EAAc,cAAc,EAAE;CAAc;AAClE;AA2BA,SAAgB,EACZ,GACgC;CAChC,IAAM,EACF,YACA,WACA,eAAY,mBACZ,iBAAc,qBACd,WACA,eAAY,gBACZ,aAAU,SACV,qBAAkB,IAClB,SACA,YACA,iBAAc,GACd,cACA,kBAAe,MAAQ,IAAK,EAAE,eAAe,EAAG,IAAI,KAAA,GACpD,UACA,kBACA,GAEE,IAAe,EAAuB;EAAE,MAAM;EAAW;CAAQ,CAAC,GAClE,IAAa,GAAG,EAAU;CAEhC,SAAS,IAA8B;EAEnC,OADI,OAAO,SAAW,MAAoB,OACnC,MAAY,YAAY,OAAO,iBAAiB,OAAO;CAClE;CACA,SAAS,IAAkC;EACvC,OAAO,EAAY,CAAC,EAAE,QAAQ,CAAU,KAAK;CACjD;CACA,SAAS,EAAkB,GAA4B;EACnD,IAAM,IAAI,EAAY;EACjB,MACD,IAAO,EAAE,QAAQ,GAAY,CAAK,IACjC,EAAE,WAAW,CAAU;CAChC;CAEA,IAAM,UAAgC,EAAa,SAAS,GACtD,UAAgC,EAAM,CAAC,CAAC;CAW9C,eAAe,IAAmC;EAC9C,IAAI,CAAC,GAAQ,OAAO,EAAM,CAAC,CAAC;EAC5B,IAAM,IAAO,MAAM,EAAI,IAAW,GAAQ,EAAE,eAAe,GAAK,CAAC;EAEjE,OADA,EAAM,CAAC,CAAC,QAAQ,CAAI,GACb;CACX;CAEA,eAAe,EAAM,GAAkD;EACnE,IAAM,IAAO,MAAM,EAAI,KAAc,GAAW;GAC5C,MAAM;GACN,UAAU;EACd,CAAC,GACK,EAAE,UAAO,oBAAiB,EAAY,CAAI;EAEhD,AADA,EAAM,CAAC,CAAC,SAAS,CAAK,GACtB,EAAkB,KAAgB,IAAI;EACtC,IAAM,IAAW,IAAY,CAAI;EAKjC,OAJI,KAAY,OAIT,EAAU,KAHb,EAAM,CAAC,CAAC,QAAQ,CAAQ,GACjB;CAGf;CAEA,SAAS,IAAe;EAEpB,AADA,EAAM,CAAC,CAAC,OAAO,GACf,EAAkB,IAAI;CAC1B;CASA,SAAS,IAAmB;EAExB,AADA,EAAO,GACH,KAAc,OAAO,SAAW,OAChC,OAAO,SAAS,OAAO,CAAU;CAEzC;CAEA,IAAM,IAAU,EAAmB,YAAY;EAC3C,IAAM,IAAO,MAAM,EAAI,KAAc,GAAa;GAC9C,MAAM,EAAY,EAAiB,CAAC;GACpC,UAAU;EACd,CAAC,GACK,EAAE,UAAO,oBAAiB,EAAY,CAAI;EAEhD,AADA,EAAM,CAAC,CAAC,SAAS,CAAK,GAClB,KAAc,EAAkB,CAAY;CACpD,CAAC,GAEK,IAAM,EAAgB;EACxB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,sBAAsB,EAAW;CACrC,CAAC;CAED,OAAO;EAAE;EAAc;EAAK;EAAO;EAAQ;EAAS;CAAS;AACjE"}
|
|
1
|
+
{"version":3,"file":"create-tempest-auth.js","names":[],"sources":["../../src/auth/create-tempest-auth.ts"],"sourcesContent":["import { createApiClient, SessionSupersededError } from \"../http\";\nimport { isDevBuild } from \"../utils/dev-mode\";\nimport type { ApiClient, CsrfOptions, RequestAuthContext, RetryOptions } from \"../http\";\nimport { createAuthStore } from \"./create-auth-store\";\nimport type { AuthState } from \"./create-auth-store\";\nimport { createRefreshQueue } from \"./refresh-queue\";\n\n/** The token envelope returned by a Tempest FastAPI SDK login/refresh route. */\nexport interface TempestTokenResponse {\n /** The bearer access token. */\n access_token: string;\n /** Token type — always `\"bearer\"` for the SDK. */\n token_type?: string;\n /** Optional refresh token (when the API returns it in the body, not a cookie). */\n refresh_token?: string;\n}\n\n/**\n * What {@link CreateTempestAuthOptions.onSessionEnd} receives about the session\n * that just ended.\n */\nexport interface TempestSessionEnd<TUser> {\n /**\n * Why it ended: `\"logout\"` for an explicit `logout()`, `\"expired\"` when the\n * client ended it on its own — the refresh failed, or the request replayed\n * after a refresh still came back `401` — and `\"switch\"` when `login()`\n * succeeded for another set of credentials while this session was live.\n */\n reason: \"logout\" | \"expired\" | \"switch\";\n /** The user of the ended session, as the store held it. */\n user: TUser | null;\n /** The access token of the ended session, or `null` when it had none. */\n token: string | null;\n /**\n * A client that sends the ended session's access token — the store has\n * already been cleared, so `auth.api` no longer does.\n *\n * Use it for the server-side half of the teardown, such as deleting this\n * browser's push subscription. It never refreshes and never ends a session:\n * a `401` here just rejects. On `\"logout\"` the token is usually still\n * valid; on `\"expired\"` the server has already refused it, so expect the\n * call to fail and keep the local half of the teardown independent of it.\n */\n api: ApiClient;\n}\n\nexport interface CreateTempestAuthOptions<TUser> {\n /** Base URL of the API. Required. */\n baseURL: string;\n /**\n * Path segment the API is mounted under, such as `\"/api\"`, forwarded to\n * every client this preset builds — see the `prefix` option of\n * `createApiClient`.\n *\n * Safe to combine with the default paths below: the prefix is applied at\n * most once, so `\"/api/auth/login\"` under a `\"/api\"` prefix stays\n * `\"/api/auth/login\"`.\n */\n prefix?: string;\n /** Login route (`POST`). Default: `\"/api/auth/login\"`. */\n loginPath?: string;\n /** Refresh route (`POST`). Default: `\"/api/auth/refresh\"`. */\n refreshPath?: string;\n /**\n * Server-side logout route (`POST`), called by an explicit `logout()` to\n * revoke the ending session. Off by default.\n *\n * `logout()` alone only clears client state, and an HttpOnly refresh\n * cookie is out of its reach: with `withCredentials`, the cookie stays\n * redeemable until the backend revokes it. The tempest-fastapi-sdk mounts\n * `POST /auth/logout` (`204`, idempotent) when it stores refresh tokens in\n * the database — at `/auth/cookie/logout` when it delivers tokens both in\n * the body and in cookies — and stateless refresh tokens cannot be\n * revoked, so the route is absent there.\n *\n * The request goes out through the ended session's client (the same one\n * `onSessionEnd` receives, carrying its access token), with the body that\n * `refreshBody` builds from the refresh token stored before the clear:\n * `{ refresh_token }` in body mode, no body in cookie mode, which is what\n * that route reads. The local clear does not wait on it — `isAuthenticated`\n * is still `false` when `logout()` returns — but the promise `logout()`\n * returns does, so a navigation after `await auth.logout()` does not abort\n * it. A failure (network, `4xx`, `5xx`) is swallowed: revocation is\n * best-effort and never keeps the user signed in. A `login()` started\n * while it is in flight waits for it, because the logout response clears\n * the auth cookies and would otherwise clear the new account's.\n *\n * Only an explicit `logout()` revokes. On `\"switch\"` the cookie jar already\n * holds the new account's cookie, and on `\"expired\"` the server has already\n * refused the session.\n *\n * Overlapping sign-outs each send their own revocation, and `login()` waits\n * for all of them — at most 10 seconds, so one that\n * never answers delays the sign-in instead of blocking it. In cookie mode,\n * a revocation also waits (within the same bound) for the login and\n * refresh responses that were in flight when `logout()` ran: the server\n * sets the ended session's cookie when that response arrives, and a\n * revocation sent earlier would leave it behind. In body mode, the refresh\n * token such a superseded response brings back is revoked on its own.\n */\n logoutPath?: string;\n /**\n * Called with the error when a `logoutPath` revocation fails — network\n * failure, `4xx` or `5xx`. `logout()` still resolves, since the local\n * sign-out already happened; this is where the app logs or retries. A dev\n * build also warns in the console. Errors it throws are swallowed.\n */\n onLogoutError?: (error: unknown) => void;\n /** Optional current-user route (`GET`) called after login/refresh. */\n mePath?: string;\n /** Persist key for the store. Default: `\"tempest-auth\"`. */\n storeName?: string;\n /** Storage backend. Default: `\"local\"`. */\n storage?: \"local\" | \"session\";\n /** Send cookies (needed when the refresh token lives in an httpOnly cookie). */\n withCredentials?: boolean;\n /**\n * CSRF token for every write, forwarded to `createApiClient`'s `csrf`. Off\n * by default; `true` echoes the `csrf_token` cookie as `X-CSRF-Token`.\n *\n * The pair to `withCredentials`: once the refresh token lives in a cookie,\n * the browser attaches it to a `POST /auth/refresh` that another site\n * triggers. Login and refresh carry the header too — they go out with\n * `skipAuth`, and the CSRF header does not follow auth.\n */\n csrf?: boolean | CsrfOptions;\n /** Custom fetch implementation (testing / SSR). Defaults to `globalThis.fetch`. */\n fetcher?: typeof fetch;\n /**\n * Extract tokens from a login/refresh response. Default reads\n * `access_token` + `refresh_token`.\n */\n parseTokens?: (data: unknown) => { token: string; refreshToken?: string };\n /** Pull the user out of the login response, when the API embeds it. */\n parseUser?: (data: unknown) => TUser | null;\n /**\n * Build the refresh request body. Default sends `{ refresh_token }` when a\n * refresh token is stored, else `undefined` (cookie-based refresh).\n */\n refreshBody?: (refreshToken: string | null) => unknown;\n /**\n * Retry policy for `api`, forwarded to {@link createApiClient}. Off by\n * default; `true` enables the conservative built-in policy, which never\n * replays a write.\n */\n retry?: boolean | RetryOptions;\n /**\n * Where to send the browser when the session ends — a hard navigation via\n * `window.location.assign`, after the store is cleared.\n *\n * **Prefer leaving this unset.** `logout()` already clears the store, so a\n * `<RouteGuard when={isAuthenticated} redirectTo=\"/login\">` wrapped around\n * the protected area navigates on its own, which keeps the SPA alive and the\n * router history intact. Reach for this only when the expiry can happen\n * outside any guarded subtree and a full reload is acceptable.\n */\n redirectTo?: string;\n /**\n * Tear down per-user state when a session ends — on an explicit `logout()`,\n * when the client ends the session on its own after a failed refresh, and\n * when a successful `login()` replaces a live session. Without it, the automatic path had no place to hook into, and\n * state derived from the user (a push subscription, a persisted query\n * cache, a background-sync queue) survived into the next account.\n *\n * Order, on every path:\n *\n * 1. any refresh still in flight is superseded, so it cannot reinstall the\n * ending session's tokens;\n * 2. the store and the stored refresh token are cleared — synchronously, so\n * `isAuthenticated` is already `false` when `logout()` returns;\n * 3. this hook runs with a {@link TempestSessionEnd} whose `api` still sends\n * the ended session's access token;\n * 4. on `\"expired\"` with `redirectTo` set, the browser navigates — after the\n * hook settled, even if it threw; on `\"switch\"`, the new session is\n * installed — after the hook settled, even if it threw.\n *\n * It may be async. `logout()` resolves when it settles and rejects with what\n * it threw; on the automatic path the error is swallowed, because the\n * request that ended the session already rejects with its own `401`. It\n * runs once per session: a second `logout()`, or the other requests of a\n * burst of `401`s, find nothing left to end and skip it.\n *\n * On `\"switch\"` the hook runs only **after** the new credentials were\n * accepted, so a failed `login()` leaves the live session untouched. It runs\n * **before** the new session is installed: teardown of the previous\n * account's state (clearing a persisted cache, a background-sync queue) has\n * to finish before the new account's requests start filling them, or it\n * would wipe — or race with — the new account's data. The cost is that\n * `isAuthenticated` is `false` while the hook runs, which a route guard may\n * act on; keep the hook short. Its error is swallowed there, since the\n * login itself succeeded.\n *\n * Inside the hook, reach the backend only through `session.api`. `auth.api`\n * goes out with no token; `auth.login()` waits on the teardown in progress —\n * this hook — and never settles. Telling the hook apart from an outside\n * caller would need an async context the browser does not have, so this is\n * a documented rule, not a runtime check.\n */\n onSessionEnd?: (session: TempestSessionEnd<TUser>) => void | Promise<void>;\n}\n\nexport interface TempestAuth<TUser, TCredentials> {\n /** The persisted Zustand auth store hook (compatible with `<AuthGuard>`). */\n useAuthStore: ReturnType<typeof createAuthStore<TUser>>;\n /** A `createApiClient` wired with bearer auth + 401 → refresh → retry. */\n api: ApiClient;\n /** Authenticate, store the session, and resolve the user (or null). */\n login: (credentials: TCredentials) => Promise<TUser | null>;\n /**\n * End the session: supersede any refresh in flight, clear the store and the\n * stored refresh token, then run `onSessionEnd`.\n *\n * The store is cleared synchronously, before the first `await`, so callers\n * that ignore the promise see the signed-out state at once. The promise\n * resolves when `onSessionEnd` settled — and, with `logoutPath`, when the\n * server-side revocation settled too — and rejects with the hook's error;\n * a failed revocation never rejects it.\n */\n logout: () => Promise<void>;\n /**\n * Refresh the access token (deduplicated across concurrent callers).\n *\n * @throws {SessionSupersededError} When the session ended or changed while\n * the refresh was in flight; its tokens were discarded.\n */\n refresh: () => Promise<void>;\n /** The current access token, or null. */\n getToken: () => string | null;\n}\n\n/**\n * How long `login()` waits for pending `logoutPath` revocations, and how long a\n * cookie-mode revocation waits for the login or refresh responses still in\n * flight when `logout()` ran, before going ahead anyway.\n *\n * A bound, not a guess at latency: a fetcher that ignores abort, or a backend\n * that never answers, would otherwise leave the next `login()` waiting forever.\n * Ten seconds is past any healthy round trip and short enough that a stuck\n * revocation costs a slow sign-in, not a dead one.\n */\nconst LOGOUT_REVOCATION_WAIT_MS = 10_000;\n\n/**\n * Wait until every promise settled, or until `ms` passed, whichever is first.\n *\n * @param pending - What to wait for; rejections count as settled.\n * @param ms - The bound.\n * @returns A promise that always resolves.\n */\nfunction settleWithin(pending: readonly Promise<unknown>[], ms: number): Promise<void> {\n if (pending.length === 0) return Promise.resolve();\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ms);\n void Promise.allSettled(pending).then(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n}\n\nfunction defaultParseTokens(data: unknown): { token: string; refreshToken?: string } {\n const d = (data ?? {}) as TempestTokenResponse;\n return { token: d.access_token, refreshToken: d.refresh_token };\n}\n\n/**\n * Turn-key auth preset wiring `createAuthStore` + `createRefreshQueue` +\n * `createApiClient` to the Tempest FastAPI SDK auth contract: login returns\n * `{ access_token, token_type }`, requests carry `Authorization: Bearer`, and a\n * `401` triggers a single deduplicated refresh + replay.\n *\n * The session is cleared whenever that path ends unauthorized anyway — the\n * refresh threw, or the replay came back `401` — so a refresh token that the\n * backend has revoked cannot leave the app holding a dead session. With\n * `redirectTo` set, the browser also leaves the page; without it, clearing the\n * store is enough for a `<RouteGuard>` to navigate on its own.\n *\n * Every refresh is bound to a **session epoch**, bumped by `logout()` and by a\n * `login()` whose credentials were accepted. A refresh that resolves after its epoch ended discards\n * what it brought back and rejects with {@link SessionSupersededError}, which\n * the client passes through without ending the new session. Before 0.77.0 a\n * refresh that was in flight during `logout()` reinstalled the old tokens —\n * and after `logout()` + `login(B)`, replaced B's token with A's while the UI\n * showed B (#435). A `401` from a request sent under an ended session is\n * refused the same way, instead of being replayed as the account signed in now.\n *\n * A `401` from a request that carried no token, while no session is installed,\n * surfaces without a refresh: in cookie mode that refresh would be answered by\n * the HttpOnly cookie `logout()` cannot clear, signing the previous account\n * back in (#474). With a `login()` in flight, that `401` waits for it and\n * replays with the token it installed, or surfaces when it failed — still\n * without a refresh (#496). Restore a session at boot with an explicit\n * `refresh()`, and pass `logoutPath` so the backend revokes the cookie:\n * without a working revocation, that boot `refresh()` restores the previous\n * account for whoever uses the browser next.\n *\n * Refreshes are collapsed per rotation, not just per overlap: a `401` whose\n * request left with a token that has since been replaced in the same session\n * replays with the new token and refreshes nothing. Three expired requests take\n * one refresh whether their `401`s arrive together or one after another.\n *\n * @example\n * const auth = createTempestAuth<User, { email: string; password: string }>({\n * baseURL: import.meta.env.VITE_API_URL,\n * mePath: \"/api/auth/me\",\n * });\n *\n * await auth.login({ email, password }); // stores session, returns the user\n * const orders = await auth.api.get(\"/api/orders\"); // sends the bearer token\n * await auth.logout(); // clears, then runs onSessionEnd\n *\n * @param options - The auth configuration.\n * @returns The store hook, a wired API client, and login/logout/refresh helpers.\n */\nexport function createTempestAuth<TUser, TCredentials = { email: string; password: string }>(\n options: CreateTempestAuthOptions<TUser>,\n): TempestAuth<TUser, TCredentials> {\n const {\n baseURL,\n prefix,\n loginPath = \"/api/auth/login\",\n refreshPath = \"/api/auth/refresh\",\n logoutPath,\n onLogoutError,\n mePath,\n storeName = \"tempest-auth\",\n storage = \"local\",\n withCredentials = false,\n csrf,\n fetcher,\n parseTokens = defaultParseTokens,\n parseUser,\n refreshBody = (rt) => (rt ? { refresh_token: rt } : undefined),\n retry,\n redirectTo,\n onSessionEnd,\n } = options;\n\n const useAuthStore = createAuthStore<TUser>({ name: storeName, storage });\n const refreshKey = `${storeName}-refresh`;\n\n function storageImpl(): Storage | null {\n if (typeof window === \"undefined\") return null;\n return storage === \"session\" ? window.sessionStorage : window.localStorage;\n }\n function readRefreshToken(): string | null {\n return storageImpl()?.getItem(refreshKey) ?? null;\n }\n function writeRefreshToken(token: string | null): void {\n const s = storageImpl();\n if (!s) return;\n if (token) s.setItem(refreshKey, token);\n else s.removeItem(refreshKey);\n }\n\n const state = (): AuthState<TUser> => useAuthStore.getState();\n const getToken = (): string | null => state().token;\n\n /**\n * Load the current user, without letting a `401` end the session.\n *\n * `skipAuthRetry` is what keeps this one client honest: the call is\n * authenticated, but a `401` here surfaces instead of triggering a refresh\n * and `onUnauthorized`. That was the behaviour of the throwaway client this\n * used to build per invocation, and it is the reason the preset needed\n * three clients before 0.66.0.\n *\n * Bound to the epoch current when the request leaves, like `rotate()`: a\n * profile that resolves after `logout()` — or after `logout()` +\n * `login(B)` — is discarded instead of written next to B's token, and the\n * `login()` that asked for it rejects as superseded (#473).\n *\n * @throws {SessionSupersededError} When the epoch changed while the\n * request was in flight, on success and on failure alike.\n */\n async function fetchUser(): Promise<TUser | null> {\n if (!mePath) return state().user;\n const started = epoch;\n let user: TUser;\n try {\n user = await api.get<TUser>(mePath, { skipAuthRetry: true });\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n if (epoch !== started) throw new SessionSupersededError();\n state().setUser(user);\n return user;\n }\n\n let epoch = 0;\n let ending: Promise<void> = Promise.resolve();\n let hooksRunning = 0;\n const loginsInFlight = new Set<Promise<unknown>>();\n const revocations = new Set<Promise<void>>();\n const credentialRequests = new Set<Promise<unknown>>();\n const rotatingEpochs = new Set<number>();\n\n /**\n * Track a login or refresh request until it settles, so a cookie-mode\n * revocation can wait for the response that sets the cookie it revokes.\n *\n * @param request - The request in flight.\n * @returns The same request.\n */\n function trackCredentialRequest<T>(request: Promise<T>): Promise<T> {\n const settled = request.then(\n () => undefined,\n () => undefined,\n );\n credentialRequests.add(settled);\n void settled.then(() => credentialRequests.delete(settled));\n return request;\n }\n\n /**\n * Surface a failed revocation: `onLogoutError`, plus a console warning in a\n * dev build.\n *\n * @param error - What the revocation rejected with.\n */\n function reportLogoutError(error: unknown): void {\n if (isDevBuild()) {\n console.warn(\n \"[tempest-react-sdk] createTempestAuth: logoutPath revocation failed\",\n error,\n );\n }\n try {\n onLogoutError?.(error);\n } catch {\n return;\n }\n }\n\n /**\n * Send one `logoutPath` revocation and track it until it settles. Never\n * rejects.\n *\n * @param build - Produces the request, after whatever wait it needs.\n * @returns A promise settling when the revocation settled.\n */\n function trackRevocation(build: () => Promise<unknown>): Promise<void> {\n const tracked = (async () => {\n try {\n await build();\n } catch (error) {\n reportLogoutError(error);\n }\n })();\n revocations.add(tracked);\n void tracked.then(() => revocations.delete(tracked));\n return tracked;\n }\n\n /**\n * Revoke, in body mode, the refresh token a superseded login or refresh\n * brought back. Nobody can use it — the client discarded it — but it would\n * stay valid on the server until it expires.\n *\n * Cookie mode is left to `revoke()`, which waits for these responses\n * instead: re-sending a cookie revocation here could carry whichever\n * account's cookie the browser holds by then.\n *\n * @param token - The superseded response's access token.\n * @param refreshToken - The superseded response's refresh token.\n */\n function revokeDiscarded(token: string | null, refreshToken: string | undefined): void {\n if (!logoutPath || withCredentials || !refreshToken) return;\n void trackRevocation(() =>\n endedSessionApi(token).post<unknown>(logoutPath, {\n body: refreshBody(refreshToken),\n }),\n );\n }\n\n /**\n * A client that sends an ended session's access token, and never refreshes\n * or ends a session: a `401` there just rejects.\n *\n * @param token - The ended session's access token.\n * @returns The client `onSessionEnd` and the `logoutPath` call go through.\n */\n function endedSessionApi(token: string | null): ApiClient {\n return createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken: () => token,\n });\n }\n\n /**\n * Start a new session epoch: supersede the refresh in flight and give the\n * new epoch a refresh queue of its own, so a `401` under the new session\n * never joins the old session's refresh.\n *\n * The client reads the epoch when each attempt leaves (`getSessionEpoch`),\n * which is what ties a `401` to the session that sent it — no set of\n * tokens to keep, and nothing that grows with the session's length.\n */\n function nextEpoch(): void {\n epoch += 1;\n queue = createRefreshQueue(rotate);\n }\n\n /**\n * Perform one refresh for the epoch that is current when it starts.\n *\n * Checked again after the round trip, on success and on failure alike: a\n * refresh that fails after `logout()` + `login(B)` must not reach\n * `onUnauthorized` either, or it would end B's session.\n *\n * @throws {SessionSupersededError} When the epoch changed during the call.\n */\n async function rotate(): Promise<void> {\n const started = epoch;\n rotatingEpochs.add(started);\n try {\n let data: unknown;\n try {\n data = await trackCredentialRequest(\n api.post<unknown>(refreshPath, {\n body: refreshBody(readRefreshToken()),\n skipAuth: true,\n }),\n );\n } catch (error) {\n if (epoch !== started) throw new SessionSupersededError();\n throw error;\n }\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n state().setToken(token);\n if (refreshToken) writeRefreshToken(refreshToken);\n } finally {\n rotatingEpochs.delete(started);\n }\n }\n\n let queue = createRefreshQueue(rotate);\n\n /**\n * Whether a `401` must be left alone: no refresh, no ending the session.\n *\n * Two cases, both of the current epoch: an attempt that carried no token\n * while a session is now installed (it left before the sign-in, and\n * refreshing or ending the new session for it would punish the wrong\n * session); and an attempt whose token the session has since rotated past\n * (the rotation it would trigger already happened).\n *\n * @param context - The attempt's credential.\n * @returns Whether the attempt is stale within the current session.\n */\n function staleWithinSession(context: RequestAuthContext): boolean {\n const current = getToken();\n if (current === null) return false;\n return context.token === null || context.token !== current;\n }\n\n /**\n * Whether nothing could make a tokenless `401` worth a refresh: no access\n * token and no stored refresh token.\n *\n * With `withCredentials`, the refresh would otherwise be answered by an\n * HttpOnly cookie the client cannot see or clear — after `logout()`, that\n * signed the previous account back in for whoever used the browser next\n * (#474). A `login()` in flight does not count as a session either: the\n * cookie a refresh would present during it is still the ended account's\n * (#496). Restoring a session from the cookie is an explicit `refresh()`,\n * typically at boot, which this does not touch.\n *\n * @returns Whether no session is installed.\n */\n function signedOut(): boolean {\n return getToken() === null && readRefreshToken() === null;\n }\n\n /**\n * Settle a tokenless `401` that arrived with no session installed while a\n * `login()` is in flight: wait for every login in flight, then let the\n * request replay when one of them installed a token.\n *\n * No refresh is sent. In cookie mode one would present whatever cookie\n * the browser holds — after `logout()` without a working `logoutPath`,\n * the previous account's: a failed login then left the client signed in\n * as that account, and a successful one could have its cookie overwritten\n * by the refresh's late `Set-Cookie` (#496).\n *\n * Skipped while an `onSessionEnd` hook runs: an account switch waits on\n * that hook, so a hook awaiting `auth.api` would wait on itself.\n *\n * @throws {Error} When no login is in flight, a hook is running, or every\n * login settled without installing a token — the `401` surfaces as is.\n */\n async function awaitLogins(): Promise<void> {\n if (loginsInFlight.size > 0 && hooksRunning === 0) {\n await Promise.allSettled([...loginsInFlight]);\n if (getToken() !== null) return;\n }\n throw new Error(\"anonymous 401 with no session\");\n }\n\n /**\n * The `refresh` the client calls on a `401`.\n *\n * - An attempt from an ended epoch is refused rather than replayed as\n * whoever is signed in now.\n * - A token this session already rotated past: the replay just picks up the\n * new one — no second refresh.\n * - No token, while a session is now installed: the `401` surfaces as is.\n * - No token, and no session installed: joins this epoch's refresh when\n * one is already in flight — the boot `refresh()` restoring a session\n * from the cookie, which the request then replays under; otherwise waits\n * for a `login()` in flight and replays with its token, see\n * `awaitLogins`; otherwise surfaces the `401` as is, see `signedOut`.\n * - Otherwise: join or start this epoch's refresh.\n *\n * @param context - The credential and epoch the rejected attempt left with.\n * @throws {SessionSupersededError} When the attempt belongs to an ended\n * session, or the session changed during the refresh.\n */\n async function refreshFor(context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) {\n if (context.token === null) throw new Error(\"anonymous 401 under a live session\");\n return;\n }\n if (context.token === null && signedOut()) {\n if (rotatingEpochs.has(epoch)) return queue();\n return awaitLogins();\n }\n return queue();\n }\n\n /**\n * The client's `onUnauthorized`: end the session only when the `401` is the\n * current session's own.\n *\n * The replay after a refresh is checked here too — it can come back `401`\n * after the user signed out and another account signed in, and ending the\n * session then would sign the new account out. A tokenless `401` with no\n * session installed ends nothing either: there is no session to end, and\n * ending \"nothing\" used to move the epoch and supersede the boot\n * `refresh()` in flight.\n *\n * @param context - The credential and epoch of the attempt that failed.\n * @throws {SessionSupersededError} When that attempt belongs to an ended\n * session.\n */\n async function onUnauthorized(_response: Response, context: RequestAuthContext): Promise<void> {\n if (context.epoch !== null && context.epoch !== epoch) throw new SessionSupersededError();\n if (staleWithinSession(context)) return;\n if (context.token === null && signedOut()) return;\n await endSession();\n }\n\n /**\n * Authenticate and install the new session.\n *\n * The previous session ends only once the new credentials are accepted: a\n * login that fails leaves it, and the refresh it may have in flight,\n * untouched. When one was live, `onSessionEnd` runs with `\"switch\"` before\n * the new tokens are installed — see the option for why that order. A\n * `logout()` still tearing down is awaited the same way, so the new\n * account's state never starts before the previous one's teardown ended.\n * Never call it from inside `onSessionEnd`: it would wait on that hook.\n * Every `logoutPath` revocation still in flight is awaited before the\n * request leaves — at most {@link LOGOUT_REVOCATION_WAIT_MS} — so a\n * cookie-clearing response cannot land after the new account's cookies.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} When a `logout()` or another `login()`\n * moved the session while this one was in flight — during its request,\n * during the teardown or while `mePath` was loading the user; the new\n * tokens, or the user, are discarded.\n */\n async function login(credentials: TCredentials): Promise<TUser | null> {\n if (revocations.size > 0) await settleWithin([...revocations], LOGOUT_REVOCATION_WAIT_MS);\n const run = signIn(credentials);\n loginsInFlight.add(run);\n try {\n return await run;\n } finally {\n loginsInFlight.delete(run);\n }\n }\n\n /**\n * The body of `login()`, tracked in `loginsInFlight` by its caller so a\n * tokenless `401` during the sign-in waits for it and replays with the\n * token it installs, see `awaitLogins`. Tracking starts only after a\n * pending revocation settled.\n *\n * @param credentials - Sent as the login body.\n * @returns The user of the new session, or null.\n * @throws {SessionSupersededError} See `login()`.\n */\n async function signIn(credentials: TCredentials): Promise<TUser | null> {\n const started = epoch;\n const data = await trackCredentialRequest(\n api.post<unknown>(loginPath, {\n body: credentials,\n skipAuth: true,\n }),\n );\n const { token, refreshToken } = parseTokens(data);\n if (epoch !== started) {\n revokeDiscarded(token ?? null, refreshToken);\n throw new SessionSupersededError();\n }\n const { done } = finish(\"switch\");\n const mine = epoch;\n await done.catch(() => undefined);\n if (epoch !== mine) throw new SessionSupersededError();\n state().setToken(token);\n writeRefreshToken(refreshToken ?? null);\n const embedded = parseUser?.(data);\n if (embedded != null) {\n state().setUser(embedded);\n return embedded;\n }\n return fetchUser();\n }\n\n /**\n * End the current session, synchronously up to the hook.\n *\n * The epoch moves first, so a refresh resolving between here and the hook\n * is already superseded. The hook only runs when there was a session to\n * end — a token, a stored refresh token or a user — which is what keeps a\n * burst of `401`s from running it once per request.\n *\n * With nothing left to end, the caller waits on the teardown already under\n * way (`ending`, which never rejects, so a later no-op does not inherit an\n * old error). Two callers skip that wait while a hook is running, because\n * they may be the hook itself and would wait on their own teardown forever:\n * `endSession` — a hook awaiting `auth.api` goes out tokenless, gets a\n * `401`, and lands here — and a `logout()` with no session left. `login()`\n * (`\"switch\"`) always waits: the new account's state must not start while\n * the previous one's teardown is still clearing it. A hook awaiting\n * `auth.login()` therefore never settles — misuse the option documents.\n *\n * `\"expired\"` with nothing live leaves the epoch alone: there is nothing to\n * supersede but a refresh with no session behind it — the boot `refresh()`\n * restoring one from the cookie — and moving the epoch would throw that\n * away. `logout()` and `login()` always move it, since they must supersede\n * such a refresh.\n *\n * The returned `done` is a fresh promise derived from the hook, not the one\n * `ending` holds: a `logout()` nobody awaits still surfaces the hook's error\n * as an unhandled rejection instead of losing it.\n *\n * @param reason - Whether the caller signed out, the client gave up, or a\n * login replaced the session.\n * @returns Whether a live session ended here, and a promise settling with\n * the hook.\n */\n function finish(reason: TempestSessionEnd<TUser>[\"reason\"]): {\n live: boolean;\n done: Promise<void>;\n } {\n const { user, token } = state();\n const live = token !== null || user !== null || readRefreshToken() !== null;\n if (live || reason !== \"expired\") nextEpoch();\n state().logout();\n writeRefreshToken(null);\n if (!live) {\n const wait = reason === \"switch\" || hooksRunning === 0;\n return { live, done: wait ? ending : Promise.resolve() };\n }\n if (!onSessionEnd) return { live, done: Promise.resolve() };\n const sessionApi = endedSessionApi(token);\n hooksRunning += 1;\n const run = (async () => {\n try {\n await onSessionEnd({ reason, user, token, api: sessionApi });\n } finally {\n hooksRunning -= 1;\n }\n })();\n ending = run.then(\n () => undefined,\n () => undefined,\n );\n return { live, done: run.then(() => undefined) };\n }\n\n /**\n * Send the `logoutPath` revocation for the session about to end, with the\n * credentials it holds now — read before `finish` clears them.\n *\n * Skipped without `logoutPath`, and in body mode when there is nothing to\n * revoke; in cookie mode it always goes out, since the cookie it revokes is\n * invisible to the client. Never rejects.\n *\n * In cookie mode it first waits — at most\n * {@link LOGOUT_REVOCATION_WAIT_MS} — for the login and refresh responses\n * in flight right now: each one sets a cookie for the session this\n * `logout()` ends, and a revocation that left before it would leave that\n * cookie behind.\n *\n * @returns A promise settling when the revocation settled, or null when\n * none was sent.\n */\n function revoke(): Promise<void> | null {\n if (!logoutPath) return null;\n const path = logoutPath;\n const { token, user } = state();\n const refreshToken = readRefreshToken();\n if (!withCredentials && token === null && user === null && refreshToken === null) {\n return null;\n }\n const inFlight = withCredentials ? [...credentialRequests] : [];\n return trackRevocation(async () => {\n await settleWithin(inFlight, LOGOUT_REVOCATION_WAIT_MS);\n return endedSessionApi(token).post<unknown>(path, { body: refreshBody(refreshToken) });\n });\n }\n\n function logout(): Promise<void> {\n const revocation = revoke();\n const { done } = finish(\"logout\");\n if (!revocation) return done;\n return Promise.all([revocation, done]).then(() => undefined);\n }\n\n /**\n * End the session after the client gave up on it and, when `redirectTo`\n * is set, leave the page once `onSessionEnd` settled.\n *\n * Separate from `logout` so an explicit sign-out stays a pure state change:\n * a caller that already navigates itself would otherwise get a second,\n * competing navigation. The hook is awaited before navigating because a\n * hard navigation aborts whatever request it still had in flight. Only the\n * call that ended a live session navigates; the rest of a burst of `401`s\n * waits on the same teardown, or returns at once inside a hook.\n */\n async function endSession(): Promise<void> {\n const { live, done } = finish(\"expired\");\n await done.catch(() => undefined);\n if (live && redirectTo && typeof window !== \"undefined\") {\n window.location.assign(redirectTo);\n }\n }\n\n const api = createApiClient({\n baseURL,\n prefix,\n withCredentials,\n csrf,\n fetcher,\n getToken,\n getSessionEpoch: () => epoch,\n refresh: refreshFor,\n retry,\n onUnauthorized,\n });\n\n const refresh = (): Promise<void> => queue();\n\n return { useAuthStore, api, login, logout, refresh, getToken };\n}\n"],"mappings":"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"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function e(e,t={}){let{getToken:n}=t,r=null,i=null;return()
|
|
1
|
+
function e(e,t={}){let{getToken:n}=t,r=null,i=null;return t=>{if(r)return r;if(n){let e=n()??null;if(t?t.token!==null&&e!==null&&t.token!==e:i!==null&&e===i)return Promise.resolve()}return r=(async()=>{try{await e(),n&&(i=n()??null)}finally{r=null}})(),r}}exports.createRefreshQueue=e;
|
|
2
2
|
//# sourceMappingURL=refresh-queue.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh-queue.cjs","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"refresh-queue.cjs","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["import type { RequestAuthContext } from \"../http\";\n\nexport interface CreateRefreshQueueOptions {\n /**\n * Reads the credential the refresh installs — typically the access token.\n *\n * Supplying it makes the queue skip a refresh whose work another caller has\n * already done. Without it, only calls that literally overlap in time are\n * collapsed.\n */\n getToken?: () => string | null | undefined;\n}\n\n/**\n * Deduplicate concurrent refresh calls. When multiple 401 responses arrive\n * at once, all of them share the same in-flight `refresh()` promise instead\n * of triggering N parallel refreshes.\n *\n * **In-flight sharing alone does not collapse a burst.** A page that fires\n * several requests at once gets several 401s back, but they do not land inside\n * one window: the stragglers arrive after the first refresh already resolved,\n * find no promise to join, and each starts another one — rotating a token that\n * is already fresh. Measured against a mock backend, five concurrent expired\n * requests took two refreshes, not one.\n *\n * Pass `getToken` to close that gap. Wired as `createApiClient`'s `refresh`, the\n * queue is told which token each rejected request carried: when that token is\n * no longer the current one, the rotation it was about to trigger already\n * happened, so the call returns at once and the replay picks up the new token.\n * The same five requests then take exactly one refresh, and so do twenty.\n *\n * Called by hand, with no context, the queue falls back to remembering the\n * token its last refresh produced and skipping while that token is in place.\n * That fallback cannot tell \"already refreshed\" from \"the refreshed token has\n * since expired\" — both leave the same string in the store — which is why the\n * client passes the context. Before 0.77.0 the client did not, and every\n * access token a refresh issued became unrefreshable once it expired: its `401`\n * skipped the refresh, the replay failed again, and `onUnauthorized` ended the\n * session.\n *\n * @param refresh - Performs the refresh and installs the new credentials.\n * @param options - Optional token reader that enables already-refreshed\n * detection.\n * @returns A function that refreshes at most once per rotation, accepting the\n * {@link RequestAuthContext} `createApiClient` passes on a `401`.\n *\n * @example\n * const refresh = createRefreshQueue(() => AuthService.refresh(), {\n * getToken: () => useAuthStore.getState().token,\n * });\n *\n * // In every request that hits 401:\n * await refresh();\n * // ...retry the original request\n */\nexport function createRefreshQueue(\n refresh: () => Promise<void>,\n options: CreateRefreshQueueOptions = {},\n): (context?: Pick<RequestAuthContext, \"token\">) => Promise<void> {\n const { getToken } = options;\n let current: Promise<void> | null = null;\n let lastIssued: string | null = null;\n\n return (context?: Pick<RequestAuthContext, \"token\">) => {\n if (current) return current;\n\n if (getToken) {\n const now = getToken() ?? null;\n const rotated = context\n ? context.token !== null && now !== null && context.token !== now\n : lastIssued !== null && now === lastIssued;\n if (rotated) return Promise.resolve();\n }\n\n current = (async () => {\n try {\n await refresh();\n if (getToken) lastIssued = getToken() ?? null;\n } finally {\n current = null;\n }\n })();\n return current;\n };\n}\n"],"mappings":"AAuDA,SAAgB,EACZ,EACA,EAAqC,CAAC,EACwB,CAC9D,GAAM,CAAE,YAAa,EACjB,EAAgC,KAChC,EAA4B,KAEhC,MAAQ,IAAgD,CACpD,GAAI,EAAS,OAAO,EAEpB,GAAI,EAAU,CACV,IAAM,EAAM,EAAS,GAAK,KAI1B,GAHgB,EACV,EAAQ,QAAU,MAAQ,IAAQ,MAAQ,EAAQ,QAAU,EAC5D,IAAe,MAAQ,IAAQ,EACxB,OAAO,QAAQ,QAAQ,CACxC,CAUA,MARA,IAAW,SAAY,CACnB,GAAI,CACA,MAAM,EAAQ,EACV,IAAU,EAAa,EAAS,GAAK,KAC7C,QAAU,CACN,EAAU,IACd,CACJ,EAAA,CAAG,EACI,CACX,CACJ"}
|
|
@@ -1,13 +1,20 @@
|
|
|
1
1
|
//#region src/auth/refresh-queue.ts
|
|
2
2
|
function e(e, t = {}) {
|
|
3
3
|
let { getToken: n } = t, r = null, i = null;
|
|
4
|
-
return () =>
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
return (t) => {
|
|
5
|
+
if (r) return r;
|
|
6
|
+
if (n) {
|
|
7
|
+
let e = n() ?? null;
|
|
8
|
+
if (t ? t.token !== null && e !== null && t.token !== e : i !== null && e === i) return Promise.resolve();
|
|
9
9
|
}
|
|
10
|
-
|
|
10
|
+
return r = (async () => {
|
|
11
|
+
try {
|
|
12
|
+
await e(), n && (i = n() ?? null);
|
|
13
|
+
} finally {
|
|
14
|
+
r = null;
|
|
15
|
+
}
|
|
16
|
+
})(), r;
|
|
17
|
+
};
|
|
11
18
|
}
|
|
12
19
|
//#endregion
|
|
13
20
|
export { e as createRefreshQueue };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"refresh-queue.js","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"refresh-queue.js","names":[],"sources":["../../src/auth/refresh-queue.ts"],"sourcesContent":["import type { RequestAuthContext } from \"../http\";\n\nexport interface CreateRefreshQueueOptions {\n /**\n * Reads the credential the refresh installs — typically the access token.\n *\n * Supplying it makes the queue skip a refresh whose work another caller has\n * already done. Without it, only calls that literally overlap in time are\n * collapsed.\n */\n getToken?: () => string | null | undefined;\n}\n\n/**\n * Deduplicate concurrent refresh calls. When multiple 401 responses arrive\n * at once, all of them share the same in-flight `refresh()` promise instead\n * of triggering N parallel refreshes.\n *\n * **In-flight sharing alone does not collapse a burst.** A page that fires\n * several requests at once gets several 401s back, but they do not land inside\n * one window: the stragglers arrive after the first refresh already resolved,\n * find no promise to join, and each starts another one — rotating a token that\n * is already fresh. Measured against a mock backend, five concurrent expired\n * requests took two refreshes, not one.\n *\n * Pass `getToken` to close that gap. Wired as `createApiClient`'s `refresh`, the\n * queue is told which token each rejected request carried: when that token is\n * no longer the current one, the rotation it was about to trigger already\n * happened, so the call returns at once and the replay picks up the new token.\n * The same five requests then take exactly one refresh, and so do twenty.\n *\n * Called by hand, with no context, the queue falls back to remembering the\n * token its last refresh produced and skipping while that token is in place.\n * That fallback cannot tell \"already refreshed\" from \"the refreshed token has\n * since expired\" — both leave the same string in the store — which is why the\n * client passes the context. Before 0.77.0 the client did not, and every\n * access token a refresh issued became unrefreshable once it expired: its `401`\n * skipped the refresh, the replay failed again, and `onUnauthorized` ended the\n * session.\n *\n * @param refresh - Performs the refresh and installs the new credentials.\n * @param options - Optional token reader that enables already-refreshed\n * detection.\n * @returns A function that refreshes at most once per rotation, accepting the\n * {@link RequestAuthContext} `createApiClient` passes on a `401`.\n *\n * @example\n * const refresh = createRefreshQueue(() => AuthService.refresh(), {\n * getToken: () => useAuthStore.getState().token,\n * });\n *\n * // In every request that hits 401:\n * await refresh();\n * // ...retry the original request\n */\nexport function createRefreshQueue(\n refresh: () => Promise<void>,\n options: CreateRefreshQueueOptions = {},\n): (context?: Pick<RequestAuthContext, \"token\">) => Promise<void> {\n const { getToken } = options;\n let current: Promise<void> | null = null;\n let lastIssued: string | null = null;\n\n return (context?: Pick<RequestAuthContext, \"token\">) => {\n if (current) return current;\n\n if (getToken) {\n const now = getToken() ?? null;\n const rotated = context\n ? context.token !== null && now !== null && context.token !== now\n : lastIssued !== null && now === lastIssued;\n if (rotated) return Promise.resolve();\n }\n\n current = (async () => {\n try {\n await refresh();\n if (getToken) lastIssued = getToken() ?? null;\n } finally {\n current = null;\n }\n })();\n return current;\n };\n}\n"],"mappings":";AAuDA,SAAgB,EACZ,GACA,IAAqC,CAAC,GACwB;CAC9D,IAAM,EAAE,gBAAa,GACjB,IAAgC,MAChC,IAA4B;CAEhC,QAAQ,MAAgD;EACpD,IAAI,GAAS,OAAO;EAEpB,IAAI,GAAU;GACV,IAAM,IAAM,EAAS,KAAK;GAI1B,IAHgB,IACV,EAAQ,UAAU,QAAQ,MAAQ,QAAQ,EAAQ,UAAU,IAC5D,MAAe,QAAQ,MAAQ,GACxB,OAAO,QAAQ,QAAQ;EACxC;EAUA,OARA,KAAW,YAAY;GACnB,IAAI;IAEA,AADA,MAAM,EAAQ,GACV,MAAU,IAAa,EAAS,KAAK;GAC7C,UAAU;IACN,IAAU;GACd;EACJ,EAAA,CAAG,GACI;CACX;AACJ"}
|
package/dist/br/pix.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../forms/br-validators.cjs");var t=class extends Error{constructor(e){super(e),this.name=`PixError`}},n=4129,r=65535,i=65535,a=`00`,o=`01`,s=`26`,c=`52`,l=`53`,u=`54`,d=`58`,f=`59`,p=`60`,m=`61`,h=`62`,g=`63`,_=`00`,v=`01`,y=`02`,b=`25`,x=`05`,S=`br.gov.bcb.pix`,C=`01`,w=`11`,T=`12`,E=`0000`,D=`986`,O=`BR`,k=`***`,A=25,j=15,M=25,N=99,P=77;function
|
|
1
|
+
const e=require("../forms/br-validators.cjs");var t=class extends Error{constructor(e){super(e),this.name=`PixError`}},n=4129,r=65535,i=65535,a=`00`,o=`01`,s=`26`,c=`52`,l=`53`,u=`54`,d=`58`,f=`59`,p=`60`,m=`61`,h=`62`,g=`63`,_=`00`,v=`01`,y=`02`,b=`25`,x=`05`,S=`br.gov.bcb.pix`,C=`01`,w=`11`,T=`12`,E=`0000`,D=`986`,O=`BR`,k=`***`,A=25,j=15,M=25,N=99,P=77,F=/^\d+(?:\.\d{0,2})?$/,I=13;function L(e){let t=new TextEncoder().encode(e),a=r;for(let e of t){a^=e<<8;for(let e=0;e<8;e+=1)a=a&32768?(a<<1^n)&i:a<<1&i}return a.toString(16).toUpperCase().padStart(4,`0`)}function R(e){return e.replace(/\D/g,``)}function z(e,n){let r=e.normalize(`NFD`).replace(/\p{Diacritic}/gu,``);if(/[^\x20-\x7E]/.test(r))throw new t(`${n} has characters the BR Code cannot carry: ${JSON.stringify(e)}. Use unaccented ASCII.`);return r}var B=/^[\x20-\x7E]*$/;function V(e,n){if(!B.test(n))throw new t(`Tag ${e} has characters outside the EMV common character set (printable ASCII): ${JSON.stringify(n)}.`);if(n.length>N)throw new t(`Tag ${e} is ${n.length} characters; the EMV length field holds at most ${N}.`);return`${e}${String(n.length).padStart(2,`0`)}${n}`}function H(t){let n=t.trim();if(n===``)return null;if(n.includes(`@`))return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(n)&&n.length<=P?`email`:null;if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(n))return`evp`;let r=R(n);return r.length===14?e.validateCNPJ(r)?`cnpj`:null:r.length===11&&e.validateCPF(r)?`cpf`:n.startsWith(`+`)?/^\+55\d{10,11}$/.test(`+${r}`)?`phone`:null:r.length===10||r.length===11||(r.length===12||r.length===13)&&r.startsWith(`55`)?`phone`:null}function U(e){let n=e.trim(),r=H(n);if(r===null)throw new t(`Not a Pix key: ${JSON.stringify(e)}. Expected a CPF, CNPJ, e-mail, phone (+5511987654321) or EVP (UUID).`);if(r===`email`||r===`evp`)return{type:r,value:n.toLowerCase()};if(r===`phone`){let e=R(n);return{type:r,value:`+55${e.length>11?e.slice(2):e}`}}return{type:r,value:R(n)}}function W(e){if(!Number.isFinite(e))throw new t(`Amount must be a finite number, got ${e}.`);if(e<=0)throw new t(`Amount must be positive, got ${e}. Omit \`amount\` for a QR whose value the payer types.`);let n=e.toFixed(2);if(Number(n)<=0)throw new t(`Amount ${e} rounds to ${n} at two decimals. Omit \`amount\` for a QR whose value the payer types.`);if(n.length>13)throw new t(`Amount ${n} does not fit tag 54, which holds 13 characters.`);return n}function G(e,n,r){let i=z(e.trim(),r);if(i===``)throw new t(`${r} is required.`);if(i.length>n)throw new t(`${r} is ${i.length} characters; the BR Code allows ${n}. Shorten it — truncating here would silently change what the payer sees.`);return i}function K(e){let n=e?.trim()??``;if(n===``||n===k)return V(h,V(x,k));if(!RegExp(`^[A-Za-z0-9]{1,${M}}$`).test(n))throw new t(`txid must be 1 to ${M} letters or digits, got ${JSON.stringify(e)}.`);return V(h,V(x,n))}function q(e){let{value:n}=U(e.key),r=V(_,S)+V(v,n),i=e.description?.trim();if(i!==void 0&&i!==``&&(r+=V(y,z(i,`description`))),r.length>N)throw new t(`Tag 26 is ${r.length} characters, over the ${N} the length field allows. Shorten \`description\`.`);return V(s,r)}function J(e){let n=z(e.url.trim(),`url`).replace(/^https?:\/\//i,``);if(n===``)throw new t(`url is required for a dynamic BR Code.`);let r=V(_,S)+V(b,n);if(r.length>N)throw new t(`Tag 26 is ${r.length} characters, over the ${N} the length field allows. Shorten the payload URL.`);return V(s,r)}function Y(e){let t=e.kind===`dynamic`,n=e.oneTime??t,r=V(a,C);r+=V(o,n?T:w),r+=t?J(e):q(e),r+=V(c,E),r+=V(l,D),!t&&e.amount!==void 0&&(r+=V(u,W(e.amount))),r+=V(d,O),r+=V(f,G(e.merchantName,A,`merchantName`)),r+=V(p,G(e.merchantCity,j,`merchantCity`));let i=e.postalCode===void 0?``:R(e.postalCode);i!==``&&(r+=V(m,i)),r+=K(t?k:e.txid);let s=`${r}${g}04`;return`${s}${L(s)}`}function X(e,n){let r=Array.from(e),i=[],a=0;for(;a<r.length;){let e=r.slice(a,a+2).join(``),o=r.slice(a+2,a+4).join(``);if(!/^\d{2}$/.test(e)||!/^\d{2}$/.test(o))throw new t(`Malformed TLV in ${n} at offset ${a}: expected a 2-digit tag and length.`);let s=Number(o),c=a+4;if(c+s>r.length)throw new t(`Tag ${e} in ${n} declares ${s} characters but only ${r.length-c} remain.`);if(i.some(t=>t.id===e))throw new t(`Tag ${e} in ${n} appears more than once; a BR Code carries each tag once per level.`);i.push({id:e,value:r.slice(c,c+s).join(``)}),a=c+s}return i}function Z(e,t){return e.find(e=>e.id===t)?.value}function Q(e){if(e.length>I||!F.test(e))throw new t(`Tag 54 (amount) must be an amount like "25.50", with "." as the decimal mark, at most two decimals and ${I} characters; got ${JSON.stringify(e)}.`);return Number(e)}function $(e,n={}){let{requireCrc:r=!0}=n,i=e.trim();if(i.length<8)throw new t(`Payload is too short to be a BR Code.`);let C=i.length-8;if(i.slice(C,C+4)!==`${g}04`)throw new t("Payload does not end in a `6304` CRC tag.");let w=i.slice(-4).toUpperCase(),E=L(i.slice(0,-4)),D=w===E;if(!D&&r)throw new t(`CRC mismatch: payload says ${w}, recomputed ${E}.`);let O=X(i.slice(0,C),`payload`);if(O[0]?.id!==a)throw new t(`Tag 00 (payload format indicator) must be the first tag of a BR Code.`);if(O.some(e=>e.id===g))throw new t(`Tag 63 (CRC) must be the last tag of a BR Code; this payload carries another one before the end.`);let k=Z(O,s);if(k===void 0)throw new t(`Payload has no tag 26 (merchant account information).`);let A=X(k,`tag 26`),j=Z(A,_);if(j?.toLowerCase()!==S)throw new t(`Tag 26 is not a Pix account: expected GUI ${S}, got ${JSON.stringify(j)}.`);let M=Z(A,b),N=Z(A,v);if(M!==void 0&&N!==void 0)throw new t(`Tag 26 carries both a key (01) and a URL (25); a BR Code is either static or dynamic, not both.`);let P=Z(O,u),F=Z(X(Z(O,h)??``,`tag 62`),x);return{kind:M===void 0?`static`:`dynamic`,...N===void 0?{}:{key:N,keyType:H(N)??void 0},...M===void 0?{}:{url:M},merchantName:Z(O,f)??``,merchantCity:Z(O,p)??``,...P===void 0?{}:{amount:Q(P)},currency:Z(O,l)??``,countryCode:Z(O,d)??``,merchantCategoryCode:Z(O,c)??``,...F===void 0?{}:{txid:F},...Z(A,y)===void 0?{}:{description:Z(A,y)},...Z(O,m)===void 0?{}:{postalCode:Z(O,m)},oneTime:Z(O,o)===T,crc:w,crcValid:D,fields:O}}exports.PixError=t,exports.normalizePixKey=U,exports.parsePixPayload=$,exports.pixCrc16=L,exports.pixKeyType=H,exports.pixPayload=Y;
|
|
2
2
|
//# sourceMappingURL=pix.cjs.map
|