@aura-stack/auth 0.1.0-rc.9 → 0.2.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.
Files changed (140) hide show
  1. package/dist/@types/index.cjs +15 -15
  2. package/dist/@types/index.d.ts +6 -31
  3. package/dist/@types/index.js +1 -1
  4. package/dist/@types/router.d.cjs +1 -1
  5. package/dist/@types/router.d.d.ts +6 -7
  6. package/dist/@types/utility.cjs +15 -15
  7. package/dist/@types/utility.d.ts +4 -8
  8. package/dist/@types/utility.js +1 -1
  9. package/dist/actions/callback/access-token.cjs +159 -149
  10. package/dist/actions/callback/access-token.d.ts +14 -20
  11. package/dist/actions/callback/access-token.js +9 -4
  12. package/dist/actions/callback/callback.cjs +371 -484
  13. package/dist/actions/callback/callback.d.ts +9 -12
  14. package/dist/actions/callback/callback.js +15 -12
  15. package/dist/actions/callback/userinfo.cjs +149 -139
  16. package/dist/actions/callback/userinfo.d.ts +8 -9
  17. package/dist/actions/callback/userinfo.js +11 -6
  18. package/dist/actions/csrfToken/csrfToken.cjs +112 -190
  19. package/dist/actions/csrfToken/csrfToken.d.ts +3 -3
  20. package/dist/actions/csrfToken/csrfToken.js +12 -8
  21. package/dist/actions/index.cjs +623 -807
  22. package/dist/actions/index.d.ts +12 -13
  23. package/dist/actions/index.js +33 -18
  24. package/dist/actions/session/session.cjs +86 -176
  25. package/dist/actions/session/session.d.ts +3 -3
  26. package/dist/actions/session/session.js +10 -7
  27. package/dist/actions/signIn/authorization.cjs +248 -257
  28. package/dist/actions/signIn/authorization.d.ts +11 -18
  29. package/dist/actions/signIn/authorization.js +16 -6
  30. package/dist/actions/signIn/signIn.cjs +302 -451
  31. package/dist/actions/signIn/signIn.d.ts +9 -10
  32. package/dist/actions/signIn/signIn.js +12 -10
  33. package/dist/actions/signOut/signOut.cjs +299 -468
  34. package/dist/actions/signOut/signOut.d.ts +3 -3
  35. package/dist/actions/signOut/signOut.js +14 -11
  36. package/dist/assert.cjs +40 -36
  37. package/dist/assert.d.ts +12 -4
  38. package/dist/assert.js +12 -2
  39. package/dist/chunk-2RXNXMCZ.js +55 -0
  40. package/dist/chunk-42XB3YCW.js +19 -17
  41. package/dist/chunk-4V4JNXVF.js +55 -0
  42. package/dist/chunk-6R2YZ4AC.js +22 -0
  43. package/dist/chunk-7H3OR6UU.js +81 -0
  44. package/dist/chunk-CXLATHS5.js +143 -0
  45. package/dist/chunk-E3OXBRYF.js +19 -17
  46. package/dist/chunk-EIL2FPSS.js +22 -0
  47. package/dist/chunk-FIPU4MLT.js +18 -16
  48. package/dist/chunk-FKRDCWBF.js +19 -17
  49. package/dist/chunk-IKHPGFCW.js +11 -9
  50. package/dist/chunk-IMICRJ5U.js +197 -0
  51. package/dist/chunk-IUYZQTJV.js +30 -0
  52. package/dist/chunk-KRNOMBXQ.js +19 -17
  53. package/dist/chunk-N2APGLXA.js +71 -0
  54. package/dist/chunk-NEVKX6K2.js +70 -0
  55. package/dist/chunk-PTJUYB33.js +33 -0
  56. package/dist/chunk-QDO2KSRJ.js +35 -0
  57. package/dist/chunk-QEZL7EYN.js +96 -0
  58. package/dist/chunk-RRLIF4PQ.js +55 -0
  59. package/dist/chunk-STHEPPUZ.js +8 -6
  60. package/dist/chunk-TLE4PXY3.js +39 -0
  61. package/dist/chunk-UEH3LVON.js +97 -0
  62. package/dist/chunk-WD7AUHQ5.js +79 -0
  63. package/dist/chunk-ZLR3LI6X.js +55 -0
  64. package/dist/cookie.cjs +222 -187
  65. package/dist/cookie.d.ts +38 -76
  66. package/dist/cookie.js +27 -34
  67. package/dist/errors.cjs +85 -0
  68. package/dist/errors.d.ts +48 -0
  69. package/dist/errors.js +18 -0
  70. package/dist/headers.cjs +28 -28
  71. package/dist/headers.d.ts +2 -2
  72. package/dist/headers.js +6 -2
  73. package/dist/{index-DpfbvTZ_.d.ts → index-EqsoyjrF.d.ts} +351 -318
  74. package/dist/index.cjs +1006 -1001
  75. package/dist/index.d.ts +9 -31
  76. package/dist/index.js +82 -51
  77. package/dist/jose.cjs +74 -66
  78. package/dist/jose.d.ts +11 -8
  79. package/dist/jose.js +10 -5
  80. package/dist/oauth/bitbucket.cjs +38 -38
  81. package/dist/oauth/bitbucket.d.ts +6 -7
  82. package/dist/oauth/bitbucket.js +6 -2
  83. package/dist/oauth/discord.cjs +47 -48
  84. package/dist/oauth/discord.d.ts +6 -7
  85. package/dist/oauth/discord.js +6 -2
  86. package/dist/oauth/figma.cjs +39 -39
  87. package/dist/oauth/figma.d.ts +6 -7
  88. package/dist/oauth/figma.js +6 -2
  89. package/dist/oauth/github.cjs +31 -31
  90. package/dist/oauth/github.d.ts +6 -7
  91. package/dist/oauth/github.js +6 -2
  92. package/dist/oauth/gitlab.cjs +39 -39
  93. package/dist/oauth/gitlab.d.ts +6 -7
  94. package/dist/oauth/gitlab.js +6 -2
  95. package/dist/oauth/index.cjs +306 -180
  96. package/dist/oauth/index.d.ts +6 -26
  97. package/dist/oauth/index.js +43 -9
  98. package/dist/oauth/spotify.cjs +39 -39
  99. package/dist/oauth/spotify.d.ts +6 -7
  100. package/dist/oauth/spotify.js +6 -2
  101. package/dist/oauth/strava.cjs +46 -0
  102. package/dist/oauth/strava.d.ts +6 -0
  103. package/dist/oauth/strava.js +6 -0
  104. package/dist/oauth/x.cjs +39 -39
  105. package/dist/oauth/x.d.ts +6 -7
  106. package/dist/oauth/x.js +6 -2
  107. package/dist/schemas.cjs +97 -91
  108. package/dist/schemas.d.ts +96 -126
  109. package/dist/schemas.js +20 -18
  110. package/dist/secure.cjs +106 -101
  111. package/dist/secure.d.ts +16 -17
  112. package/dist/secure.js +19 -4
  113. package/dist/utils.cjs +197 -135
  114. package/dist/utils.d.ts +20 -26
  115. package/dist/utils.js +25 -21
  116. package/package.json +5 -6
  117. package/dist/chunk-256KIVJL.js +0 -110
  118. package/dist/chunk-6SM22VVJ.js +0 -15
  119. package/dist/chunk-CAKJT3KS.js +0 -77
  120. package/dist/chunk-EBPE35JT.js +0 -29
  121. package/dist/chunk-FJUDBLCP.js +0 -52
  122. package/dist/chunk-GZU3RBTB.js +0 -51
  123. package/dist/chunk-HGJ4TXY4.js +0 -105
  124. package/dist/chunk-HMRKN75I.js +0 -74
  125. package/dist/chunk-JAPMIE6S.js +0 -8
  126. package/dist/chunk-LLR722CL.js +0 -75
  127. package/dist/chunk-RLT4RFKV.js +0 -36
  128. package/dist/chunk-SJPDVKUS.js +0 -93
  129. package/dist/chunk-SMQO5WD7.js +0 -20
  130. package/dist/chunk-UJJ7R56J.js +0 -42
  131. package/dist/chunk-UTDLUEEG.js +0 -25
  132. package/dist/chunk-VFTYH33W.js +0 -44
  133. package/dist/chunk-XXJKNKGQ.js +0 -27
  134. package/dist/chunk-ZV4BH47P.js +0 -156
  135. package/dist/error.cjs +0 -88
  136. package/dist/error.d.ts +0 -62
  137. package/dist/error.js +0 -9
  138. package/dist/response.cjs +0 -34
  139. package/dist/response.d.ts +0 -10
  140. package/dist/response.js +0 -2
