@o/better-auth-utils 0.16.19

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -0
  3. package/dist/cjs/createAuthClient.cjs +251 -0
  4. package/dist/cjs/createAuthClient.native.js +279 -0
  5. package/dist/cjs/createAuthClient.native.js.map +1 -0
  6. package/dist/cjs/createAuthClient.test.cjs +88 -0
  7. package/dist/cjs/createAuthClient.test.native.js +105 -0
  8. package/dist/cjs/createAuthClient.test.native.js.map +1 -0
  9. package/dist/cjs/index.cjs +20 -0
  10. package/dist/cjs/index.native.js +23 -0
  11. package/dist/cjs/index.native.js.map +1 -0
  12. package/dist/cjs/server.cjs +106 -0
  13. package/dist/cjs/server.native.js +228 -0
  14. package/dist/cjs/server.native.js.map +1 -0
  15. package/dist/esm/createAuthClient.mjs +226 -0
  16. package/dist/esm/createAuthClient.mjs.map +1 -0
  17. package/dist/esm/createAuthClient.native.js +251 -0
  18. package/dist/esm/createAuthClient.native.js.map +1 -0
  19. package/dist/esm/createAuthClient.test.mjs +89 -0
  20. package/dist/esm/createAuthClient.test.mjs.map +1 -0
  21. package/dist/esm/createAuthClient.test.native.js +103 -0
  22. package/dist/esm/createAuthClient.test.native.js.map +1 -0
  23. package/dist/esm/index.js +2 -0
  24. package/dist/esm/index.js.map +1 -0
  25. package/dist/esm/index.mjs +2 -0
  26. package/dist/esm/index.mjs.map +1 -0
  27. package/dist/esm/index.native.js +2 -0
  28. package/dist/esm/index.native.js.map +1 -0
  29. package/dist/esm/server.mjs +77 -0
  30. package/dist/esm/server.mjs.map +1 -0
  31. package/dist/esm/server.native.js +196 -0
  32. package/dist/esm/server.native.js.map +1 -0
  33. package/package.json +66 -0
  34. package/src/createAuthClient.test.ts +86 -0
  35. package/src/createAuthClient.ts +373 -0
  36. package/src/index.ts +1 -0
  37. package/src/server.ts +150 -0
