alex-evo-sh-auth 0.0.17 → 0.0.22

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.
@@ -1,24 +1,29 @@
1
- import ue, { createContext as fe, useState as I, useCallback as j, useEffect as N, useContext as B, useRef as de } from "react";
2
- import { Outlet as H } from "react-router-dom";
3
- async function me(r) {
4
- const t = await fetch(`${r.authServer}/refresh`, {
1
+ import fe, { createContext as de, useState as I, useCallback as C, useEffect as N, useContext as X, useRef as me } from "react";
2
+ import { Outlet as B } from "react-router-dom";
3
+ async function ge(t) {
4
+ const r = await fetch(`${t.authServer}/refresh`, {
5
5
  method: "POST",
6
+ credentials: "include",
6
7
  headers: {
7
8
  "Content-Type": "application/json"
8
9
  },
9
10
  body: JSON.stringify({
10
11
  grant_type: "refresh_token",
11
- client_id: r.clientId
12
+ client_id: t.clientId
12
13
  })
13
14
  });
14
- if (t.status === 401)
15
- return localStorage.removeItem(r.baseKey + "_access"), null;
16
- const o = await t.json();
17
- return localStorage.setItem(r.baseKey + "_access", o.access), o.access;
15
+ if (r.status === 401)
16
+ return localStorage.removeItem(t.baseKey + "_access"), null;
17
+ if (!r.ok)
18
+ throw new Error(`Token refresh failed: ${r.status} ${await r.text()}`);
19
+ const n = await r.json();
20
+ if (typeof n.access != "string" || !n.access)
21
+ throw new Error("Token refresh response did not contain an access token");
22
+ return localStorage.setItem(t.baseKey + "_access", n.access), n.access;
18
23
  }
19
- class Se {
20
- constructor(t, o) {
21
- this.onAuthFail = o, this.config = t;
24
+ class xe {
25
+ constructor(r, n) {
26
+ this.onAuthFail = n, this.config = r;
22
27
  }
23
28
  onAuthFail;
24
29
  refreshPromise = null;
@@ -26,59 +31,60 @@ class Se {
26
31
  getToken() {
27
32
  return localStorage.getItem(this.config.baseKey + "_access");
28
33
  }
29
- setToken(t) {
30
- t ? localStorage.setItem(this.config.baseKey + "_access", t) : localStorage.removeItem(this.config.baseKey + "_access");
34
+ setToken(r) {
35
+ r ? localStorage.setItem(this.config.baseKey + "_access", r) : localStorage.removeItem(this.config.baseKey + "_access");
31
36
  }
32
37
  async getValidToken() {
33
- let t = this.getToken();
34
- return t || (this.refreshPromise || (this.refreshPromise = me(this.config).then((o) => (this.setToken(o), o)).finally(() => {
38
+ let r = this.getToken();
39
+ return r || (this.refreshPromise || (this.refreshPromise = ge(this.config).then((n) => (this.setToken(n), n)).finally(() => {
35
40
  this.refreshPromise = null;
36
- })), t = await this.refreshPromise, !t && this.onAuthFail && this.onAuthFail(), t);
41
+ })), r = await this.refreshPromise, !r && this.onAuthFail && this.onAuthFail(), r);
37
42
  }
38
43
  }
39
- class ke {
44
+ class Oe {
40
45
  authServer;
41
46
  clientId;
42
47
  redirectUri;
43
48
  homePage;
44
49
  baseKey;
45
- constructor(t, o, s, a, i) {
46
- this.authServer = t, this.clientId = o, this.redirectUri = s, this.homePage = a, this.baseKey = i;
50
+ constructor(r, n, o, s, c) {
51
+ this.authServer = r, this.clientId = n, this.redirectUri = o, this.homePage = s, this.baseKey = c;
47
52
  }
48
53
  }
49
- async function X(r, t, o = {}, s) {
50
- let a = r.getToken();
51
- const i = (d) => fetch(t, {
52
- ...o,
54
+ async function $(t, r, n = {}, o) {
55
+ let s = t.getToken();
56
+ const c = (d) => fetch(r, {
57
+ ...n,
58
+ credentials: n.credentials ?? "include",
53
59
  headers: {
54
- ...o.headers,
60
+ ...n.headers,
55
61
  Authorization: d ? `Bearer ${d}` : ""
56
62
  }
57
- });
58
- let l = await i(a);
59
- return l.status !== 401 ? l : (r.setToken(null), a = await r.getValidToken(), a ? i(a) : (s?.(), l));
63
+ }), l = await c(s);
64
+ return l.status !== 401 ? l : (t.setToken(null), s = await t.getValidToken(), s ? c(s) : (o?.(), l));
60
65
  }
61
- async function he(r) {
62
- const t = new URLSearchParams(window.location.search), o = t.get("code"), s = t.get("state");
63
- if (!o)
66
+ async function pe(t) {
67
+ const r = new URLSearchParams(window.location.search), n = r.get("code"), o = r.get("state");
68
+ if (!n)
64
69
  throw new Error("Missing OAuth code");
65
- const a = sessionStorage.getItem("oauth_state");
66
- if (!s || s !== a)
70
+ const s = sessionStorage.getItem("oauth_state");
71
+ if (!o || o !== s)
67
72
  throw new Error("Invalid OAuth state");
68
- const i = sessionStorage.getItem("pkce_verifier");
69
- if (!i)
73
+ const c = sessionStorage.getItem("pkce_verifier");
74
+ if (!c)
70
75
  throw new Error("Missing PKCE verifier");
71
76
  const l = await fetch(
72
- `${r.config.authServer}/token`,
77
+ `${t.config.authServer}/token`,
73
78
  {
74
79
  method: "POST",
80
+ credentials: "include",
75
81
  headers: {
76
82
  "Content-Type": "application/json"
77
83
  },
78
84
  body: JSON.stringify({
79
- client_id: r.config.clientId,
80
- code: o,
81
- code_verifier: i
85
+ client_id: t.config.clientId,
86
+ code: n,
87
+ code_verifier: c
82
88
  })
83
89
  }
84
90
  );
@@ -89,205 +95,249 @@ async function he(r) {
89
95
  );
90
96
  }
91
97
  const d = await l.json();
92
- r.setToken(d.access), sessionStorage.removeItem("oauth_state"), sessionStorage.removeItem("pkce_verifier");
98
+ if (typeof d.access != "string" || !d.access)
99
+ throw new Error("Token response did not contain an access token");
100
+ t.setToken(d.access), sessionStorage.removeItem("oauth_state"), sessionStorage.removeItem("pkce_verifier");
93
101
  }
94
- function ge(r = 64) {
95
- const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
96
- let o = "";
97
- const s = new Uint8Array(r);
98
- crypto.getRandomValues(s);
99
- for (let a = 0; a < s.length; a++)
100
- o += t[s[a] % t.length];
101
- return o;
102
+ function he(t = 64) {
103
+ const r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
104
+ let n = "";
105
+ const o = new Uint8Array(t);
106
+ crypto.getRandomValues(o);
107
+ for (let s = 0; s < o.length; s++)
108
+ n += r[o[s] % r.length];
109
+ return n;
102
110
  }
103
- async function _e(r) {
104
- const o = new TextEncoder().encode(r), s = await crypto.subtle.digest("SHA-256", o);
105
- return new Uint8Array(s);
111
+ async function _e(t) {
112
+ const n = new TextEncoder().encode(t), o = await crypto.subtle.digest("SHA-256", n);
113
+ return new Uint8Array(o);
106
114
  }
107
- function pe(r) {
108
- return btoa(String.fromCharCode(...Array.from(r))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
115
+ function ve(t) {
116
+ return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
109
117
  }
110
- async function C(r) {
111
- const t = ge(64), o = pe(await _e(t));
112
- sessionStorage.setItem("pkce_verifier", t);
113
- const s = crypto.randomUUID();
114
- sessionStorage.setItem("oauth_state", s);
115
- const a = new URLSearchParams({
118
+ async function Z(t) {
119
+ const r = he(64), n = ve(await _e(r));
120
+ sessionStorage.setItem("pkce_verifier", r);
121
+ const o = crypto.randomUUID();
122
+ sessionStorage.setItem("oauth_state", o);
123
+ const s = new URLSearchParams({
116
124
  response_type: "code",
117
- client_id: r.config.clientId,
118
- redirect_uri: r.config.redirectUri,
119
- code_challenge: o,
125
+ client_id: t.config.clientId,
126
+ redirect_uri: t.config.redirectUri,
127
+ code_challenge: n,
120
128
  code_challenge_method: "S256",
121
- state: s
129
+ state: o
122
130
  });
123
- window.location.href = `${r.config.authServer}/authorize?${a}`;
131
+ window.location.href = `${t.config.authServer}/authorize?${s}`;
124
132
  }
125
- async function z(r) {
133
+ async function we(t) {
126
134
  try {
127
- await X(r, `${r.config.authServer}/logout`, {
135
+ await $(t, `${t.config.authServer}/logout`, {
128
136
  method: "POST",
129
137
  headers: {
130
138
  "Content-Type": "application/json"
131
139
  },
132
140
  body: JSON.stringify({
133
- client_id: r.config.clientId
141
+ client_id: t.config.clientId
134
142
  })
135
- }), localStorage.removeItem(r.config.baseKey + "_access"), await C(r);
136
- } catch (t) {
137
- console.error(t);
143
+ }), localStorage.removeItem(t.config.baseKey + "_access"), await Z(t);
144
+ } catch (r) {
145
+ console.error(r);
138
146
  }
139
147
  }
140
- const $ = fe({
148
+ async function y(t, r, n = {}) {
149
+ const o = await $(t, `${t.config.authServer}/settings${r}`, n);
150
+ if (!o.ok) {
151
+ const s = await o.text();
152
+ throw new Error(`Settings request failed (${o.status}): ${s}`);
153
+ }
154
+ return o;
155
+ }
156
+ async function ye(t) {
157
+ return (await y(t, "")).json();
158
+ }
159
+ async function z(t, r) {
160
+ return (await (await y(t, `/${encodeURIComponent(r)}`)).json()).value;
161
+ }
162
+ async function Ee(t) {
163
+ return (await y(t, "/meta")).json();
164
+ }
165
+ async function Se(t, r) {
166
+ return (await y(t, "", {
167
+ method: "PATCH",
168
+ headers: { "Content-Type": "application/json" },
169
+ body: JSON.stringify({ settings: r })
170
+ })).json();
171
+ }
172
+ async function be(t, r, n) {
173
+ return (await y(t, `/${encodeURIComponent(r)}`, {
174
+ method: "PUT",
175
+ headers: { "Content-Type": "application/json" },
176
+ body: JSON.stringify({ value: n })
177
+ })).json();
178
+ }
179
+ function Ce(t) {
180
+ return {
181
+ getSettings: () => ye(t),
182
+ getSetting: (r) => z(t, r),
183
+ getSettingsMeta: () => Ee(t),
184
+ updateSettings: (r) => Se(t, r),
185
+ updateSetting: (r, n) => be(t, r, n),
186
+ /** Удобный способ получить текущий язык интерфейса. */
187
+ getLanguage: () => z(t, "language")
188
+ };
189
+ }
190
+ const U = de({
141
191
  login: () => {
142
192
  },
143
193
  logout: () => {
144
194
  },
145
- loadMe: () => {
195
+ loadMe: async () => {
146
196
  },
147
197
  authManager: null,
148
198
  user: null,
149
199
  loading: !1
150
200
  });
151
- var S = { exports: {} }, v = {};
152
- var q;
153
- function ve() {
154
- if (q) return v;
155
- q = 1;
156
- var r = /* @__PURE__ */ Symbol.for("react.transitional.element"), t = /* @__PURE__ */ Symbol.for("react.fragment");
157
- function o(s, a, i) {
201
+ var k = { exports: {} }, v = {};
202
+ var G;
203
+ function Te() {
204
+ if (G) return v;
205
+ G = 1;
206
+ var t = /* @__PURE__ */ Symbol.for("react.transitional.element"), r = /* @__PURE__ */ Symbol.for("react.fragment");
207
+ function n(o, s, c) {
158
208
  var l = null;
159
- if (i !== void 0 && (l = "" + i), a.key !== void 0 && (l = "" + a.key), "key" in a) {
160
- i = {};
161
- for (var d in a)
162
- d !== "key" && (i[d] = a[d]);
163
- } else i = a;
164
- return a = i.ref, {
165
- $$typeof: r,
166
- type: s,
209
+ if (c !== void 0 && (l = "" + c), s.key !== void 0 && (l = "" + s.key), "key" in s) {
210
+ c = {};
211
+ for (var d in s)
212
+ d !== "key" && (c[d] = s[d]);
213
+ } else c = s;
214
+ return s = c.ref, {
215
+ $$typeof: t,
216
+ type: o,
167
217
  key: l,
168
- ref: a !== void 0 ? a : null,
169
- props: i
218
+ ref: s !== void 0 ? s : null,
219
+ props: c
170
220
  };
171
221
  }
172
- return v.Fragment = t, v.jsx = o, v.jsxs = o, v;
222
+ return v.Fragment = r, v.jsx = n, v.jsxs = n, v;
173
223
  }
174
- var E = {};
175
- var G;
176
- function Ee() {
177
- return G || (G = 1, process.env.NODE_ENV !== "production" && (function() {
178
- function r(e) {
224
+ var w = {};
225
+ var K;
226
+ function ke() {
227
+ return K || (K = 1, process.env.NODE_ENV !== "production" && (function() {
228
+ function t(e) {
179
229
  if (e == null) return null;
180
230
  if (typeof e == "function")
181
- return e.$$typeof === ie ? null : e.displayName || e.name || null;
231
+ return e.$$typeof === ce ? null : e.displayName || e.name || null;
182
232
  if (typeof e == "string") return e;
183
233
  switch (e) {
184
- case k:
234
+ case R:
185
235
  return "Fragment";
186
- case Q:
236
+ case ee:
187
237
  return "Profiler";
188
- case Z:
238
+ case M:
189
239
  return "StrictMode";
190
- case ne:
191
- return "Suspense";
192
240
  case oe:
193
- return "SuspenseList";
241
+ return "Suspense";
194
242
  case se:
243
+ return "SuspenseList";
244
+ case ie:
195
245
  return "Activity";
196
246
  }
197
247
  if (typeof e == "object")
198
248
  switch (typeof e.tag == "number" && console.error(
199
249
  "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
200
250
  ), e.$$typeof) {
201
- case M:
251
+ case Q:
202
252
  return "Portal";
203
253
  case re:
204
254
  return e.displayName || "Context";
205
- case ee:
206
- return (e._context.displayName || "Context") + ".Consumer";
207
255
  case te:
208
- var n = e.render;
209
- return e = e.displayName, e || (e = n.displayName || n.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
256
+ return (e._context.displayName || "Context") + ".Consumer";
257
+ case ne:
258
+ var a = e.render;
259
+ return e = e.displayName, e || (e = a.displayName || a.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
210
260
  case ae:
211
- return n = e.displayName || null, n !== null ? n : r(e.type) || "Memo";
212
- case R:
213
- n = e._payload, e = e._init;
261
+ return a = e.displayName || null, a !== null ? a : t(e.type) || "Memo";
262
+ case P:
263
+ a = e._payload, e = e._init;
214
264
  try {
215
- return r(e(n));
265
+ return t(e(a));
216
266
  } catch {
217
267
  }
218
268
  }
219
269
  return null;
220
270
  }
221
- function t(e) {
271
+ function r(e) {
222
272
  return "" + e;
223
273
  }
224
- function o(e) {
274
+ function n(e) {
225
275
  try {
226
- t(e);
227
- var n = !1;
276
+ r(e);
277
+ var a = !1;
228
278
  } catch {
229
- n = !0;
279
+ a = !0;
230
280
  }
231
- if (n) {
232
- n = console;
233
- var c = n.error, u = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
234
- return c.call(
235
- n,
281
+ if (a) {
282
+ a = console;
283
+ var i = a.error, u = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
284
+ return i.call(
285
+ a,
236
286
  "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
237
287
  u
238
- ), t(e);
288
+ ), r(e);
239
289
  }
240
290
  }
241
- function s(e) {
242
- if (e === k) return "<>";
243
- if (typeof e == "object" && e !== null && e.$$typeof === R)
291
+ function o(e) {
292
+ if (e === R) return "<>";
293
+ if (typeof e == "object" && e !== null && e.$$typeof === P)
244
294
  return "<...>";
245
295
  try {
246
- var n = r(e);
247
- return n ? "<" + n + ">" : "<...>";
296
+ var a = t(e);
297
+ return a ? "<" + a + ">" : "<...>";
248
298
  } catch {
249
299
  return "<...>";
250
300
  }
251
301
  }
252
- function a() {
253
- var e = P.A;
302
+ function s() {
303
+ var e = A.A;
254
304
  return e === null ? null : e.getOwner();
255
305
  }
256
- function i() {
306
+ function c() {
257
307
  return Error("react-stack-top-frame");
258
308
  }
259
309
  function l(e) {
260
- if (Y.call(e, "key")) {
261
- var n = Object.getOwnPropertyDescriptor(e, "key").get;
262
- if (n && n.isReactWarning) return !1;
310
+ if (L.call(e, "key")) {
311
+ var a = Object.getOwnPropertyDescriptor(e, "key").get;
312
+ if (a && a.isReactWarning) return !1;
263
313
  }
264
314
  return e.key !== void 0;
265
315
  }
266
- function d(e, n) {
267
- function c() {
268
- L || (L = !0, console.error(
316
+ function d(e, a) {
317
+ function i() {
318
+ D || (D = !0, console.error(
269
319
  "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
270
- n
320
+ a
271
321
  ));
272
322
  }
273
- c.isReactWarning = !0, Object.defineProperty(e, "key", {
274
- get: c,
323
+ i.isReactWarning = !0, Object.defineProperty(e, "key", {
324
+ get: i,
275
325
  configurable: !0
276
326
  });
277
327
  }
278
328
  function _() {
279
- var e = r(this.type);
280
- return D[e] || (D[e] = !0, console.error(
329
+ var e = t(this.type);
330
+ return J[e] || (J[e] = !0, console.error(
281
331
  "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
282
332
  )), e = this.props.ref, e !== void 0 ? e : null;
283
333
  }
284
- function b(e, n, c, u, T, O) {
285
- var f = c.ref;
334
+ function E(e, a, i, u, T, x) {
335
+ var f = i.ref;
286
336
  return e = {
287
- $$typeof: U,
337
+ $$typeof: Y,
288
338
  type: e,
289
- key: n,
290
- props: c,
339
+ key: a,
340
+ props: i,
291
341
  _owner: u
292
342
  }, (f !== void 0 ? f : null) !== null ? Object.defineProperty(e, "ref", {
293
343
  enumerable: !1,
@@ -311,28 +361,28 @@ function Ee() {
311
361
  configurable: !1,
312
362
  enumerable: !1,
313
363
  writable: !0,
314
- value: O
364
+ value: x
315
365
  }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
316
366
  }
317
- function p(e, n, c, u, T, O) {
318
- var f = n.children;
367
+ function g(e, a, i, u, T, x) {
368
+ var f = a.children;
319
369
  if (f !== void 0)
320
370
  if (u)
321
- if (ce(f)) {
371
+ if (le(f)) {
322
372
  for (u = 0; u < f.length; u++)
323
- m(f[u]);
373
+ p(f[u]);
324
374
  Object.freeze && Object.freeze(f);
325
375
  } else
326
376
  console.error(
327
377
  "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
328
378
  );
329
- else m(f);
330
- if (Y.call(n, "key")) {
331
- f = r(e);
332
- var h = Object.keys(n).filter(function(le) {
333
- return le !== "key";
379
+ else p(f);
380
+ if (L.call(a, "key")) {
381
+ f = t(e);
382
+ var h = Object.keys(a).filter(function(ue) {
383
+ return ue !== "key";
334
384
  });
335
- u = 0 < h.length ? "{key: someKey, " + h.join(": ..., ") + ": ...}" : "{key: someKey}", W[f + u] || (h = 0 < h.length ? "{" + h.join(": ..., ") + ": ...}" : "{}", console.error(
385
+ u = 0 < h.length ? "{key: someKey, " + h.join(": ..., ") + ": ...}" : "{key: someKey}", q[f + u] || (h = 0 < h.length ? "{" + h.join(": ..., ") + ": ...}" : "{}", console.error(
336
386
  `A props object containing a "key" prop is being spread into JSX:
337
387
  let props = %s;
338
388
  <%s {...props} />
@@ -343,156 +393,163 @@ React keys must be passed directly to JSX without using spread:
343
393
  f,
344
394
  h,
345
395
  f
346
- ), W[f + u] = !0);
396
+ ), q[f + u] = !0);
347
397
  }
348
- if (f = null, c !== void 0 && (o(c), f = "" + c), l(n) && (o(n.key), f = "" + n.key), "key" in n) {
349
- c = {};
350
- for (var x in n)
351
- x !== "key" && (c[x] = n[x]);
352
- } else c = n;
398
+ if (f = null, i !== void 0 && (n(i), f = "" + i), l(a) && (n(a.key), f = "" + a.key), "key" in a) {
399
+ i = {};
400
+ for (var O in a)
401
+ O !== "key" && (i[O] = a[O]);
402
+ } else i = a;
353
403
  return f && d(
354
- c,
404
+ i,
355
405
  typeof e == "function" ? e.displayName || e.name || "Unknown" : e
356
- ), b(
406
+ ), E(
357
407
  e,
358
408
  f,
359
- c,
360
- a(),
409
+ i,
410
+ s(),
361
411
  T,
362
- O
412
+ x
363
413
  );
364
414
  }
365
- function m(e) {
366
- w(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === R && (e._payload.status === "fulfilled" ? w(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
415
+ function p(e) {
416
+ S(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === P && (e._payload.status === "fulfilled" ? S(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
367
417
  }
368
- function w(e) {
369
- return typeof e == "object" && e !== null && e.$$typeof === U;
418
+ function S(e) {
419
+ return typeof e == "object" && e !== null && e.$$typeof === Y;
370
420
  }
371
- var y = ue, U = /* @__PURE__ */ Symbol.for("react.transitional.element"), M = /* @__PURE__ */ Symbol.for("react.portal"), k = /* @__PURE__ */ Symbol.for("react.fragment"), Z = /* @__PURE__ */ Symbol.for("react.strict_mode"), Q = /* @__PURE__ */ Symbol.for("react.profiler"), ee = /* @__PURE__ */ Symbol.for("react.consumer"), re = /* @__PURE__ */ Symbol.for("react.context"), te = /* @__PURE__ */ Symbol.for("react.forward_ref"), ne = /* @__PURE__ */ Symbol.for("react.suspense"), oe = /* @__PURE__ */ Symbol.for("react.suspense_list"), ae = /* @__PURE__ */ Symbol.for("react.memo"), R = /* @__PURE__ */ Symbol.for("react.lazy"), se = /* @__PURE__ */ Symbol.for("react.activity"), ie = /* @__PURE__ */ Symbol.for("react.client.reference"), P = y.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, Y = Object.prototype.hasOwnProperty, ce = Array.isArray, A = console.createTask ? console.createTask : function() {
421
+ var b = fe, Y = /* @__PURE__ */ Symbol.for("react.transitional.element"), Q = /* @__PURE__ */ Symbol.for("react.portal"), R = /* @__PURE__ */ Symbol.for("react.fragment"), M = /* @__PURE__ */ Symbol.for("react.strict_mode"), ee = /* @__PURE__ */ Symbol.for("react.profiler"), te = /* @__PURE__ */ Symbol.for("react.consumer"), re = /* @__PURE__ */ Symbol.for("react.context"), ne = /* @__PURE__ */ Symbol.for("react.forward_ref"), oe = /* @__PURE__ */ Symbol.for("react.suspense"), se = /* @__PURE__ */ Symbol.for("react.suspense_list"), ae = /* @__PURE__ */ Symbol.for("react.memo"), P = /* @__PURE__ */ Symbol.for("react.lazy"), ie = /* @__PURE__ */ Symbol.for("react.activity"), ce = /* @__PURE__ */ Symbol.for("react.client.reference"), A = b.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, L = Object.prototype.hasOwnProperty, le = Array.isArray, j = console.createTask ? console.createTask : function() {
372
422
  return null;
373
423
  };
374
- y = {
424
+ b = {
375
425
  react_stack_bottom_frame: function(e) {
376
426
  return e();
377
427
  }
378
428
  };
379
- var L, D = {}, J = y.react_stack_bottom_frame.bind(
380
- y,
381
- i
382
- )(), V = A(s(i)), W = {};
383
- E.Fragment = k, E.jsx = function(e, n, c) {
384
- var u = 1e4 > P.recentlyCreatedOwnerStacks++;
385
- return p(
429
+ var D, J = {}, V = b.react_stack_bottom_frame.bind(
430
+ b,
431
+ c
432
+ )(), W = j(o(c)), q = {};
433
+ w.Fragment = R, w.jsx = function(e, a, i) {
434
+ var u = 1e4 > A.recentlyCreatedOwnerStacks++;
435
+ return g(
386
436
  e,
387
- n,
388
- c,
437
+ a,
438
+ i,
389
439
  !1,
390
- u ? Error("react-stack-top-frame") : J,
391
- u ? A(s(e)) : V
440
+ u ? Error("react-stack-top-frame") : V,
441
+ u ? j(o(e)) : W
392
442
  );
393
- }, E.jsxs = function(e, n, c) {
394
- var u = 1e4 > P.recentlyCreatedOwnerStacks++;
395
- return p(
443
+ }, w.jsxs = function(e, a, i) {
444
+ var u = 1e4 > A.recentlyCreatedOwnerStacks++;
445
+ return g(
396
446
  e,
397
- n,
398
- c,
447
+ a,
448
+ i,
399
449
  !0,
400
- u ? Error("react-stack-top-frame") : J,
401
- u ? A(s(e)) : V
450
+ u ? Error("react-stack-top-frame") : V,
451
+ u ? j(o(e)) : W
402
452
  );
403
453
  };
404
- })()), E;
454
+ })()), w;
405
455
  }
406
- var K;
407
- function be() {
408
- return K || (K = 1, process.env.NODE_ENV === "production" ? S.exports = ve() : S.exports = Ee()), S.exports;
456
+ var H;
457
+ function Re() {
458
+ return H || (H = 1, process.env.NODE_ENV === "production" ? k.exports = Te() : k.exports = ke()), k.exports;
409
459
  }
410
- var g = be();
411
- const Re = ({ children: r, authManager: t }) => {
412
- const [o, s] = I(null), [a, i] = I(!0), l = j(async () => {
413
- i(!0);
414
- const b = localStorage.getItem(t.config.baseKey + "_access");
415
- if (!b) {
416
- s(null), i(!1);
417
- return;
418
- }
460
+ var m = Re();
461
+ const Ie = ({ children: t, authManager: r }) => {
462
+ const [n, o] = I(null), [s, c] = I(!0), l = C(async () => {
419
463
  try {
420
- const p = await X(t, `${t.config.authServer}/me`, {
421
- headers: {
422
- Authorization: `Bearer ${b}`
423
- }
424
- });
425
- if (!p.ok) throw new Error("not found");
426
- const m = await p.json();
427
- s({
428
- role: m.role.role_name,
429
- userId: m.user_id,
430
- userName: m.user_name,
431
- privileges: m.role.privileges.map((w) => w.privilege.trim())
464
+ if (!await r.getValidToken()) {
465
+ o(null);
466
+ return;
467
+ }
468
+ const g = await $(r, `${r.config.authServer}/me`);
469
+ if (g.status === 401) {
470
+ r.setToken(null), o(null);
471
+ return;
472
+ }
473
+ if (!g.ok)
474
+ throw new Error(`Failed to load current user: ${g.status}`);
475
+ const p = await g.json();
476
+ o({
477
+ role: p.role.role_name,
478
+ userId: p.user_id,
479
+ userName: p.user_name,
480
+ privileges: p.role.privileges.map((S) => S.privilege.trim())
432
481
  });
433
- } catch {
434
- s(null);
482
+ } catch (E) {
483
+ console.error("Failed to load current user:", E), o(null);
484
+ } finally {
485
+ c(!1);
435
486
  }
436
- i(!1);
437
- }, []);
487
+ }, [r]);
438
488
  N(() => {
439
- l();
489
+ Promise.resolve().then(l);
440
490
  }, [l]);
441
- const d = j(() => {
442
- C(t);
443
- }, [C, t]), _ = j(() => {
444
- z(t), s(null);
445
- }, [z, t]);
446
- return /* @__PURE__ */ g.jsx($.Provider, { value: { loadMe: l, loading: a, user: o, login: d, authManager: t, logout: _ }, children: r });
447
- }, Pe = () => {
448
- const { authManager: r, loadMe: t } = B($), o = de(!1);
491
+ const d = C(() => {
492
+ Z(r);
493
+ }, [r]), _ = C(() => {
494
+ we(r), o(null);
495
+ }, [r]);
496
+ return /* @__PURE__ */ m.jsx(U.Provider, { value: { loadMe: l, loading: s, user: n, login: d, authManager: r, logout: _ }, children: t });
497
+ }, Ne = () => {
498
+ const { authManager: t, login: r } = X(U), n = me(!1), [o, s] = I(null);
449
499
  return N(() => {
450
- if (!r || o.current)
500
+ if (!t || n.current)
451
501
  return;
452
- o.current = !0, (async () => {
502
+ n.current = !0, (async () => {
453
503
  try {
454
- await he(r), await t(), window.location.replace(
455
- r.config.homePage
456
- );
457
- } catch (a) {
458
- console.error("Authentication callback failed:", a), window.location.replace(
459
- r.config.homePage
460
- );
504
+ await pe(t), window.location.replace(t.config.homePage);
505
+ } catch (l) {
506
+ console.error("Authentication callback failed:", l), s("Не удалось завершить вход. Попробуйте снова.");
461
507
  }
462
508
  })();
463
- }, [r, t]), /* @__PURE__ */ g.jsx("div", { children: "Авторизация..." });
509
+ }, [t]), o ? /* @__PURE__ */ m.jsxs("div", { role: "alert", children: [
510
+ /* @__PURE__ */ m.jsxs("p", { children: [
511
+ "Не удалось завершить вход: ",
512
+ o
513
+ ] }),
514
+ /* @__PURE__ */ m.jsx("button", { type: "button", onClick: r, children: "Повторить вход" })
515
+ ] }) : /* @__PURE__ */ m.jsx("div", { children: "Авторизация..." });
464
516
  }, F = () => {
465
- const r = B($);
466
- if (!r || !r.authManager) throw new Error("AuthContext not found");
467
- return r;
468
- }, we = (r) => {
469
- const { user: t } = F();
470
- return !!t?.privileges?.includes(r);
517
+ const t = X(U);
518
+ if (!t || !t.authManager) throw new Error("AuthContext not found");
519
+ return t;
520
+ }, Pe = (t) => {
521
+ const { user: r } = F();
522
+ return !!r?.privileges?.includes(t);
471
523
  };
472
- function Ae({ privilege: r, invalidPage: t, loadingPage: o }) {
473
- const { loading: s } = F(), a = we(r);
474
- return s ? o : a ? /* @__PURE__ */ g.jsx(H, {}) : t;
524
+ function $e({ privilege: t, invalidPage: r, loadingPage: n }) {
525
+ const { loading: o } = F(), s = Pe(t);
526
+ return o ? n : s ? /* @__PURE__ */ m.jsx(B, {}) : r;
475
527
  }
476
- function Oe({ loadingPage: r }) {
477
- const { authManager: t, login: o, user: s } = F(), [a, i] = I(!0);
528
+ function Ue({ loadingPage: t }) {
529
+ const { authManager: r, login: n, loading: o } = F(), s = r?.getToken() ?? null;
478
530
  return N(() => {
479
- if (!t) return;
480
- t.getToken() ? i(!1) : o();
481
- }, [t, s]), t ? a ? r ?? /* @__PURE__ */ g.jsx("div", { children: "Loading..." }) : /* @__PURE__ */ g.jsx(H, {}) : /* @__PURE__ */ g.jsx("p", { children: "invalud config" });
531
+ r && !o && !s && n();
532
+ }, [r, o, n, s]), o || !s ? t ?? /* @__PURE__ */ m.jsx("div", { children: "Loading..." }) : /* @__PURE__ */ m.jsx(B, {});
482
533
  }
483
534
  export {
484
- $ as AuthContext,
485
- Se as AuthManager,
486
- Re as AuthProvider,
487
- Pe as CallbackPage,
488
- ke as Config,
489
- Ae as PrivilegeGate,
490
- Oe as ProtectGate,
491
- X as apiFetch,
492
- he as handleCallback,
493
- C as login,
494
- z as logout,
495
- me as refreshToken,
535
+ U as AuthContext,
536
+ xe as AuthManager,
537
+ Ie as AuthProvider,
538
+ Ne as CallbackPage,
539
+ Oe as Config,
540
+ $e as PrivilegeGate,
541
+ Ue as ProtectGate,
542
+ $ as apiFetch,
543
+ Ce as createSettingsApi,
544
+ z as getSetting,
545
+ ye as getSettings,
546
+ Ee as getSettingsMeta,
547
+ pe as handleCallback,
548
+ Z as login,
549
+ we as logout,
550
+ ge as refreshToken,
551
+ be as updateSetting,
552
+ Se as updateSettings,
496
553
  F as useAuth,
497
- we as usePrivilege
554
+ Pe as usePrivilege
498
555
  };
@@ -1,6 +1,6 @@
1
- (function(l,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("react"),require("react-router-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom"],h):(l=typeof globalThis<"u"?globalThis:l||self,h(l["alex-evo-sh-auth"]={},l.React,l.ReactRouterDOM))})(this,(function(l,h,L){"use strict";async function D(t){const r=await fetch(`${t.authServer}/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t.clientId})});if(r.status===401)return localStorage.removeItem(t.baseKey+"_access"),null;const o=await r.json();return localStorage.setItem(t.baseKey+"_access",o.access),o.access}class ${constructor(r,o){this.onAuthFail=o,this.config=r}onAuthFail;refreshPromise=null;config;getToken(){return localStorage.getItem(this.config.baseKey+"_access")}setToken(r){r?localStorage.setItem(this.config.baseKey+"_access",r):localStorage.removeItem(this.config.baseKey+"_access")}async getValidToken(){let r=this.getToken();return r||(this.refreshPromise||(this.refreshPromise=D(this.config).then(o=>(this.setToken(o),o)).finally(()=>{this.refreshPromise=null})),r=await this.refreshPromise,!r&&this.onAuthFail&&this.onAuthFail(),r)}}class q{authServer;clientId;redirectUri;homePage;baseKey;constructor(r,o,s,a,c){this.authServer=r,this.clientId=o,this.redirectUri=s,this.homePage=a,this.baseKey=c}}async function j(t,r,o={},s){let a=t.getToken();const c=m=>fetch(r,{...o,headers:{...o.headers,Authorization:m?`Bearer ${m}`:""}});let u=await c(a);return u.status!==401?u:(t.setToken(null),a=await t.getValidToken(),a?c(a):(s?.(),u))}async function J(t){const r=new URLSearchParams(window.location.search),o=r.get("code"),s=r.get("state");if(!o)throw new Error("Missing OAuth code");const a=sessionStorage.getItem("oauth_state");if(!s||s!==a)throw new Error("Invalid OAuth state");const c=sessionStorage.getItem("pkce_verifier");if(!c)throw new Error("Missing PKCE verifier");const u=await fetch(`${t.config.authServer}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId,code:o,code_verifier:c})});if(!u.ok){const E=await u.text();throw new Error(`Token exchange failed: ${u.status} ${E}`)}const m=await u.json();t.setToken(m.access),sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("pkce_verifier")}function ee(t=64){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let o="";const s=new Uint8Array(t);crypto.getRandomValues(s);for(let a=0;a<s.length;a++)o+=r[s[a]%r.length];return o}async function te(t){const o=new TextEncoder().encode(t),s=await crypto.subtle.digest("SHA-256",o);return new Uint8Array(s)}function re(t){return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function T(t){const r=ee(64),o=re(await te(r));sessionStorage.setItem("pkce_verifier",r);const s=crypto.randomUUID();sessionStorage.setItem("oauth_state",s);const a=new URLSearchParams({response_type:"code",client_id:t.config.clientId,redirect_uri:t.config.redirectUri,code_challenge:o,code_challenge_method:"S256",state:s});window.location.href=`${t.config.authServer}/authorize?${a}`}async function x(t){try{await j(t,`${t.config.authServer}/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId})}),localStorage.removeItem(t.config.baseKey+"_access"),await T(t)}catch(r){console.error(r)}}const k=h.createContext({login:()=>{},logout:()=>{},loadMe:()=>{},authManager:null,user:null,loading:!1});var w={exports:{}},p={};var V;function ne(){if(V)return p;V=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function o(s,a,c){var u=null;if(c!==void 0&&(u=""+c),a.key!==void 0&&(u=""+a.key),"key"in a){c={};for(var m in a)m!=="key"&&(c[m]=a[m])}else c=a;return a=c.ref,{$$typeof:t,type:s,key:u,ref:a!==void 0?a:null,props:c}}return p.Fragment=r,p.jsx=o,p.jsxs=o,p}var b={};var W;function oe(){return W||(W=1,process.env.NODE_ENV!=="production"&&(function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Ee?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case C:return"Fragment";case de:return"Profiler";case fe:return"StrictMode";case _e:return"Suspense";case ve:return"SuspenseList";case be:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ue:return"Portal";case me:return e.displayName||"Context";case he:return(e._context.displayName||"Context")+".Consumer";case ge:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case pe:return n=e.displayName||null,n!==null?n:t(e.type)||"Memo";case I:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function r(e){return""+e}function o(e){try{r(e);var n=!1}catch{n=!0}if(n){n=console;var i=n.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return i.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),r(e)}}function s(e){if(e===C)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===I)return"<...>";try{var n=t(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function a(){var e=N.A;return e===null?null:e.getOwner()}function c(){return Error("react-stack-top-frame")}function u(e){if(M.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function m(e,n){function i(){B||(B=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}i.isReactWarning=!0,Object.defineProperty(e,"key",{get:i,configurable:!0})}function E(){var e=t(this.type);return H[e]||(H[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function R(e,n,i,f,O,U){var d=i.ref;return e={$$typeof:K,type:e,key:n,props:i,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:E}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:O}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function y(e,n,i,f,O,U){var d=n.children;if(d!==void 0)if(f)if(ye(d)){for(f=0;f<d.length;f++)g(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else g(d);if(M.call(n,"key")){d=t(e);var v=Object.keys(n).filter(function(Te){return Te!=="key"});f=0<v.length?"{key: someKey, "+v.join(": ..., ")+": ...}":"{key: someKey}",Q[d+f]||(v=0<v.length?"{"+v.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
1
+ (function(i,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react"),require("react-router-dom")):typeof define=="function"&&define.amd?define(["exports","react","react-router-dom"],g):(i=typeof globalThis<"u"?globalThis:i||self,g(i["alex-evo-sh-auth"]={},i.React,i.ReactRouterDOM))})(this,(function(i,g,D){"use strict";async function J(t){const r=await fetch(`${t.authServer}/refresh`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:t.clientId})});if(r.status===401)return localStorage.removeItem(t.baseKey+"_access"),null;if(!r.ok)throw new Error(`Token refresh failed: ${r.status} ${await r.text()}`);const n=await r.json();if(typeof n.access!="string"||!n.access)throw new Error("Token refresh response did not contain an access token");return localStorage.setItem(t.baseKey+"_access",n.access),n.access}class oe{constructor(r,n){this.onAuthFail=n,this.config=r}onAuthFail;refreshPromise=null;config;getToken(){return localStorage.getItem(this.config.baseKey+"_access")}setToken(r){r?localStorage.setItem(this.config.baseKey+"_access",r):localStorage.removeItem(this.config.baseKey+"_access")}async getValidToken(){let r=this.getToken();return r||(this.refreshPromise||(this.refreshPromise=J(this.config).then(n=>(this.setToken(n),n)).finally(()=>{this.refreshPromise=null})),r=await this.refreshPromise,!r&&this.onAuthFail&&this.onAuthFail(),r)}}class se{authServer;clientId;redirectUri;homePage;baseKey;constructor(r,n,o,s,l){this.authServer=r,this.clientId=n,this.redirectUri=o,this.homePage=s,this.baseKey=l}}async function b(t,r,n={},o){let s=t.getToken();const l=h=>fetch(r,{...n,credentials:n.credentials??"include",headers:{...n.headers,Authorization:h?`Bearer ${h}`:""}}),u=await l(s);return u.status!==401?u:(t.setToken(null),s=await t.getValidToken(),s?l(s):(o?.(),u))}async function V(t){const r=new URLSearchParams(window.location.search),n=r.get("code"),o=r.get("state");if(!n)throw new Error("Missing OAuth code");const s=sessionStorage.getItem("oauth_state");if(!o||o!==s)throw new Error("Invalid OAuth state");const l=sessionStorage.getItem("pkce_verifier");if(!l)throw new Error("Missing PKCE verifier");const u=await fetch(`${t.config.authServer}/token`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId,code:n,code_verifier:l})});if(!u.ok){const E=await u.text();throw new Error(`Token exchange failed: ${u.status} ${E}`)}const h=await u.json();if(typeof h.access!="string"||!h.access)throw new Error("Token response did not contain an access token");t.setToken(h.access),sessionStorage.removeItem("oauth_state"),sessionStorage.removeItem("pkce_verifier")}function ae(t=64){const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let n="";const o=new Uint8Array(t);crypto.getRandomValues(o);for(let s=0;s<o.length;s++)n+=r[o[s]%r.length];return n}async function ie(t){const n=new TextEncoder().encode(t),o=await crypto.subtle.digest("SHA-256",n);return new Uint8Array(o)}function ce(t){return btoa(String.fromCharCode(...Array.from(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function C(t){const r=ae(64),n=ce(await ie(r));sessionStorage.setItem("pkce_verifier",r);const o=crypto.randomUUID();sessionStorage.setItem("oauth_state",o);const s=new URLSearchParams({response_type:"code",client_id:t.config.clientId,redirect_uri:t.config.redirectUri,code_challenge:n,code_challenge_method:"S256",state:o});window.location.href=`${t.config.authServer}/authorize?${s}`}async function W(t){try{await b(t,`${t.config.authServer}/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:t.config.clientId})}),localStorage.removeItem(t.config.baseKey+"_access"),await C(t)}catch(r){console.error(r)}}async function S(t,r,n={}){const o=await b(t,`${t.config.authServer}/settings${r}`,n);if(!o.ok){const s=await o.text();throw new Error(`Settings request failed (${o.status}): ${s}`)}return o}async function G(t){return(await S(t,"")).json()}async function x(t,r){return(await(await S(t,`/${encodeURIComponent(r)}`)).json()).value}async function z(t){return(await S(t,"/meta")).json()}async function K(t,r){return(await S(t,"",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({settings:r})})).json()}async function $(t,r,n){return(await S(t,`/${encodeURIComponent(r)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:n})})).json()}function le(t){return{getSettings:()=>G(t),getSetting:r=>x(t,r),getSettingsMeta:()=>z(t),updateSettings:r=>K(t,r),updateSetting:(r,n)=>$(t,r,n),getLanguage:()=>x(t,"language")}}const T=g.createContext({login:()=>{},logout:()=>{},loadMe:async()=>{},authManager:null,user:null,loading:!1});var k={exports:{}},y={};var H;function ue(){if(H)return y;H=1;var t=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function n(o,s,l){var u=null;if(l!==void 0&&(u=""+l),s.key!==void 0&&(u=""+s.key),"key"in s){l={};for(var h in s)h!=="key"&&(l[h]=s[h])}else l=s;return s=l.ref,{$$typeof:t,type:o,key:u,ref:s!==void 0?s:null,props:l}}return y.Fragment=r,y.jsx=n,y.jsxs=n,y}var w={};var X;function fe(){return X||(X=1,process.env.NODE_ENV!=="production"&&(function(){function t(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Pe?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case I:return"Fragment";case Se:return"Profiler";case _e:return"StrictMode";case be:return"Suspense";case Te:return"SuspenseList";case Re:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case ve:return"Portal";case we:return e.displayName||"Context";case ye:return(e._context.displayName||"Context")+".Consumer";case Ee:var a=e.render;return e=e.displayName,e||(e=a.displayName||a.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case ke:return a=e.displayName||null,a!==null?a:t(e.type)||"Memo";case N:a=e._payload,e=e._init;try{return t(e(a))}catch{}}return null}function r(e){return""+e}function n(e){try{r(e);var a=!1}catch{a=!0}if(a){a=console;var c=a.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return c.call(a,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),r(e)}}function o(e){if(e===I)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===N)return"<...>";try{var a=t(e);return a?"<"+a+">":"<...>"}catch{return"<...>"}}function s(){var e=F.A;return e===null?null:e.getOwner()}function l(){return Error("react-stack-top-frame")}function u(e){if(Q.call(e,"key")){var a=Object.getOwnPropertyDescriptor(e,"key").get;if(a&&a.isReactWarning)return!1}return e.key!==void 0}function h(e,a){function c(){q||(q=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",a))}c.isReactWarning=!0,Object.defineProperty(e,"key",{get:c,configurable:!0})}function E(){var e=t(this.type);return ee[e]||(ee[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function P(e,a,c,f,O,Y){var d=c.ref;return e={$$typeof:M,type:e,key:a,props:c,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:E}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:O}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Y}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function p(e,a,c,f,O,Y){var d=a.children;if(d!==void 0)if(f)if(Ae(d)){for(f=0;f<d.length;f++)v(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else v(d);if(Q.call(a,"key")){d=t(e);var _=Object.keys(a).filter(function(je){return je!=="key"});f=0<_.length?"{key: someKey, "+_.join(": ..., ")+": ...}":"{key: someKey}",ne[d+f]||(_=0<_.length?"{"+_.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
2
  let props = %s;
3
3
  <%s {...props} />
4
4
  React keys must be passed directly to JSX without using spread:
5
5
  let props = %s;
6
- <%s key={someKey} {...props} />`,f,d,v,d),Q[d+f]=!0)}if(d=null,i!==void 0&&(o(i),d=""+i),u(n)&&(o(n.key),d=""+n.key),"key"in n){i={};for(var Y in n)Y!=="key"&&(i[Y]=n[Y])}else i=n;return d&&m(i,typeof e=="function"?e.displayName||e.name||"Unknown":e),R(e,d,i,a(),O,U)}function g(e){P(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===I&&(e._payload.status==="fulfilled"?P(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function P(e){return typeof e=="object"&&e!==null&&e.$$typeof===K}var A=h,K=Symbol.for("react.transitional.element"),ue=Symbol.for("react.portal"),C=Symbol.for("react.fragment"),fe=Symbol.for("react.strict_mode"),de=Symbol.for("react.profiler"),he=Symbol.for("react.consumer"),me=Symbol.for("react.context"),ge=Symbol.for("react.forward_ref"),_e=Symbol.for("react.suspense"),ve=Symbol.for("react.suspense_list"),pe=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),be=Symbol.for("react.activity"),Ee=Symbol.for("react.client.reference"),N=A.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,M=Object.prototype.hasOwnProperty,ye=Array.isArray,F=console.createTask?console.createTask:function(){return null};A={react_stack_bottom_frame:function(e){return e()}};var B,H={},X=A.react_stack_bottom_frame.bind(A,c)(),Z=F(s(c)),Q={};b.Fragment=C,b.jsx=function(e,n,i){var f=1e4>N.recentlyCreatedOwnerStacks++;return y(e,n,i,!1,f?Error("react-stack-top-frame"):X,f?F(s(e)):Z)},b.jsxs=function(e,n,i){var f=1e4>N.recentlyCreatedOwnerStacks++;return y(e,n,i,!0,f?Error("react-stack-top-frame"):X,f?F(s(e)):Z)}})()),b}var z;function ae(){return z||(z=1,process.env.NODE_ENV==="production"?w.exports=ne():w.exports=oe()),w.exports}var _=ae();const se=({children:t,authManager:r})=>{const[o,s]=h.useState(null),[a,c]=h.useState(!0),u=h.useCallback(async()=>{c(!0);const R=localStorage.getItem(r.config.baseKey+"_access");if(!R){s(null),c(!1);return}try{const y=await j(r,`${r.config.authServer}/me`,{headers:{Authorization:`Bearer ${R}`}});if(!y.ok)throw new Error("not found");const g=await y.json();s({role:g.role.role_name,userId:g.user_id,userName:g.user_name,privileges:g.role.privileges.map(P=>P.privilege.trim())})}catch{s(null)}c(!1)},[]);h.useEffect(()=>{u()},[u]);const m=h.useCallback(()=>{T(r)},[T,r]),E=h.useCallback(()=>{x(r),s(null)},[x,r]);return _.jsx(k.Provider,{value:{loadMe:u,loading:a,user:o,login:m,authManager:r,logout:E},children:t})},ce=()=>{const{authManager:t,loadMe:r}=h.useContext(k),o=h.useRef(!1);return h.useEffect(()=>{if(!t||o.current)return;o.current=!0,(async()=>{try{await J(t),await r(),window.location.replace(t.config.homePage)}catch(a){console.error("Authentication callback failed:",a),window.location.replace(t.config.homePage)}})()},[t,r]),_.jsx("div",{children:"Авторизация..."})},S=()=>{const t=h.useContext(k);if(!t||!t.authManager)throw new Error("AuthContext not found");return t},G=t=>{const{user:r}=S();return!!r?.privileges?.includes(t)};function ie({privilege:t,invalidPage:r,loadingPage:o}){const{loading:s}=S(),a=G(t);return s?o:a?_.jsx(L.Outlet,{}):r}function le({loadingPage:t}){const{authManager:r,login:o,user:s}=S(),[a,c]=h.useState(!0);return h.useEffect(()=>{if(!r)return;r.getToken()?c(!1):o()},[r,s]),r?a?t??_.jsx("div",{children:"Loading..."}):_.jsx(L.Outlet,{}):_.jsx("p",{children:"invalud config"})}l.AuthContext=k,l.AuthManager=$,l.AuthProvider=se,l.CallbackPage=ce,l.Config=q,l.PrivilegeGate=ie,l.ProtectGate=le,l.apiFetch=j,l.handleCallback=J,l.login=T,l.logout=x,l.refreshToken=D,l.useAuth=S,l.usePrivilege=G,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
6
+ <%s key={someKey} {...props} />`,f,d,_,d),ne[d+f]=!0)}if(d=null,c!==void 0&&(n(c),d=""+c),u(a)&&(n(a.key),d=""+a.key),"key"in a){c={};for(var L in a)L!=="key"&&(c[L]=a[L])}else c=a;return d&&h(c,typeof e=="function"?e.displayName||e.name||"Unknown":e),P(e,d,c,s(),O,Y)}function v(e){A(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===N&&(e._payload.status==="fulfilled"?A(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function A(e){return typeof e=="object"&&e!==null&&e.$$typeof===M}var j=g,M=Symbol.for("react.transitional.element"),ve=Symbol.for("react.portal"),I=Symbol.for("react.fragment"),_e=Symbol.for("react.strict_mode"),Se=Symbol.for("react.profiler"),ye=Symbol.for("react.consumer"),we=Symbol.for("react.context"),Ee=Symbol.for("react.forward_ref"),be=Symbol.for("react.suspense"),Te=Symbol.for("react.suspense_list"),ke=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),Re=Symbol.for("react.activity"),Pe=Symbol.for("react.client.reference"),F=j.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,Q=Object.prototype.hasOwnProperty,Ae=Array.isArray,U=console.createTask?console.createTask:function(){return null};j={react_stack_bottom_frame:function(e){return e()}};var q,ee={},te=j.react_stack_bottom_frame.bind(j,l)(),re=U(o(l)),ne={};w.Fragment=I,w.jsx=function(e,a,c){var f=1e4>F.recentlyCreatedOwnerStacks++;return p(e,a,c,!1,f?Error("react-stack-top-frame"):te,f?U(o(e)):re)},w.jsxs=function(e,a,c){var f=1e4>F.recentlyCreatedOwnerStacks++;return p(e,a,c,!0,f?Error("react-stack-top-frame"):te,f?U(o(e)):re)}})()),w}var B;function de(){return B||(B=1,process.env.NODE_ENV==="production"?k.exports=ue():k.exports=fe()),k.exports}var m=de();const ge=({children:t,authManager:r})=>{const[n,o]=g.useState(null),[s,l]=g.useState(!0),u=g.useCallback(async()=>{try{if(!await r.getValidToken()){o(null);return}const p=await b(r,`${r.config.authServer}/me`);if(p.status===401){r.setToken(null),o(null);return}if(!p.ok)throw new Error(`Failed to load current user: ${p.status}`);const v=await p.json();o({role:v.role.role_name,userId:v.user_id,userName:v.user_name,privileges:v.role.privileges.map(A=>A.privilege.trim())})}catch(P){console.error("Failed to load current user:",P),o(null)}finally{l(!1)}},[r]);g.useEffect(()=>{Promise.resolve().then(u)},[u]);const h=g.useCallback(()=>{C(r)},[r]),E=g.useCallback(()=>{W(r),o(null)},[r]);return m.jsx(T.Provider,{value:{loadMe:u,loading:s,user:n,login:h,authManager:r,logout:E},children:t})},he=()=>{const{authManager:t,login:r}=g.useContext(T),n=g.useRef(!1),[o,s]=g.useState(null);return g.useEffect(()=>{if(!t||n.current)return;n.current=!0,(async()=>{try{await V(t),window.location.replace(t.config.homePage)}catch(u){console.error("Authentication callback failed:",u),s("Не удалось завершить вход. Попробуйте снова.")}})()},[t]),o?m.jsxs("div",{role:"alert",children:[m.jsxs("p",{children:["Не удалось завершить вход: ",o]}),m.jsx("button",{type:"button",onClick:r,children:"Повторить вход"})]}):m.jsx("div",{children:"Авторизация..."})},R=()=>{const t=g.useContext(T);if(!t||!t.authManager)throw new Error("AuthContext not found");return t},Z=t=>{const{user:r}=R();return!!r?.privileges?.includes(t)};function me({privilege:t,invalidPage:r,loadingPage:n}){const{loading:o}=R(),s=Z(t);return o?n:s?m.jsx(D.Outlet,{}):r}function pe({loadingPage:t}){const{authManager:r,login:n,loading:o}=R(),s=r?.getToken()??null;return g.useEffect(()=>{r&&!o&&!s&&n()},[r,o,n,s]),o||!s?t??m.jsx("div",{children:"Loading..."}):m.jsx(D.Outlet,{})}i.AuthContext=T,i.AuthManager=oe,i.AuthProvider=ge,i.CallbackPage=he,i.Config=se,i.PrivilegeGate=me,i.ProtectGate=pe,i.apiFetch=b,i.createSettingsApi=le,i.getSetting=x,i.getSettings=G,i.getSettingsMeta=z,i.handleCallback=V,i.login=C,i.logout=W,i.refreshToken=J,i.updateSetting=$,i.updateSettings=K,i.useAuth=R,i.usePrivilege=Z,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
package/dist/index.d.ts CHANGED
@@ -4,6 +4,8 @@ export { apiFetch } from './lib/helpers/fatch';
4
4
  export { handleCallback } from './lib/helpers/handleCallback';
5
5
  export { login, logout } from './lib/helpers/login';
6
6
  export { refreshToken } from './lib/helpers/refresh';
7
+ export { getSettings, getSetting, getSettingsMeta, updateSettings, updateSetting, createSettingsApi } from './lib/helpers/settings';
8
+ export type { UserSettings, SettingsPatch, SettingsValue, SettingMeta, SettingsMeta } from './lib/types';
7
9
  export { AuthContext } from './lib/react/AuthContext';
8
10
  export { AuthProvider } from './lib/react/AuthProvider';
9
11
  export { CallbackPage } from './lib/react/CallBackPage';
@@ -1,2 +1,2 @@
1
1
  import { Config } from './config';
2
- export declare function refreshToken(authConfig: Config): Promise<any>;
2
+ export declare function refreshToken(authConfig: Config): Promise<string | null>;
@@ -0,0 +1,24 @@
1
+ import { AuthManager } from './authManager';
2
+ import { UserSettings, SettingsPatch, SettingsMeta } from '../types';
3
+ export declare function getSettings(authManager: AuthManager): Promise<UserSettings>;
4
+ export declare function getSetting(authManager: AuthManager, key: string): Promise<string>;
5
+ export declare function getSettingsMeta(authManager: AuthManager): Promise<SettingsMeta>;
6
+ export declare function updateSettings(authManager: AuthManager, patch: SettingsPatch): Promise<UserSettings>;
7
+ export declare function updateSetting(authManager: AuthManager, key: string, value: string): Promise<UserSettings>;
8
+ /**
9
+ * Фабрика клиентского API настроек. Позволяет другим сервисам работать
10
+ * с настройками в стиле:
11
+ *
12
+ * const settingsApi = createSettingsApi(authManager);
13
+ * const language = await settingsApi.getSetting("language");
14
+ * await settingsApi.updateSettings({ language: "en" });
15
+ */
16
+ export declare function createSettingsApi(authManager: AuthManager): {
17
+ getSettings: () => Promise<UserSettings>;
18
+ getSetting: (key: string) => Promise<string>;
19
+ getSettingsMeta: () => Promise<SettingsMeta>;
20
+ updateSettings: (patch: SettingsPatch) => Promise<UserSettings>;
21
+ updateSetting: (key: string, value: string) => Promise<UserSettings>;
22
+ /** Удобный способ получить текущий язык интерфейса. */
23
+ getLanguage: () => Promise<string>;
24
+ };
@@ -3,7 +3,7 @@ import { AuthData } from '../types';
3
3
  type IAuthContext = {
4
4
  login: () => void;
5
5
  logout: () => void;
6
- loadMe: () => void;
6
+ loadMe: () => Promise<void>;
7
7
  authManager: AuthManager | null;
8
8
  user: AuthData | null;
9
9
  loading: boolean;
@@ -1,6 +1,5 @@
1
- import { default as React } from 'react';
2
1
  export declare function PrivilegeGate({ privilege, invalidPage, loadingPage }: {
3
2
  privilege: string;
4
3
  invalidPage: React.ReactNode;
5
4
  loadingPage: React.ReactNode;
6
- }): string | number | bigint | boolean | Iterable<React.ReactNode> | Promise<string | number | bigint | boolean | React.ReactPortal | React.ReactElement<unknown, string | React.JSXElementConstructor<any>> | Iterable<React.ReactNode> | null | undefined> | React.JSX.Element | null | undefined;
5
+ }): string | number | bigint | boolean | Iterable<import('react').ReactNode> | Promise<string | number | bigint | boolean | import('react').ReactPortal | import('react').ReactElement<unknown, string | import('react').JSXElementConstructor<any>> | Iterable<import('react').ReactNode> | null | undefined> | import("react").JSX.Element | null | undefined;
@@ -1,7 +1,7 @@
1
1
  export declare const useAuth: () => {
2
2
  login: () => void;
3
3
  logout: () => void;
4
- loadMe: () => void;
4
+ loadMe: () => Promise<void>;
5
5
  authManager: import('../..').AuthManager | null;
6
6
  user: import('../types').AuthData | null;
7
7
  loading: boolean;
@@ -18,3 +18,23 @@ export type AuthData = {
18
18
  role: string;
19
19
  privileges: string[];
20
20
  };
21
+ export type SettingsValue = string;
22
+ /**
23
+ * Набор пользовательских настроек, возвращаемый AuthService.
24
+ * Известные ключи типизированы (language), новые настройки добавляются
25
+ * на стороне сервера и доступны по произвольному ключу.
26
+ */
27
+ export interface UserSettings {
28
+ language?: SettingsValue;
29
+ [key: string]: SettingsValue | undefined;
30
+ }
31
+ export type SettingKey = keyof UserSettings;
32
+ export type SettingsPatch = Record<string, SettingsValue>;
33
+ export interface SettingMeta {
34
+ key: string;
35
+ default: SettingsValue;
36
+ allowed_values?: SettingsValue[] | null;
37
+ }
38
+ export interface SettingsMeta {
39
+ settings: SettingMeta[];
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alex-evo-sh-auth",
3
- "version": "0.0.17",
3
+ "version": "0.0.22",
4
4
  "type": "module",
5
5
  "main": "./dist/alex-evo-sh-auth.umd.js",
6
6
  "module": "./dist/alex-evo-sh-auth.es.js",