@@ -1,496 +1,347 @@
1
- "use strict"
2
- var __create = Object.create
3
- var __defProp = Object.defineProperty
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor
5
- var __getOwnPropNames = Object.getOwnPropertyNames
6
- var __getProtoOf = Object.getPrototypeOf
7
- var __hasOwnProp = Object.prototype.hasOwnProperty
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __export = (target, all) => {
9
- for (var name in all) __defProp(target, name, { get: all[name], enumerable: true })
10
- }
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
11
12
  var __copyProps = (to, from, except, desc) => {
12
- if ((from && typeof from === "object") || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })
16
- }
17
- return to
18
- }
19
- var __toESM = (mod, isNodeMode, target) => (
20
- (target = mod != null ? __create(__getProtoOf(mod)) : {}),
21
- __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- )
29
- )
30
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod)
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
29
 
32
30
  // src/actions/signIn/signIn.ts
33
- var signIn_exports = {}
31
+ var signIn_exports = {};
34
32
  __export(signIn_exports, {
35
- signInAction: () => signInAction,
36
- })
37
- module.exports = __toCommonJS(signIn_exports)
38
- var import_zod = __toESM(require("zod"), 1)
39
- var import_router2 = require("@aura-stack/router")
40
-
41
- // src/response.ts
42
- var AuraResponse = class extends Response {
43
- static json(body, init) {
44
- return Response.json(body, init)
45
- }
46
- }
33
+ signInAction: () => signInAction
34
+ });
35
+ module.exports = __toCommonJS(signIn_exports);
36
+ var import_zod = __toESM(require("zod"), 1);
37
+ var import_router2 = require("@aura-stack/router");
47
38
 