@@ -0,0 +1,88 @@
1
+ var import_vitest = require("vitest");
2
+ var import_createAuthClient = require("./createAuthClient.cjs");
3
+ const mocks = import_vitest.vi.hoisted(() => ({
4
+ createAuthClient: import_vitest.vi.fn(),
5
+ request: import_vitest.vi.fn()
6
+ }));
7
+ import_vitest.vi.mock("better-auth/client", () => ({
8
+ createAuthClient: mocks.createAuthClient
9
+ }));
10
+ import_vitest.vi.mock("@o/helpers", () => ({
11
+ createEmitter: (_name, initialValue) => {
12
+ const emitter = {
13
+ value: initialValue,
14
+ emit(value) {
15
+ emitter.value = value;
16
+ }
17
+ };
18
+ return emitter;
19
+ },
20
+ createStorageValue: () => ({
21
+ get: () => void 0,
22
+ set: import_vitest.vi.fn(),
23
+ remove: import_vitest.vi.fn()
24
+ }),
25
+ isEqualDeepLite: Object.is,
26
+ useEmitterValue: emitter => emitter.value
27
+ }));
28
+ (0, import_vitest.describe)("createBetterAuthClient signOut", () => {
29
+ (0, import_vitest.beforeEach)(() => {
30
+ mocks.request.mockReset();
31
+ mocks.createAuthClient.mockReset();
32
+ mocks.createAuthClient.mockReturnValue({
33
+ $fetch: mocks.request,
34
+ useSession: {
35
+ subscribe: import_vitest.vi.fn(() => import_vitest.vi.fn())
36
+ }
37
+ });
38
+ });
39
+ (0, import_vitest.test)("sends JSON and clears local auth only after server revocation succeeds", async () => {
40
+ const deferred = Promise.withResolvers();
41
+ mocks.request.mockReturnValue(deferred.promise);
42
+ const onAuthStateChange = import_vitest.vi.fn();
43
+ const client = (0, import_createAuthClient.createBetterAuthClient)({
44
+ baseURL: "https://auth.example.com",
45
+ onAuthStateChange
46
+ });
47
+ const pending = client.authClient.signOut();
48
+ (0, import_vitest.expect)(mocks.request).toHaveBeenCalledWith("/sign-out", {
49
+ method: "POST",
50
+ body: {}
51
+ });
52
+ (0, import_vitest.expect)(onAuthStateChange).not.toHaveBeenCalled();
53
+ deferred.resolve({
54
+ data: {
55
+ success: true
56
+ },
57
+ error: null
58
+ });
59
+ await (0, import_vitest.expect)(pending).resolves.toEqual({
60
+ data: {
61
+ success: true
62
+ },
63
+ error: null
64
+ });
65
+ (0, import_vitest.expect)(onAuthStateChange).toHaveBeenCalledWith({
66
+ state: "logged-out",
67
+ session: null,
68
+ user: null,
69
+ token: null
70
+ });
71
+ });
72
+ (0, import_vitest.test)("keeps local auth when server revocation fails", async () => {
73
+ const error = {
74
+ message: "network unavailable"
75
+ };
76
+ mocks.request.mockResolvedValue({
77
+ data: null,
78
+ error
79
+ });
80
+ const onAuthStateChange = import_vitest.vi.fn();
81
+ const client = (0, import_createAuthClient.createBetterAuthClient)({
82
+ baseURL: "https://auth.example.com",
83
+ onAuthStateChange
84
+ });
85
+ await (0, import_vitest.expect)(client.authClient.signOut()).rejects.toBe(error);
86
+ (0, import_vitest.expect)(onAuthStateChange).not.toHaveBeenCalled();
87
+ });
88
+ });
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+
3
+ var import_vitest = require("vitest");
4
+ var import_createAuthClient = require("./createAuthClient.native.js");
5
+ var mocks = import_vitest.vi.hoisted(function () {
6
+ return {
7
+ createAuthClient: import_vitest.vi.fn(),
8
+ request: import_vitest.vi.fn()
9
+ };
10
+ });
11
+ import_vitest.vi.mock("better-auth/client", function () {
12
+ return {
13
+ createAuthClient: mocks.createAuthClient
14
+ };
15
+ });
16
+ import_vitest.vi.mock("@o/helpers", function () {
17
+ return {
18
+ createEmitter: function createEmitter(_name, initialValue) {
19
+ var emitter = {
20
+ value: initialValue,
21
+ emit(value) {
22
+ emitter.value = value;
23
+ }
24
+ };
25
+ return emitter;
26
+ },
27
+ createStorageValue: function createStorageValue() {
28
+ return {
29
+ get: function get() {
30
+ return void 0;
31
+ },
32
+ set: import_vitest.vi.fn(),
33
+ remove: import_vitest.vi.fn()
34
+ };
35
+ },
36
+ isEqualDeepLite: Object.is,
37
+ useEmitterValue: function useEmitterValue(emitter) {
38
+ return emitter.value;
39
+ }
40
+ };
41
+ });
42
+ (0, import_vitest.describe)("createBetterAuthClient signOut", function () {
43
+ (0, import_vitest.beforeEach)(function () {
44
+ mocks.request.mockReset();
45
+ mocks.createAuthClient.mockReset();
46
+ mocks.createAuthClient.mockReturnValue({
47
+ $fetch: mocks.request,
48
+ useSession: {
49
+ subscribe: import_vitest.vi.fn(function () {
50
+ return import_vitest.vi.fn();
51
+ })
52
+ }
53
+ });
54
+ });
55
+ (0, import_vitest.test)("sends JSON and clears local auth only after server revocation succeeds", async function () {
56
+ var deferred = Promise.withResolvers();
57
+ mocks.request.mockReturnValue(deferred.promise);
58
+ var onAuthStateChange = import_vitest.vi.fn();
59
+ var client = (0, import_createAuthClient.createBetterAuthClient)({
60
+ baseURL: "https://auth.example.com",
61
+ onAuthStateChange
62
+ });
63
+ var pending = client.authClient.signOut();
64
+ (0, import_vitest.expect)(mocks.request).toHaveBeenCalledWith("/sign-out", {
65
+ method: "POST",
66
+ body: {}
67
+ });
68
+ (0, import_vitest.expect)(onAuthStateChange).not.toHaveBeenCalled();
69
+ deferred.resolve({
70
+ data: {
71
+ success: true
72
+ },
73
+ error: null
74
+ });
75
+ await (0, import_vitest.expect)(pending).resolves.toEqual({
76
+ data: {
77
+ success: true
78
+ },
79
+ error: null
80
+ });
81
+ (0, import_vitest.expect)(onAuthStateChange).toHaveBeenCalledWith({
82
+ state: "logged-out",
83
+ session: null,
84
+ user: null,
85
+ token: null
86
+ });
87
+ });
88
+ (0, import_vitest.test)("keeps local auth when server revocation fails", async function () {
89
+ var error = {
90
+ message: "network unavailable"
91
+ };
92
+ mocks.request.mockResolvedValue({
93
+ data: null,
94
+ error
95
+ });
96
+ var onAuthStateChange = import_vitest.vi.fn();
97
+ var client = (0, import_createAuthClient.createBetterAuthClient)({
98
+ baseURL: "https://auth.example.com",
99
+ onAuthStateChange
100
+ });
101
+ await (0, import_vitest.expect)(client.authClient.signOut()).rejects.toBe(error);
102
+ (0, import_vitest.expect)(onAuthStateChange).not.toHaveBeenCalled();
103
+ });
104
+ });
105
+ //# sourceMappingURL=createAuthClient.test.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["import_vitest","require","import_createAuthClient","mocks","vi","hoisted","createAuthClient","fn","request","mock","createEmitter","_name","initialValue","emitter","value","emit","createStorageValue","get","set","remove","isEqualDeepLite","Object","is","useEmitterValue","describe","beforeEach","mockReset","mockReturnValue","$fetch","useSession","subscribe","test","deferred","Promise","withResolvers","promise","onAuthStateChange","client","createBetterAuthClient","baseURL","pending","authClient","signOut","expect","toHaveBeenCalledWith","method","body","not","toHaveBeenCalled","resolve","data","success","error"],"sources":["../../src/createAuthClient.test.ts"],"sourcesContent":[null],"mappings":"AAAA;;AA8BA,IAAAA,aAAA,GAAAC,OAAA,SAAuC;AA5BvC,IAAAC,uBAAc,GAAAD,OAAG,+BAAe;AAAA,IAC9BE,KAAA,GAAAH,aAAkB,CAAAI,EAAA,CAAAC,OAAA,CAAG,YAAG;EACxB;IACAC,gBAAA,EAAAN,aAAA,CAAAI,EAAA,CAAAG,EAAA;IAEFC,OAAA,EAAAR,aAAQ,CAAAI,EAAA,CAAAG,EAAA;EACN;AACF,EAAE;AAEFP,aAAA,CAAAI,EAAA,CAAGK,IAAA,CAAK,oBAAc,EAAO;EAC3B;IACEH,gBAAgB,EAAAH,KAAA,CAAAG;EAAA;AACP;AAELN,aAAA,CAAAI,EAAQ,CAAAK,IAAA,aAAQ;EAAA,OAClB;IACFC,aAAA,WAAAA,cAAAC,KAAA,EAAAC,YAAA;MACA,IAAAC,OAAO;QACTC,KAAA,EAAAF,YAAA;QACAG,KAAAD,KAAA;UACOD,OAAM,CAAAC,KAAA,GAAAA,KAAA;QACX;MACA;MACF,OAAAD,OAAA;IACA;IACAG,kBAAkB,WAAgCA,kBAAQA,CAAA;MAC1D;QAIFC,GAAA,WAAAA,IAAA,EAAS;UACP;QACE;QACAC,GAAM,EAAAlB,aAAA,CAAiBI,EAAA,CAAAG,EAAA;QACvBY,MAAM,EAAAnB,aAAiB,CAAAI,EAAA,CAAAG,EAAA;MACrB;IAAc;IACFa,eACC,EAAAC,MAAA,CAAAC,EAAA;IAAmBC,eAChC,WAAAA,gBAAAV,OAAA;MACD,OAAAA,OAAA,CAAAC,KAAA;IACF;EAED;AACE;AAIA,IAAAd,aAAM,CAAQwB,QAAA,kCAAgC;EAC9C,IAAAxB,aAAM,CAAAyB,UAAoB;IAC1BtB,KAAA,CAAMK,OAAA,CAAAkB,SAAS;IAAuBvB,KACpC,CAAAG,gBAAS,CAAAoB,SAAA;IAAAvB,KACT,CAAAG,gBAAA,CAAAqB,eAAA;MACDC,MAAA,EAAAzB,KAAA,CAAAK,OAAA;MAEDqB,UAAM;QACNC,SAAA,EAAA9B,aAAO,CAAAI,EAAA,CAAMG,EAAA,aAAS;UACpB,OAAQP,aAAA,CAAAI,EAAA,CAAAG,EAAA;QACR;MACD;IACD;EAEA;EACA,IAAAP,aAAM,CAAA+B,IAAA,0EAAmE,oBAAM;IAC/E,IAAAC,QAAA,GAAAC,OAAA,CAAAC,aAAO;IAAwC/B,KAC7C,CAAAK,OAAO,CAAAmB,eAAA,CAAAK,QAAA,CAAAG,OAAA;IAAA,IACPC,iBAAS,GAAApC,aAAA,CAAAI,EAAA,CAAAG,EAAA;IAAA,IACT8B,MAAM,OAAAnC,uBAAA,CAAAoC,sBAAA;MACNC,OAAO;MACRH;IACF;IAED,IAAAI,OAAA,GAAAH,MAAA,CAAAI,UAAK,CAAAC,OAAA;IACH,IAAA1C,aAAgB,CAAA2C,MAAA,EAASxC,KAAA,CAAAK,OAAA,EAAAoC,oBAAsB;MAC/CC,MAAM,QAAQ;MACdC,IAAM;IACN;IAAsC,EACpC,EAAA9C,aAAS,CAAA2C,MAAA,EAAAP,iBAAA,EAAAW,GAAA,CAAAC,gBAAA;IAAAhB,QACT,CAAAiB,OAAA;MACDC,IAAA;QAEDC,OAAM;MACN;MACDC,KAAA;IACF","ignoreList":[]}
@@ -0,0 +1,20 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
8
+ get: () => from[key],
9
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
10
+ });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
16
+ value: true
17
+ }), mod);
18
+ var index_exports = {};
19
+ module.exports = __toCommonJS(index_exports);
20
+ __reExport(index_exports, require("./createAuthClient.cjs"), module.exports);
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __copyProps = (to, from, except, desc) => {
8
+ if (from && typeof from === "object" || typeof from === "function") {
9
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
10
+ get: () => from[key],
11
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
12
+ });
13
+ }
14
+ return to;
15
+ };
16
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
17
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
18
+ value: true
19
+ }), mod);
20
+ var index_exports = {};
21
+ module.exports = __toCommonJS(index_exports);
22
+ __reExport(index_exports, require("./createAuthClient.native.js"), module.exports);
23
+ //# sourceMappingURL=index.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["__toCommonJS","mod","__copyProps","__defProp","value","index_exports","module","exports"],"sources":["../../src/index.ts"],"sourcesContent":[null],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,GAAA,IAAAC,WAAA,CAAAC,SAAA;EAAAC,KAAA;AAAA,IAAAH,GAAA;AAAA,IAAAI,aAAA;AAAAC,MAAA,CAAAC,OAAA,GAAAP,YAAc,CAAAK,aAAA","ignoreList":[]}
@@ -0,0 +1,106 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: () => from[key],
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
21
+ value: true
22
+ }), mod);
23
+ var server_exports = {};
24
+ __export(server_exports, {
25
+ InvalidTokenError: () => InvalidTokenError,
26
+ NotAuthenticatedError: () => NotAuthenticatedError,
27
+ getAuthDataFromRequest: () => getAuthDataFromRequest,
28
+ isValidJWT: () => isValidJWT,
29
+ validateToken: () => validateToken
30
+ });
31
+ module.exports = __toCommonJS(server_exports);
32
+ var import_jose = require("jose");
33
+ class NotAuthenticatedError extends Error {}
34
+ class InvalidTokenError extends Error {}
35
+ async function getAuthDataFromRequest(authServer, req, tokenOptions) {
36
+ const authHeader = req.headers.get("authorization");
37
+ try {
38
+ const session = await authServer.api.getSession({
39
+ headers: req.headers
40
+ });
41
+ if (session?.user) {
42
+ return {
43
+ id: session.user.id,
44
+ email: session.user.email || void 0,
45
+ role: session.user.role === "admin" ? "admin" : void 0
46
+ };
47
+ }
48
+ } catch (err) {
49
+ console.warn(`Error validating session`, err);
50
+ }
51
+ const jwtToken = authHeader?.replace("Bearer ", "");
52
+ if (jwtToken) {
53
+ try {
54
+ const payload = await validateToken(jwtToken, tokenOptions);
55
+ const userId = payload?.id || payload?.sub;
56
+ if (userId) {
57
+ return {
58
+ id: userId,
59
+ email: payload.email,
60
+ role: payload.role === "admin" ? "admin" : void 0
61
+ };
62
+ }
63
+ } catch (err) {
64
+ if (!(err instanceof InvalidTokenError)) {
65
+ throw err;
66
+ }
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+ async function validateToken(token, options) {
72
+ const {
73
+ baseUrl = process.env.ONE_SERVER_URL,
74
+ forceIssuer = process.env.FORCE_ISSUER || "",
75
+ jwksPath = "/api/auth/jwks"
76
+ } = options || {};
77
+ if (!baseUrl) {
78
+ throw new Error(`No baseURL!`);
79
+ }
80
+ const normalizedBaseUrl = removeTrailingSlash(baseUrl);
81
+ const url = `${forceIssuer || normalizedBaseUrl}${jwksPath}`;
82
+ const JWKS = (0, import_jose.createRemoteJWKSet)(new URL(url));
83
+ try {
84
+ const verifyOptions = forceIssuer ? {} : {
85
+ issuer: normalizedBaseUrl,
86
+ audience: normalizedBaseUrl
87
+ };
88
+ const {
89
+ payload
90
+ } = await (0, import_jose.jwtVerify)(token, JWKS, verifyOptions);
91
+ return payload;
92
+ } catch (error) {
93
+ throw new InvalidTokenError(`${error}`);
94
+ }
95
+ }
96
+ async function isValidJWT(token, options) {
97
+ try {
98
+ await validateToken(token, options);
99
+ return true;
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
104
+ function removeTrailingSlash(str) {
105
+ return str.replace(/\/$/, "");
106
+ }
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: () => from[key],
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
23
+ value: true
24
+ }), mod);
25
+ var server_exports = {};
26
+ __export(server_exports, {
27
+ InvalidTokenError: () => InvalidTokenError,
28
+ NotAuthenticatedError: () => NotAuthenticatedError,
29
+ getAuthDataFromRequest: () => getAuthDataFromRequest,
30
+ isValidJWT: () => isValidJWT,
31
+ validateToken: () => validateToken
32
+ });
33
+ module.exports = __toCommonJS(server_exports);
34
+ var import_jose = require("jose");
35
+ function _assert_this_initialized(self) {
36
+ if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
37
+ return self;
38
+ }
39
+ function _call_super(_this, derived, args) {
40
+ derived = _get_prototype_of(derived);
41
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
42
+ }
43
+ function _class_call_check(instance, Constructor) {
44
+ if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
45
+ }
46
+ function _construct(Parent, args, Class) {
47
+ if (_is_native_reflect_construct()) _construct = Reflect.construct;else {
48
+ _construct = function construct(Parent2, args2, Class2) {
49
+ var a = [null];
50
+ a.push.apply(a, args2);
51
+ var Constructor = Function.bind.apply(Parent2, a);
52
+ var instance = new Constructor();
53
+ if (Class2) _set_prototype_of(instance, Class2.prototype);
54
+ return instance;
55
+ };
56
+ }
57
+ return _construct.apply(null, arguments);
58
+ }
59
+ function _get_prototype_of(o) {
60
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o2) {
61
+ return o2.__proto__ || Object.getPrototypeOf(o2);
62
+ };
63
+ return _get_prototype_of(o);
64
+ }
65
+ function _inherits(subClass, superClass) {
66
+ if (typeof superClass !== "function" && superClass !== null) {
67
+ throw new TypeError("Super expression must either be null or a function");
68
+ }
69
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
70
+ constructor: {
71
+ value: subClass,
72
+ writable: true,
73
+ configurable: true
74
+ }
75
+ });
76
+ if (superClass) _set_prototype_of(subClass, superClass);
77
+ }
78
+ function _instanceof(left, right) {
79
+ "@swc/helpers - instanceof";
80
+
81
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
82
+ return !!right[Symbol.hasInstance](left);
83
+ } else return left instanceof right;
84
+ }
85
+ function _is_native_function(fn) {
86
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
87
+ }
88
+ function _is_native_reflect_construct() {
89
+ try {
90
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
91
+ } catch (_) {}
92
+ return (_is_native_reflect_construct = function () {
93
+ return !!result;
94
+ })();
95
+ }
96
+ function _possible_constructor_return(self, call) {
97
+ if (call && (_type_of(call) === "object" || typeof call === "function")) return call;
98
+ return _assert_this_initialized(self);
99
+ }
100
+ function _set_prototype_of(o, p) {
101
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o2, p2) {
102
+ o2.__proto__ = p2;
103
+ return o2;
104
+ };
105
+ return _set_prototype_of(o, p);
106
+ }
107
+ function _type_of(obj) {
108
+ "@swc/helpers - typeof";
109
+
110
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
111
+ }
112
+ function _wrap_native_super(Class) {
113
+ var _cache = typeof Map === "function" ? /* @__PURE__ */new Map() : void 0;
114
+ _wrap_native_super = function (Class2) {
115
+ if (Class2 === null || !_is_native_function(Class2)) return Class2;
116
+ if (typeof Class2 !== "function") throw new TypeError("Super expression must either be null or a function");
117
+ if (typeof _cache !== "undefined") {
118
+ if (_cache.has(Class2)) return _cache.get(Class2);
119
+ _cache.set(Class2, Wrapper);
120
+ }
121
+ function Wrapper() {
122
+ return _construct(Class2, arguments, _get_prototype_of(this).constructor);
123
+ }
124
+ Wrapper.prototype = Object.create(Class2.prototype, {
125
+ constructor: {
126
+ value: Wrapper,
127
+ enumerable: false,
128
+ writable: true,
129
+ configurable: true
130
+ }
131
+ });
132
+ return _set_prototype_of(Wrapper, Class2);
133
+ };
134
+ return _wrap_native_super(Class);
135
+ }
136
+ var NotAuthenticatedError = /* @__PURE__ */function (Error1) {
137
+ "use strict";
138
+
139
+ _inherits(NotAuthenticatedError2, Error1);
140
+ function NotAuthenticatedError2() {
141
+ _class_call_check(this, NotAuthenticatedError2);
142
+ return _call_super(this, NotAuthenticatedError2, arguments);
143
+ }
144
+ return NotAuthenticatedError2;
145
+ }(_wrap_native_super(Error));
146
+ var InvalidTokenError = /* @__PURE__ */function (Error1) {
147
+ "use strict";
148
+
149
+ _inherits(InvalidTokenError2, Error1);
150
+ function InvalidTokenError2() {
151
+ _class_call_check(this, InvalidTokenError2);
152
+ return _call_super(this, InvalidTokenError2, arguments);
153
+ }
154
+ return InvalidTokenError2;
155
+ }(_wrap_native_super(Error));
156
+ async function getAuthDataFromRequest(authServer, req, tokenOptions) {
157
+ var authHeader = req.headers.get("authorization");
158
+ try {
159
+ var session = await authServer.api.getSession({
160
+ headers: req.headers
161
+ });
162
+ if (session === null || session === void 0 ? void 0 : session.user) {
163
+ return {
164
+ id: session.user.id,
165
+ email: session.user.email || void 0,
166
+ role: session.user.role === "admin" ? "admin" : void 0
167
+ };
168
+ }
169
+ } catch (err) {
170
+ console.warn(`Error validating session`, err);
171
+ }
172
+ var jwtToken = authHeader === null || authHeader === void 0 ? void 0 : authHeader.replace("Bearer ", "");
173
+ if (jwtToken) {
174
+ try {
175
+ var payload = await validateToken(jwtToken, tokenOptions);
176
+ var userId = (payload === null || payload === void 0 ? void 0 : payload.id) || (payload === null || payload === void 0 ? void 0 : payload.sub);
177
+ if (userId) {
178
+ return {
179
+ id: userId,
180
+ email: payload.email,
181
+ role: payload.role === "admin" ? "admin" : void 0
182
+ };
183
+ }
184
+ } catch (err) {
185
+ if (!_instanceof(err, InvalidTokenError)) {
186
+ throw err;
187
+ }
188
+ }
189
+ }
190
+ return null;
191
+ }
192
+ async function validateToken(token, options) {
193
+ var {
194
+ baseUrl = process.env.ONE_SERVER_URL,
195
+ forceIssuer = process.env.FORCE_ISSUER || "",
196
+ jwksPath = "/api/auth/jwks"
197
+ } = options || {};
198
+ if (!baseUrl) {
199
+ throw new Error(`No baseURL!`);
200
+ }
201
+ var normalizedBaseUrl = removeTrailingSlash(baseUrl);
202
+ var url = `${forceIssuer || normalizedBaseUrl}${jwksPath}`;
203
+ var JWKS = (0, import_jose.createRemoteJWKSet)(new URL(url));
204
+ try {
205
+ var verifyOptions = forceIssuer ? {} : {
206
+ issuer: normalizedBaseUrl,
207
+ audience: normalizedBaseUrl
208
+ };
209
+ var {
210
+ payload
211
+ } = await (0, import_jose.jwtVerify)(token, JWKS, verifyOptions);
212
+ return payload;
213
+ } catch (error) {
214
+ throw new InvalidTokenError(`${error}`);
215
+ }
216
+ }
217
+ async function isValidJWT(token, options) {
218
+ try {
219
+ await validateToken(token, options);
220
+ return true;
221
+ } catch (unused) {
222
+ return false;
223
+ }
224
+ }
225
+ function removeTrailingSlash(str) {
226
+ return str.replace(/\/$/, "");
227
+ }
228
+ //# sourceMappingURL=server.native.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["__toCommonJS","mod","__copyProps","__defProp","value","server_exports","__export","InvalidTokenError","NotAuthenticatedError","getAuthDataFromRequest","isValidJWT","validateToken","module","exports","import_jose","require","_assert_this_initialized","self","ReferenceError","_call_super","_this","derived","args","_get_prototype_of","_possible_constructor_return","_is_native_reflect_construct","Reflect","construct","constructor","apply","_class_call_check","instance","Constructor","TypeError","_construct","Parent","Class","Parent2","args2","Class2","a","push","Function","bind","_set_prototype_of","prototype","arguments","o","Object","setPrototypeOf","getPrototypeOf","o2","__proto__","_inherits","subClass","superClass","create","writable","configurable","_instanceof","left","right","Symbol","hasInstance","_is_native_function","fn","toString","call","indexOf","result","Boolean","valueOf","_","_type_of","p","p2"],"sources":["../../src/server.ts"],"sourcesContent":[null],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,YAAA,GAAAC,GAAA,IAAAC,WAAA,CAAAC,SAAA;EAAAC,KAAA;AAAA,IAAAH,GAAA;AAAA,IAAAI,cAAA;AAAAC,QAAA,CAAAD,cAAA;EAAAE,iBAAA,EAAAA,CAAA,KAAAA,iBAAA;EAAAC,qBAAA,EAAAA,CAAA,KAAAA,qBAAA;EAAAC,sBAAA,EAAAA,CAAA,KAAAA,sBAAA;EAAAC,UAAA,EAAAA,CAAA,KAAAA,UAAA;EAAAC,aAAA,EAAAA,CAAA,KAAAA;AAAA;AAMAC,MAAA,CAAAC,OAAA,GAAAb,YAA+D,CAAAK,cAAA;AAiBxD,IAAAS,WAAM,GAAAC,OAAA;AAAqC,SAAAC,yBAAAC,IAAA;EAC3C,IAAMA,IAAA,uBAA0BC,cAAM;EAAC,OAAAD,IAAA;AAkB9C;AAKE,SAAME,YAAaC,KAAI,EAAAC,OAAQ,EAAIC,IAAA;EAWnCD,OAAI,GAAAE,iBAAA,CAAAF,OAAA;EACF,OAAAG,4BAAiC,CAAAJ,KAAI,EAAAK,4BAA0B,EAAQ,GAACC,OAAA,CAAAC,SAAA,CAAAN,OAAA,EAAAC,IAAA,QAAAC,iBAAA,CAAAH,KAAA,EAAAQ,WAAA,IAAAP,OAAA,CAAAQ,KAAA,CAAAT,KAAA,EAAAE,IAAA;AACxE;AACE,SAAAQ,iBAAOA,CAAAC,QAAA,EAAAC,WAAA;EAAA,MACLD,QAAI,YAAaC,WAAA,aAAAC,SAAA;AAAA;AACY,SAC7BC,UAAMA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