48
39
  // src/secure.ts
49
- var import_node_crypto = __toESM(require("crypto"), 1)
40
+ var import_node_crypto = __toESM(require("crypto"), 1);
50
41
 
51
42
  // src/utils.ts
52
- var import_router = require("@aura-stack/router")
43
+ var import_router = require("@aura-stack/router");
53
44
 
54
- // src/error.ts
55
- var AuthError = class extends Error {
56
- constructor(type, message) {
57
- super(message)
58
- this.type = type
59
- this.name = "AuthError"
60
- }
61
- }
62
- var InvalidRedirectToError = class extends AuthError {
63
- constructor(message = "The redirectTo parameter does not match the hosted origin.") {
64
- super("invalid_redirect_to", message)
65
- this.name = "InvalidRedirectToError"
66
- }
67
- }
68
- var isAuthError = (error) => {
69
- return error instanceof AuthError
70
- }
71
- var ERROR_RESPONSE = {
72
- AUTHORIZATION: {
73
- INVALID_REQUEST: "invalid_request",
74
- UNAUTHORIZED_CLIENT: "unauthorized_client",
75
- ACCESS_DENIED: "access_denied",
76
- UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
77
- INVALID_SCOPE: "invalid_scope",
78
- SERVER_ERROR: "server_error",
79
- TEMPORARILY_UNAVAILABLE: "temporarily_unavailable",
80
- },
81
- ACCESS_TOKEN: {
82
- INVALID_REQUEST: "invalid_request",
83
- INVALID_CLIENT: "invalid_client",
84
- INVALID_GRANT: "invalid_grant",
85
- UNAUTHORIZED_CLIENT: "unauthorized_client",
86
- UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
87
- INVALID_SCOPE: "invalid_scope",
88
- },
89
- }
45
+ // src/errors.ts
46
+ var AuthInternalError = class extends Error {
47
+ type = "AUTH_INTERNAL_ERROR";
48
+ code;
49
+ constructor(code, message, options2) {
50
+ super(message, options2);
51
+ this.code = code;
52
+ this.name = new.target.name;
53
+ Error.captureStackTrace(this, new.target);
54
+ }
55
+ };
56
+ var AuthSecurityError = class extends Error {
57
+ type = "AUTH_SECURITY_ERROR";
58
+ code;
59
+ constructor(code, message, options2) {
60
+ super(message, options2);
61
+ this.code = code;
62
+ this.name = new.target.name;
63
+ Error.captureStackTrace(this, new.target);
64
+ }
65
+ };
66
+ var isAuthSecurityError = (error) => {
67
+ return error instanceof AuthSecurityError;
68
+ };
90
69
 
91
70
  // src/utils.ts
92
71
  var toSnakeCase = (str) => {
93
- return str
94
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
95
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
96
- .toLowerCase()
97
- .replace(/^_+/, "")
98
- }
72
+ return str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().replace(/^_+/, "");
73
+ };
99
74
  var toUpperCase = (str) => {
100
- return str.toUpperCase()
101
- }
75
+ return str.toUpperCase();
76
+ };
102
77
  var toCastCase = (obj, type = "snake") => {
103
- return Object.entries(obj).reduce((previous, [key, value]) => {
104
- const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key)
105
- return { ...previous, [newKey]: value }
106
- }, {})
107
- }
78
+ return Object.entries(obj).reduce((previous, [key, value]) => {
79
+ const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key);
80
+ return { ...previous, [newKey]: value };
81
+ }, {});
82
+ };
108
83
  var equals = (a, b) => {
109
- if (a === null || b === null || a === void 0 || b === void 0) return false
110
- return a === b
111
- }
112
- var sanitizeURL = (url2) => {
113
- try {
114
- let decodedURL = decodeURIComponent(url2).trim()
115
- const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/)
116
- let protocol = ""
117
- let rest = decodedURL
118
- if (protocolMatch) {
119
- protocol = protocolMatch[1]
120
- rest = decodedURL.slice(protocol.length)
121
- const slashIndex = rest.indexOf("/")
122
- if (slashIndex === -1) {
123
- return protocol + rest
124
- }
125
- const domain = rest.slice(0, slashIndex)
126
- let path = rest
127
- .slice(slashIndex)
128
- .replace(/\/\.\.\//g, "/")
129
- .replace(/\/\.\.$/, "")
130
- .replace(/\.{2,}/g, "")
131
- .replace(/\/{2,}/g, "/")
132
- if (path !== "/" && path.endsWith("/")) {
133
- path = path.replace(/\/+$/, "/")
134
- } else if (path !== "/") {
135
- path = path.replace(/\/+$/, "")
136
- }
137
- return protocol + domain + path
138
- }
139
- let sanitized = decodedURL
140
- .replace(/\/\.\.\//g, "/")
141
- .replace(/\/\.\.$/, "")
142
- .replace(/\.{2,}/g, "")
143
- .replace(/\/{2,}/g, "/")
144
- if (sanitized !== "/" && sanitized.endsWith("/")) {
145
- sanitized = sanitized.replace(/\/+$/, "/")
146
- } else if (sanitized !== "/") {
147
- sanitized = sanitized.replace(/\/+$/, "")
148
- }
149
- return sanitized
150
- } catch {
151
- return url2.trim()
84
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
85
+ return a === b;
86
+ };
87
+ var sanitizeURL = (url) => {
88
+ try {
89
+ let decodedURL = decodeURIComponent(url).trim();
90
+ const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
91
+ let protocol = "";
92
+ let rest = decodedURL;
93
+ if (protocolMatch) {
94
+ protocol = protocolMatch[1];
95
+ rest = decodedURL.slice(protocol.length);
96
+ const slashIndex = rest.indexOf("/");
97
+ if (slashIndex === -1) {
98
+ return protocol + rest;
99
+ }
100
+ const domain = rest.slice(0, slashIndex);
101
+ let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
102
+ if (path !== "/" && path.endsWith("/")) {
103
+ path = path.replace(/\/+$/, "/");
104
+ } else if (path !== "/") {
105
+ path = path.replace(/\/+$/, "");
106
+ }
107
+ return protocol + domain + path;
152
108
  }
153
- }
154
- var getNormalizedOriginPath = (path) => {
155
- try {
156
- const url2 = new URL(path)
157
- url2.hash = ""
158
- url2.search = ""
159
- return `${url2.origin}${url2.pathname}`
160
- } catch {
161
- return sanitizeURL(path)
109
+ let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
110
+ if (sanitized !== "/" && sanitized.endsWith("/")) {
111
+ sanitized = sanitized.replace(/\/+$/, "/");
112
+ } else if (sanitized !== "/") {
113
+ sanitized = sanitized.replace(/\/+$/, "");
162
114
  }
163
- }
115
+ return sanitized;
116
+ } catch {
117
+ return url.trim();
118
+ }
119
+ };
120
+ var getNormalizedOriginPath = (path) => {
121
+ try {
122
+ const url = new URL(path);
123
+ url.hash = "";
124
+ url.search = "";
125
+ return `${url.origin}${url.pathname}`;
126
+ } catch {
127
+ return sanitizeURL(path);
128
+ }
129
+ };
130
+ var formatZodError = (error) => {
131
+ if (!error.issues || error.issues.length === 0) {
132
+ return {};
133
+ }
134
+ return error.issues.reduce((previous, issue) => {
135
+ const key = issue.path.join(".");
136
+ return {
137
+ ...previous,
138
+ [key]: {
139
+ code: issue.code,
140
+ message: issue.message
141
+ }
142
+ };
143
+ }, {});
144
+ };
145
+
146
+ // src/assert.ts
147
+ var isValidURL = (value) => {
148
+ if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false;
149
+ const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/;
150
+ return regex.test(value);
151
+ };
164
152
 
165
153
  // src/secure.ts
166
154
  var generateSecure = (length = 32) => {
167
- return import_node_crypto.default.randomBytes(length).toString("base64url")
168
- }
155
+ return import_node_crypto.default.randomBytes(length).toString("base64url");
156
+ };
169
157
  var createHash = (data, base = "hex") => {
170
- return import_node_crypto.default.createHash("sha256").update(data).digest().toString(base)
171
- }
158
+ return import_node_crypto.default.createHash("sha256").update(data).digest().toString(base);
159
+ };
172
160
  var createPKCE = async (verifier) => {
173
- const codeVerifier = verifier ?? generateSecure(86)
174
- const codeChallenge = createHash(codeVerifier, "base64url")
175
- return { codeVerifier, codeChallenge, method: "S256" }
176
- }
177
-
178
- // src/cookie.ts
179
- var import_cookie = require("cookie")
180
-
181
- // src/assert.ts
182
- var isValidURL = (value) => {
183
- if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false
184
- const regex =
185
- /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/
186
- return regex.test(value)
187
- }
188
-
189
- // src/cookie.ts
190
- var import_cookie2 = require("cookie")
191
- var COOKIE_NAME = "aura-auth"
192
- var defaultCookieOptions = {
193
- httpOnly: true,
194
- sameSite: "lax",
195
- path: "/",
196
- maxAge: 60 * 60 * 24 * 15,
197
- }
198
- var defaultStandardCookieConfig = {
199
- secure: false,
200
- httpOnly: true,
201
- prefix: "",
202
- }
203
- var defaultSecureCookieConfig = {
204
- secure: true,
205
- prefix: "__Secure-",
206
- }
207
- var defaultHostCookieConfig = {
208
- secure: true,
209
- prefix: "__Host-",
210
- path: "/",
211
- domain: void 0,
212
- }
213
- var expiredCookieOptions = {
214
- ...defaultCookieOptions,
215
- expires: /* @__PURE__ */ new Date(0),
216
- maxAge: 0,
217
- }
218
- var defineDefaultCookieOptions = (options2) => {
219
- return {
220
- name: options2?.name ?? COOKIE_NAME,
221
- prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
222
- ...defaultCookieOptions,
223
- ...options2,
224
- }
225
- }
226
- var setCookie = (cookieName, value, options2) => {
227
- const { prefix, name } = defineDefaultCookieOptions(options2)
228
- const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`
229
- return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
230
- ...defaultCookieOptions,
231
- ...options2,
232
- })
233
- }
234
- var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
235
- const name = cookieOptions.name ?? COOKIE_NAME
236
- const isSecure = trustedProxyHeaders
237
- ? request.url.startsWith("https://") ||
238
- request.headers.get("X-Forwarded-Proto") === "https" ||
239
- request.headers.get("Forwarded")?.includes("proto=https")
240
- : request.url.startsWith("https://")
241
- if (!cookieOptions.options?.httpOnly) {
242
- console.warn(
243
- "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
244
- )
245
- }
246
- if (cookieOptions.options?.domain === "*") {
247
- console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.")
248
- }
249
- if (!isSecure) {
250
- const options2 = cookieOptions.options
251
- if (options2?.secure) {
252
- console.warn(
253
- "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
254
- )
255
- }
256
- if (options2?.sameSite == "none") {
257
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.")
258
- }
259
- if (process.env.NODE_ENV === "production") {
260
- console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.")
261
- }
262
- return {
263
- ...defaultCookieOptions,
264
- ...cookieOptions.options,
265
- sameSite: options2?.sameSite === "none" ? "lax" : (options2?.sameSite ?? "lax"),
266
- ...defaultStandardCookieConfig,
267
- name,
268
- }
269
- }
270
- return cookieOptions.strategy === "host"
271
- ? {
272
- ...defaultCookieOptions,
273
- ...cookieOptions.options,
274
- ...defaultHostCookieConfig,
275
- name,
276
- }
277
- : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name }
278
- }
279
- var oauthCookie = (options2) => {
280
- return {
281
- ...options2,
282
- secure: options2.secure,
283
- httpOnly: options2.httpOnly,
284
- maxAge: 5 * 60,
285
- expires: new Date(Date.now() + 5 * 60 * 1e3),
286
- }
287
- }
161
+ const codeVerifier = verifier ?? generateSecure(86);
162
+ const codeChallenge = createHash(codeVerifier, "base64url");
163
+ return { codeVerifier, codeChallenge, method: "S256" };
164
+ };
288
165
 
289
166
  // src/schemas.ts
290
- var import_v4 = require("zod/v4")
167
+ var import_v4 = require("zod/v4");
291
168
  var OAuthProviderConfigSchema = (0, import_v4.object)({
292
- authorizeURL: (0, import_v4.url)(),
293
- accessToken: (0, import_v4.url)(),
294
- scope: (0, import_v4.string)().optional(),
295
- userInfo: (0, import_v4.url)(),
296
- responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
297
- clientId: (0, import_v4.string)(),
298
- clientSecret: (0, import_v4.string)(),
299
- })
169
+ authorizeURL: (0, import_v4.httpUrl)(),
170
+ accessToken: (0, import_v4.httpUrl)(),
171
+ scope: (0, import_v4.string)().optional(),
172
+ userInfo: (0, import_v4.httpUrl)(),
173
+ responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
174
+ clientId: (0, import_v4.string)(),
175
+ clientSecret: (0, import_v4.string)()
176
+ });
300
177
  var OAuthAuthorization = OAuthProviderConfigSchema.extend({
301
- redirectURI: (0, import_v4.string)(),
302
- state: (0, import_v4.string)(),
303
- codeChallenge: (0, import_v4.string)(),
304
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"]),
305
- })
178
+ redirectURI: (0, import_v4.string)(),
179
+ state: (0, import_v4.string)(),
180
+ codeChallenge: (0, import_v4.string)(),
181
+ codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
182
+ });
306
183
  var OAuthAuthorizationResponse = (0, import_v4.object)({
307
- state: (0, import_v4.string)(),
308
- code: (0, import_v4.string)(),
309
- })
184
+ state: (0, import_v4.string)("Missing state parameter in the OAuth authorization response."),
185
+ code: (0, import_v4.string)("Missing code parameter in the OAuth authorization response.")
186
+ });
310
187
  var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
311
- error: (0, import_v4.enum)([
312
- "invalid_request",
313
- "unauthorized_client",
314
- "access_denied",
315
- "unsupported_response_type",
316
- "invalid_scope",
317
- "server_error",
318
- "temporarily_unavailable",
319
- ]),
320
- error_description: (0, import_v4.string)().optional(),
321
- error_uri: (0, import_v4.string)().optional(),
322
- state: (0, import_v4.string)(),
323
- })
188
+ error: (0, import_v4.enum)([
189
+ "invalid_request",
190
+ "unauthorized_client",
191
+ "access_denied",
192
+ "unsupported_response_type",
193
+ "invalid_scope",
194
+ "server_error",
195
+ "temporarily_unavailable"
196
+ ]),
197
+ error_description: (0, import_v4.string)().optional(),
198
+ error_uri: (0, import_v4.string)().optional(),
199
+ state: (0, import_v4.string)()
200
+ });
324
201
  var OAuthAccessToken = OAuthProviderConfigSchema.extend({
325
- redirectURI: (0, import_v4.string)(),
326
- code: (0, import_v4.string)(),
327
- codeVerifier: (0, import_v4.string)().min(43).max(128),
328
- })
202
+ redirectURI: (0, import_v4.string)(),
203
+ code: (0, import_v4.string)(),
204
+ codeVerifier: (0, import_v4.string)().min(43).max(128)
205
+ });
329
206
  var OAuthAccessTokenResponse = (0, import_v4.object)({
330
- access_token: (0, import_v4.string)(),
331
- token_type: (0, import_v4.string)(),
332
- expires_in: (0, import_v4.number)().optional(),
333
- refresh_token: (0, import_v4.string)().optional(),
334
- scope: (0, import_v4.string)().optional(),
335
- })
207
+ access_token: (0, import_v4.string)(),
208
+ token_type: (0, import_v4.string)(),
209
+ expires_in: (0, import_v4.number)().optional(),
210
+ refresh_token: (0, import_v4.string)().optional(),
211
+ scope: (0, import_v4.string)().optional()
212
+ });
336
213
  var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
337
- error: (0, import_v4.enum)([
338
- "invalid_request",
339
- "invalid_client",
340
- "invalid_grant",
341
- "unauthorized_client",
342
- "unsupported_grant_type",
343
- "invalid_scope",
344
- ]),
345
- error_description: (0, import_v4.string)().optional(),
346
- error_uri: (0, import_v4.string)().optional(),
347
- })
214
+ error: (0, import_v4.enum)([
215
+ "invalid_request",
216
+ "invalid_client",
217
+ "invalid_grant",
218
+ "unauthorized_client",
219
+ "unsupported_grant_type",
220
+ "invalid_scope"
221
+ ]),
222
+ error_description: (0, import_v4.string)().optional(),
223
+ error_uri: (0, import_v4.string)().optional()
224
+ });
348
225
  var OAuthErrorResponse = (0, import_v4.object)({
349
- error: (0, import_v4.string)(),
350
- error_description: (0, import_v4.string)().optional(),
351
- })
226
+ error: (0, import_v4.string)(),
227
+ error_description: (0, import_v4.string)().optional()
228
+ });
229
+ var OAuthEnvSchema = (0, import_v4.object)({
230
+ clientId: import_v4.z.string().min(1, "OAuth Client ID is required in the environment variables."),
231
+ clientSecret: import_v4.z.string().min(1, "OAuth Client Secret is required in the environment variables.")
232
+ });
352
233
 
353
234
  // src/actions/signIn/authorization.ts
354
235
  var createAuthorizationURL = (oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod) => {
355
- const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod })
356
- if (!parsed.success) {
357
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR, "Invalid OAuth configuration")
358
- }
359
- const { authorizeURL, ...options2 } = parsed.data
360
- const { userInfo, accessToken, clientSecret, ...required } = options2
361
- const searchParams = new URLSearchParams(toCastCase(required))
362
- return `${authorizeURL}?${searchParams}`
363
- }
236
+ const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod });
237
+ if (!parsed.success) {
238
+ const msg = JSON.stringify(formatZodError(parsed.error), null, 2);
239
+ throw new AuthInternalError("INVALID_OAUTH_CONFIGURATION", msg);
240
+ }
241
+ const { authorizeURL, ...options2 } = parsed.data;
242
+ const { userInfo, accessToken, clientSecret, ...required } = options2;
243
+ const searchParams = new URLSearchParams(toCastCase(required));
244
+ return `${authorizeURL}?${searchParams}`;
245
+ };
364
246
  var getOriginURL = (request, trustedProxyHeaders) => {
365
- const headers = request.headers
366
- if (trustedProxyHeaders) {
367
- const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http"
368
- const host =
369
- headers.get("X-Forwarded-Host") ??
370
- headers.get("Host") ??
371
- headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ??
372
- null
373
- return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`)
374
- } else {
375
- return new URL(getNormalizedOriginPath(request.url))
376
- }
377
- }
247
+ const headers = request.headers;
248
+ if (trustedProxyHeaders) {
249
+ const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http";
250
+ const host = headers.get("X-Forwarded-Host") ?? headers.get("Host") ?? headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? null;
251
+ return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`);
252
+ } else {
253
+ return new URL(getNormalizedOriginPath(request.url));
254
+ }
255
+ };
378
256
  var createRedirectURI = (request, oauth, basePath, trustedProxyHeaders) => {
379
- const url2 = getOriginURL(request, trustedProxyHeaders)
380
- return `${url2.origin}${basePath}/callback/${oauth}`
381
- }
257
+ const url = getOriginURL(request, trustedProxyHeaders);
258
+ return `${url.origin}${basePath}/callback/${oauth}`;
259
+ };
382
260
  var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
383
- try {
384
- const headers = request.headers
385
- const origin = headers.get("Origin")
386
- const referer = headers.get("Referer")
387
- let hostedURL = getOriginURL(request, trustedProxyHeaders)
388
- if (redirectTo) {
389
- if (redirectTo.startsWith("/")) {
390
- return sanitizeURL(redirectTo)
391
- }
392
- const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)))
393
- if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
394
- throw new InvalidRedirectToError()
395
- }
396
- return sanitizeURL(redirectToURL.pathname)
397
- }
398
- if (referer) {
399
- const refererURL = new URL(sanitizeURL(referer))
400
- if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
401
- throw new AuthError(
402
- ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST,
403
- "The referer of the request does not match the hosted origin."
404
- )
405
- }
406
- return sanitizeURL(refererURL.pathname)
407
- }
408
- if (origin) {
409
- const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)))
410
- if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
411
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).")
412
- }
413
- return sanitizeURL(originURL.pathname)
414
- }
415
- return "/"
416
- } catch (error) {
417
- if (isAuthError(error)) {
418
- throw error
419
- }
420
- throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).")
261
+ try {
262
+ const headers = request.headers;
263
+ const origin = headers.get("Origin");
264
+ const referer = headers.get("Referer");
265
+ let hostedURL = getOriginURL(request, trustedProxyHeaders);
266
+ if (redirectTo) {
267
+ if (redirectTo.startsWith("/")) {
268
+ return sanitizeURL(redirectTo);
269
+ }
270
+ const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)));
271
+ if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
272
+ throw new AuthSecurityError(
273
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
274
+ "The redirectTo parameter does not match the hosted origin."
275
+ );
276
+ }
277
+ return sanitizeURL(redirectToURL.pathname);
278
+ }
279
+ if (referer) {
280
+ const refererURL = new URL(sanitizeURL(referer));
281
+ if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
282
+ throw new AuthSecurityError(
283
+ "POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED",
284
+ "The referer of the request does not match the hosted origin."
285
+ );
286
+ }
287
+ return sanitizeURL(refererURL.pathname);
421
288
  }
422
- }
289
+ if (origin) {
290
+ const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)));
291
+ if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
292
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
293
+ }
294
+ return sanitizeURL(originURL.pathname);
295
+ }
296
+ return "/";
297
+ } catch (error) {
298
+ if (isAuthSecurityError(error)) {
299
+ throw error;
300
+ }
301
+ throw new AuthSecurityError("POTENTIAL_OPEN_REDIRECT_ATTACK_DETECTED", "Invalid origin (potential CSRF).");
302
+ }
303
+ };
423
304
 
424
305
  // src/actions/signIn/signIn.ts
425
306
  var signInConfig = (oauth) => {
426
- return (0, import_router2.createEndpointConfig)("/signIn/:oauth", {
427
- schemas: {
428
- params: import_zod.default.object({
429
- oauth: import_zod.default.enum(Object.keys(oauth)),
430
- redirectTo: import_zod.default.string().optional(),
431
- }),
432
- },
433
- })
434
- }
307
+ return (0, import_router2.createEndpointConfig)("/signIn/:oauth", {
308
+ schemas: {
309
+ params: import_zod.default.object({
310
+ oauth: import_zod.default.enum(Object.keys(oauth), "The OAuth provider is not supported or invalid."),
311
+ redirectTo: import_zod.default.string().optional()
312
+ })
313
+ }
314
+ });
315
+ };
435
316
  var signInAction = (oauth) => {
436
- return (0, import_router2.createEndpoint)(
437
- "GET",
438
- "/signIn/:oauth",
439
- async (ctx) => {
440
- const {
441
- request,
442
- params: { oauth: oauth2, redirectTo },
443
- context: { oauth: providers, cookies, trustedProxyHeaders, basePath },
444
- } = ctx
445
- try {
446
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
447
- const state = generateSecure()
448
- const redirectURI = createRedirectURI(request, oauth2, basePath, trustedProxyHeaders)
449
- const stateCookie = setCookie("state", state, oauthCookie(cookieOptions))
450
- const redirectURICookie = setCookie("redirect_uri", redirectURI, oauthCookie(cookieOptions))
451
- const redirectToCookie = setCookie(
452
- "redirect_to",
453
- createRedirectTo(request, redirectTo, trustedProxyHeaders),
454
- oauthCookie(cookieOptions)
455
- )
456
- const { codeVerifier, codeChallenge, method } = await createPKCE()
457
- const codeVerifierCookie = setCookie("code_verifier", codeVerifier, oauthCookie(cookieOptions))
458
- const authorization = createAuthorizationURL(providers[oauth2], redirectURI, state, codeChallenge, method)
459
- const headers = new Headers()
460
- headers.set("Location", authorization)
461
- headers.append("Set-Cookie", stateCookie)
462
- headers.append("Set-Cookie", redirectURICookie)
463
- headers.append("Set-Cookie", redirectToCookie)
464
- headers.append("Set-Cookie", codeVerifierCookie)
465
- return Response.json(
466
- { oauth: oauth2 },
467
- {
468
- status: 302,
469
- headers,
470
- }
471
- )
472
- } catch (error) {
473
- if (isAuthError(error)) {
474
- const { type, message } = error
475
- return AuraResponse.json(
476
- { error: type, error_description: message },
477
- { status: import_router2.statusCode.BAD_REQUEST }
478
- )
479
- }
480
- return AuraResponse.json(
481
- {
482
- error: ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR,
483
- error_description: "An unexpected error occurred",
484
- },
485
- { status: import_router2.statusCode.INTERNAL_SERVER_ERROR }
486
- )
487
- }
488
- },
489
- signInConfig(oauth)
490
- )
491
- }
317
+ return (0, import_router2.createEndpoint)(
318
+ "GET",
319
+ "/signIn/:oauth",
320
+ async (ctx) => {
321
+ const {
322
+ request,
323
+ headers: headersBuilder,
324
+ params: { oauth: oauth2, redirectTo },
325
+ context: { oauth: providers, cookies, trustedProxyHeaders, basePath }
326
+ } = ctx;
327
+ const state = generateSecure();
328
+ const redirectURI = createRedirectURI(request, oauth2, basePath, trustedProxyHeaders);
329
+ const redirectToValue = createRedirectTo(request, redirectTo, trustedProxyHeaders);
330
+ const { codeVerifier, codeChallenge, method } = await createPKCE();
331
+ const authorization = createAuthorizationURL(providers[oauth2], redirectURI, state, codeChallenge, method);
332
+ const headers = headersBuilder.setHeader("Location", authorization).setCookie(cookies.state.name, state, cookies.state.attributes).setCookie(cookies.redirect_uri.name, redirectURI, cookies.redirect_uri.attributes).setCookie(cookies.redirect_to.name, redirectToValue, cookies.redirect_to.attributes).setCookie(cookies.code_verifier.name, codeVerifier, cookies.code_verifier.attributes).toHeaders();
333
+ return Response.json(
334
+ { oauth: oauth2 },
335
+ {
336
+ status: 302,
337
+ headers
338
+ }
339
+ );
340
+ },
341
+ signInConfig(oauth)
342
+ );
343
+ };
492
344
  // Annotate the CommonJS export names for ESM import in node:
493
- 0 &&
494
- (module.exports = {
495
- signInAction,
496
- })
345
+ 0 && (module.exports = {
346
+ signInAction
347
+ });