@aura-stack/auth 0.1.0-rc.8 → 0.1.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 (116) hide show
  1. package/dist/@types/index.cjs +15 -15
  2. package/dist/@types/index.d.ts +7 -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 +7 -7
  6. package/dist/@types/utility.cjs +15 -15
  7. package/dist/@types/utility.d.ts +6 -6
  8. package/dist/@types/utility.js +1 -1
  9. package/dist/actions/callback/access-token.cjs +143 -143
  10. package/dist/actions/callback/access-token.d.ts +15 -20
  11. package/dist/actions/callback/access-token.js +8 -4
  12. package/dist/actions/callback/callback.cjs +437 -455
  13. package/dist/actions/callback/callback.d.ts +10 -12
  14. package/dist/actions/callback/callback.js +16 -12
  15. package/dist/actions/callback/userinfo.cjs +131 -134
  16. package/dist/actions/callback/userinfo.d.ts +9 -9
  17. package/dist/actions/callback/userinfo.js +10 -6
  18. package/dist/actions/csrfToken/csrfToken.cjs +162 -171
  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 +746 -773
  22. package/dist/actions/index.d.ts +13 -13
  23. package/dist/actions/index.js +34 -18
  24. package/dist/actions/session/session.cjs +149 -155
  25. package/dist/actions/session/session.d.ts +3 -3
  26. package/dist/actions/session/session.js +11 -7
  27. package/dist/actions/signIn/authorization.cjs +231 -249
  28. package/dist/actions/signIn/authorization.d.ts +12 -18
  29. package/dist/actions/signIn/authorization.js +16 -6
  30. package/dist/actions/signIn/signIn.cjs +396 -423
  31. package/dist/actions/signIn/signIn.d.ts +10 -10
  32. package/dist/actions/signIn/signIn.js +14 -10
  33. package/dist/actions/signOut/signOut.cjs +417 -440
  34. package/dist/actions/signOut/signOut.d.ts +3 -3
  35. package/dist/actions/signOut/signOut.js +15 -11
  36. package/dist/assert.cjs +35 -36
  37. package/dist/assert.d.ts +4 -4
  38. package/dist/assert.js +10 -2
  39. package/dist/chunk-256KIVJL.js +85 -96
  40. package/dist/chunk-42XB3YCW.js +19 -17
  41. package/dist/chunk-6SM22VVJ.js +13 -10
  42. package/dist/chunk-CAKJT3KS.js +84 -69
  43. package/dist/chunk-E3OXBRYF.js +19 -17
  44. package/dist/chunk-EBPE35JT.js +28 -26
  45. package/dist/chunk-FIPU4MLT.js +18 -16
  46. package/dist/chunk-FJUDBLCP.js +50 -43
  47. package/dist/chunk-FKRDCWBF.js +19 -17
  48. package/dist/chunk-GZU3RBTB.js +51 -40
  49. package/dist/chunk-HGJ4TXY4.js +132 -100
  50. package/dist/chunk-HMRKN75I.js +63 -63
  51. package/dist/chunk-IKHPGFCW.js +11 -9
  52. package/dist/chunk-JAPMIE6S.js +7 -5
  53. package/dist/chunk-KRNOMBXQ.js +19 -17
  54. package/dist/chunk-LLR722CL.js +91 -70
  55. package/dist/chunk-RLT4RFKV.js +39 -30
  56. package/dist/chunk-SJPDVKUS.js +107 -88
  57. package/dist/chunk-SMQO5WD7.js +26 -16
  58. package/dist/chunk-STHEPPUZ.js +8 -6
  59. package/dist/chunk-UJJ7R56J.js +47 -37
  60. package/dist/chunk-UTDLUEEG.js +27 -21
  61. package/dist/chunk-VFTYH33W.js +54 -37
  62. package/dist/chunk-XXJKNKGQ.js +33 -23
  63. package/dist/chunk-ZV4BH47P.js +132 -134
  64. package/dist/cookie.cjs +169 -175
  65. package/dist/cookie.d.ts +23 -51
  66. package/dist/cookie.js +34 -34
  67. package/dist/error.cjs +75 -75
  68. package/dist/error.d.ts +30 -30
  69. package/dist/error.js +15 -8
  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 +249 -298
  74. package/dist/index.cjs +936 -969
  75. package/dist/index.d.ts +10 -31
  76. package/dist/index.js +70 -50
  77. package/dist/jose.cjs +61 -64
  78. package/dist/jose.d.ts +8 -8
  79. package/dist/jose.js +9 -5
  80. package/dist/oauth/bitbucket.cjs +38 -38
  81. package/dist/oauth/bitbucket.d.ts +7 -7
  82. package/dist/oauth/bitbucket.js +6 -2
  83. package/dist/oauth/discord.cjs +48 -48
  84. package/dist/oauth/discord.d.ts +7 -7
  85. package/dist/oauth/discord.js +6 -2
  86. package/dist/oauth/figma.cjs +39 -39
  87. package/dist/oauth/figma.d.ts +7 -7
  88. package/dist/oauth/figma.js +6 -2
  89. package/dist/oauth/github.cjs +31 -31
  90. package/dist/oauth/github.d.ts +7 -7
  91. package/dist/oauth/github.js +6 -2
  92. package/dist/oauth/gitlab.cjs +39 -39
  93. package/dist/oauth/gitlab.d.ts +7 -7
  94. package/dist/oauth/gitlab.js +6 -2
  95. package/dist/oauth/index.cjs +180 -180
  96. package/dist/oauth/index.d.ts +7 -26
  97. package/dist/oauth/index.js +36 -9
  98. package/dist/oauth/spotify.cjs +39 -39
  99. package/dist/oauth/spotify.d.ts +7 -7
  100. package/dist/oauth/spotify.js +6 -2
  101. package/dist/oauth/x.cjs +39 -39
  102. package/dist/oauth/x.d.ts +7 -7
  103. package/dist/oauth/x.js +6 -2
  104. package/dist/response.cjs +27 -27
  105. package/dist/response.d.ts +2 -2
  106. package/dist/response.js +6 -2
  107. package/dist/schemas.cjs +91 -91
  108. package/dist/schemas.d.ts +93 -126
  109. package/dist/schemas.js +18 -18
  110. package/dist/secure.cjs +95 -98
  111. package/dist/secure.d.ts +17 -17
  112. package/dist/secure.js +18 -4
  113. package/dist/utils.cjs +119 -132
  114. package/dist/utils.d.ts +11 -26
  115. package/dist/utils.js +21 -21
  116. package/package.json +2 -2
@@ -1,535 +1,517 @@
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/callback/callback.ts
33
- var callback_exports = {}
31
+ var callback_exports = {};
34
32
  __export(callback_exports, {
35
- callbackAction: () => callbackAction,
36
- })
37
- module.exports = __toCommonJS(callback_exports)
38
- var import_zod = __toESM(require("zod"), 1)
39
- var import_router2 = require("@aura-stack/router")
33
+ callbackAction: () => callbackAction
34
+ });
35
+ module.exports = __toCommonJS(callback_exports);
36
+ var import_zod = __toESM(require("zod"), 1);
37
+ var import_router2 = require("@aura-stack/router");
40
38
 
41
39
  // src/secure.ts
42
- var import_node_crypto = __toESM(require("crypto"), 1)
40
+ var import_node_crypto = __toESM(require("crypto"), 1);
43
41
 
44
42
  // src/utils.ts
45
- var import_router = require("@aura-stack/router")
43
+ var import_router = require("@aura-stack/router");
46
44
 
47
45
  // src/error.ts
48
46
  var AuthError = class extends Error {
49
- constructor(type, message) {
50
- super(message)
51
- this.type = type
52
- this.name = "AuthError"
53
- }
54
- }
47
+ constructor(type, message) {
48
+ super(message);
49
+ this.type = type;
50
+ this.name = "AuthError";
51
+ }
52
+ };
55
53
  var isAuthError = (error) => {
56
- return error instanceof AuthError
57
- }
54
+ return error instanceof AuthError;
55
+ };
58
56
  var throwAuthError = (error, message) => {
59
- if (error instanceof Error) {
60
- if (isAuthError(error)) {
61
- throw error
62
- }
63
- throw new AuthError("invalid_request", error.message ?? message)
57
+ if (error instanceof Error) {
58
+ if (isAuthError(error)) {
59
+ throw error;
64
60
  }
65
- }
61
+ throw new AuthError("invalid_request", error.message ?? message);
62
+ }
63
+ };
66
64
  var ERROR_RESPONSE = {
67
- AUTHORIZATION: {
68
- INVALID_REQUEST: "invalid_request",
69
- UNAUTHORIZED_CLIENT: "unauthorized_client",
70
- ACCESS_DENIED: "access_denied",
71
- UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
72
- INVALID_SCOPE: "invalid_scope",
73
- SERVER_ERROR: "server_error",
74
- TEMPORARILY_UNAVAILABLE: "temporarily_unavailable",
75
- },
76
- ACCESS_TOKEN: {
77
- INVALID_REQUEST: "invalid_request",
78
- INVALID_CLIENT: "invalid_client",
79
- INVALID_GRANT: "invalid_grant",
80
- UNAUTHORIZED_CLIENT: "unauthorized_client",
81
- UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
82
- INVALID_SCOPE: "invalid_scope",
83
- },
84
- }
65
+ AUTHORIZATION: {
66
+ INVALID_REQUEST: "invalid_request",
67
+ UNAUTHORIZED_CLIENT: "unauthorized_client",
68
+ ACCESS_DENIED: "access_denied",
69
+ UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
70
+ INVALID_SCOPE: "invalid_scope",
71
+ SERVER_ERROR: "server_error",
72
+ TEMPORARILY_UNAVAILABLE: "temporarily_unavailable"
73
+ },
74
+ ACCESS_TOKEN: {
75
+ INVALID_REQUEST: "invalid_request",
76
+ INVALID_CLIENT: "invalid_client",
77
+ INVALID_GRANT: "invalid_grant",
78
+ UNAUTHORIZED_CLIENT: "unauthorized_client",
79
+ UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
80
+ INVALID_SCOPE: "invalid_scope"
81
+ }
82
+ };
85
83
 
86
84
  // src/utils.ts
87
85
  var equals = (a, b) => {
88
- if (a === null || b === null || a === void 0 || b === void 0) return false
89
- return a === b
90
- }
86
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
87
+ return a === b;
88
+ };
91
89
  var sanitizeURL = (url2) => {
92
- try {
93
- let decodedURL = decodeURIComponent(url2).trim()
94
- const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/)
95
- let protocol = ""
96
- let rest = decodedURL
97
- if (protocolMatch) {
98
- protocol = protocolMatch[1]
99
- rest = decodedURL.slice(protocol.length)
100
- const slashIndex = rest.indexOf("/")
101
- if (slashIndex === -1) {
102
- return protocol + rest
103
- }
104
- const domain = rest.slice(0, slashIndex)
105
- let path = rest
106
- .slice(slashIndex)
107
- .replace(/\/\.\.\//g, "/")
108
- .replace(/\/\.\.$/, "")
109
- .replace(/\.{2,}/g, "")
110
- .replace(/\/{2,}/g, "/")
111
- if (path !== "/" && path.endsWith("/")) {
112
- path = path.replace(/\/+$/, "/")
113
- } else if (path !== "/") {
114
- path = path.replace(/\/+$/, "")
115
- }
116
- return protocol + domain + path
117
- }
118
- let sanitized = decodedURL
119
- .replace(/\/\.\.\//g, "/")
120
- .replace(/\/\.\.$/, "")
121
- .replace(/\.{2,}/g, "")
122
- .replace(/\/{2,}/g, "/")
123
- if (sanitized !== "/" && sanitized.endsWith("/")) {
124
- sanitized = sanitized.replace(/\/+$/, "/")
125
- } else if (sanitized !== "/") {
126
- sanitized = sanitized.replace(/\/+$/, "")
127
- }
128
- return sanitized
129
- } catch {
130
- return url2.trim()
90
+ try {
91
+ let decodedURL = decodeURIComponent(url2).trim();
92
+ const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
93
+ let protocol = "";
94
+ let rest = decodedURL;
95
+ if (protocolMatch) {
96
+ protocol = protocolMatch[1];
97
+ rest = decodedURL.slice(protocol.length);
98
+ const slashIndex = rest.indexOf("/");
99
+ if (slashIndex === -1) {
100
+ return protocol + rest;
101
+ }
102
+ const domain = rest.slice(0, slashIndex);
103
+ let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
104
+ if (path !== "/" && path.endsWith("/")) {
105
+ path = path.replace(/\/+$/, "/");
106
+ } else if (path !== "/") {
107
+ path = path.replace(/\/+$/, "");
108
+ }
109
+ return protocol + domain + path;
110
+ }
111
+ let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
112
+ if (sanitized !== "/" && sanitized.endsWith("/")) {
113
+ sanitized = sanitized.replace(/\/+$/, "/");
114
+ } else if (sanitized !== "/") {
115
+ sanitized = sanitized.replace(/\/+$/, "");
131
116
  }
132
- }
117
+ return sanitized;
118
+ } catch {
119
+ return url2.trim();
120
+ }
121
+ };
133
122
  var isValidRelativePath = (path) => {
134
- if (!path || typeof path !== "string") return false
135
- if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false
136
- if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false
137
- const sanitized = sanitizeURL(path)
138
- if (sanitized.includes("..")) return false
139
- return true
140
- }
123
+ if (!path || typeof path !== "string") return false;
124
+ if (!path.startsWith("/") || path.includes("://") || path.includes("\r") || path.includes("\n")) return false;
125
+ if (/[\x00-\x1F\x7F]/.test(path) || path.includes("\0")) return false;
126
+ const sanitized = sanitizeURL(path);
127
+ if (sanitized.includes("..")) return false;
128
+ return true;
129
+ };
141
130
 
142
131
  // src/secure.ts
143
132
  var generateSecure = (length = 32) => {
144
- return import_node_crypto.default.randomBytes(length).toString("base64url")
145
- }
133
+ return import_node_crypto.default.randomBytes(length).toString("base64url");
134
+ };
146
135
  var createCSRF = async (jose, csrfCookie) => {
147
- try {
148
- const token = generateSecure(32)
149
- if (csrfCookie) {
150
- await jose.verifyJWS(csrfCookie)
151
- return csrfCookie
152
- }
153
- return jose.signJWS({ token })
154
- } catch {
155
- const token = generateSecure(32)
156
- return jose.signJWS({ token })
136
+ try {
137
+ const token = generateSecure(32);
138
+ if (csrfCookie) {
139
+ await jose.verifyJWS(csrfCookie);
140
+ return csrfCookie;
157
141
  }
158
- }
142
+ return jose.signJWS({ token });
143
+ } catch {
144
+ const token = generateSecure(32);
145
+ return jose.signJWS({ token });
146
+ }
147
+ };
159
148
 
160
149
  // src/headers.ts
161
150
  var cacheControl = {
162
- "Cache-Control": "no-store",
163
- Pragma: "no-cache",
164
- Expires: "0",
165
- Vary: "Cookie",
166
- }
151
+ "Cache-Control": "no-store",
152
+ Pragma: "no-cache",
153
+ Expires: "0",
154
+ Vary: "Cookie"
155
+ };
167
156
 
168
157
  // src/schemas.ts
169
- var import_v4 = require("zod/v4")
158
+ var import_v4 = require("zod/v4");
170
159
  var OAuthProviderConfigSchema = (0, import_v4.object)({
171
- authorizeURL: (0, import_v4.url)(),
172
- accessToken: (0, import_v4.url)(),
173
- scope: (0, import_v4.string)().optional(),
174
- userInfo: (0, import_v4.url)(),
175
- responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
176
- clientId: (0, import_v4.string)(),
177
- clientSecret: (0, import_v4.string)(),
178
- })
160
+ authorizeURL: (0, import_v4.url)(),
161
+ accessToken: (0, import_v4.url)(),
162
+ scope: (0, import_v4.string)().optional(),
163
+ userInfo: (0, import_v4.url)(),
164
+ responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
165
+ clientId: (0, import_v4.string)(),
166
+ clientSecret: (0, import_v4.string)()
167
+ });
179
168
  var OAuthAuthorization = OAuthProviderConfigSchema.extend({
180
- redirectURI: (0, import_v4.string)(),
181
- state: (0, import_v4.string)(),
182
- codeChallenge: (0, import_v4.string)(),
183
- codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"]),
184
- })
169
+ redirectURI: (0, import_v4.string)(),
170
+ state: (0, import_v4.string)(),
171
+ codeChallenge: (0, import_v4.string)(),
172
+ codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
173
+ });
185
174
  var OAuthAuthorizationResponse = (0, import_v4.object)({
186
- state: (0, import_v4.string)(),
187
- code: (0, import_v4.string)(),
188
- })
175
+ state: (0, import_v4.string)(),
176
+ code: (0, import_v4.string)()
177
+ });
189
178
  var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
190
- error: (0, import_v4.enum)([
191
- "invalid_request",
192
- "unauthorized_client",
193
- "access_denied",
194
- "unsupported_response_type",
195
- "invalid_scope",
196
- "server_error",
197
- "temporarily_unavailable",
198
- ]),
199
- error_description: (0, import_v4.string)().optional(),
200
- error_uri: (0, import_v4.string)().optional(),
201
- state: (0, import_v4.string)(),
202
- })
179
+ error: (0, import_v4.enum)([
180
+ "invalid_request",
181
+ "unauthorized_client",
182
+ "access_denied",
183
+ "unsupported_response_type",
184
+ "invalid_scope",
185
+ "server_error",
186
+ "temporarily_unavailable"
187
+ ]),
188
+ error_description: (0, import_v4.string)().optional(),
189
+ error_uri: (0, import_v4.string)().optional(),
190
+ state: (0, import_v4.string)()
191
+ });
203
192
  var OAuthAccessToken = OAuthProviderConfigSchema.extend({
204
- redirectURI: (0, import_v4.string)(),
205
- code: (0, import_v4.string)(),
206
- codeVerifier: (0, import_v4.string)().min(43).max(128),
207
- })
193
+ redirectURI: (0, import_v4.string)(),
194
+ code: (0, import_v4.string)(),
195
+ codeVerifier: (0, import_v4.string)().min(43).max(128)
196
+ });
208
197
  var OAuthAccessTokenResponse = (0, import_v4.object)({
209
- access_token: (0, import_v4.string)(),
210
- token_type: (0, import_v4.string)(),
211
- expires_in: (0, import_v4.number)().optional(),
212
- refresh_token: (0, import_v4.string)().optional(),
213
- scope: (0, import_v4.string)().optional(),
214
- })
198
+ access_token: (0, import_v4.string)(),
199
+ token_type: (0, import_v4.string)(),
200
+ expires_in: (0, import_v4.number)().optional(),
201
+ refresh_token: (0, import_v4.string)().optional(),
202
+ scope: (0, import_v4.string)().optional()
203
+ });
215
204
  var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
216
- error: (0, import_v4.enum)([
217
- "invalid_request",
218
- "invalid_client",
219
- "invalid_grant",
220
- "unauthorized_client",
221
- "unsupported_grant_type",
222
- "invalid_scope",
223
- ]),
224
- error_description: (0, import_v4.string)().optional(),
225
- error_uri: (0, import_v4.string)().optional(),
226
- })
205
+ error: (0, import_v4.enum)([
206
+ "invalid_request",
207
+ "invalid_client",
208
+ "invalid_grant",
209
+ "unauthorized_client",
210
+ "unsupported_grant_type",
211
+ "invalid_scope"
212
+ ]),
213
+ error_description: (0, import_v4.string)().optional(),
214
+ error_uri: (0, import_v4.string)().optional()
215
+ });
227
216
  var OAuthErrorResponse = (0, import_v4.object)({
228
- error: (0, import_v4.string)(),
229
- error_description: (0, import_v4.string)().optional(),
230
- })
217
+ error: (0, import_v4.string)(),
218
+ error_description: (0, import_v4.string)().optional()
219
+ });
231
220
 
232
221
  // src/actions/callback/userinfo.ts
233
222
  var getDefaultUserInfo = (profile) => {
234
- const sub = generateSecure(16)
235
- return {
236
- sub: profile?.id ?? profile?.sub ?? sub,
237
- email: profile?.email,
238
- name: profile?.name ?? profile?.username ?? profile?.nickname,
239
- image: profile?.image ?? profile?.picture,
240
- }
241
- }
223
+ const sub = generateSecure(16);
224
+ return {
225
+ sub: profile?.id ?? profile?.sub ?? sub,
226
+ email: profile?.email,
227
+ name: profile?.name ?? profile?.username ?? profile?.nickname,
228
+ image: profile?.image ?? profile?.picture
229
+ };
230
+ };
242
231
  var getUserInfo = async (oauthConfig, accessToken) => {
243
- const userinfoEndpoint = oauthConfig.userInfo
244
- try {
245
- const response = await fetch(userinfoEndpoint, {
246
- method: "GET",
247
- headers: {
248
- Accept: "application/json",
249
- Authorization: `Bearer ${accessToken}`,
250
- },
251
- })
252
- const json = await response.json()
253
- const { success, data } = OAuthErrorResponse.safeParse(json)
254
- if (success) {
255
- throw new AuthError(data.error, data?.error_description ?? "An error occurred while fetching user information.")
256
- }
257
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json)
258
- } catch (error) {
259
- throw throwAuthError(error, "Failed to retrieve userinfo")
232
+ const userinfoEndpoint = oauthConfig.userInfo;
233
+ try {
234
+ const response = await fetch(userinfoEndpoint, {
235
+ method: "GET",
236
+ headers: {
237
+ Accept: "application/json",
238
+ Authorization: `Bearer ${accessToken}`
239
+ }
240
+ });
241
+ const json = await response.json();
242
+ const { success, data } = OAuthErrorResponse.safeParse(json);
243
+ if (success) {
244
+ throw new AuthError(data.error, data?.error_description ?? "An error occurred while fetching user information.");
260
245
  }
261
- }
246
+ return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
247
+ } catch (error) {
248
+ throw throwAuthError(error, "Failed to retrieve userinfo");
249
+ }
250
+ };
262
251
 
263
252
  // src/response.ts
264
253
  var AuraResponse = class extends Response {
265
- static json(body, init) {
266
- return Response.json(body, init)
267
- }
268
- }
254
+ static json(body, init) {
255
+ return Response.json(body, init);
256
+ }
257
+ };
269
258
 
270
259
  // src/actions/callback/access-token.ts
271
260
  var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier) => {
272
- const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier })
273
- if (!parsed.success) {
274
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Invalid OAuth configuration")
275
- }
276
- const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data
277
- try {
278
- const response = await fetch(accessToken, {
279
- method: "POST",
280
- headers: {
281
- Accept: "application/json",
282
- "Content-Type": "application/x-www-form-urlencoded",
283
- },
284
- body: new URLSearchParams({
285
- client_id: clientId,
286
- client_secret: clientSecret,
287
- code: codeParsed,
288
- redirect_uri: redirectParsed,
289
- grant_type: "authorization_code",
290
- code_verifier: codeVerifier,
291
- }).toString(),
292
- })
293
- const json = await response.json()
294
- const token = OAuthAccessTokenResponse.safeParse(json)
295
- if (!token.success) {
296
- const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json)
297
- if (!success) {
298
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_GRANT, "Invalid access token response format")
299
- }
300
- throw new AuthError(data.error, data?.error_description ?? "Failed to retrieve access token")
301
- }
302
- return token.data
303
- } catch (error) {
304
- throw throwAuthError(error, "Failed to create access token")
261
+ const parsed = OAuthAccessToken.safeParse({ ...oauthConfig, redirectURI, code, codeVerifier });
262
+ if (!parsed.success) {
263
+ throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Invalid OAuth configuration");
264
+ }
265
+ const { accessToken, clientId, clientSecret, code: codeParsed, redirectURI: redirectParsed } = parsed.data;
266
+ try {
267
+ const response = await fetch(accessToken, {
268
+ method: "POST",
269
+ headers: {
270
+ Accept: "application/json",
271
+ "Content-Type": "application/x-www-form-urlencoded"
272
+ },
273
+ body: new URLSearchParams({
274
+ client_id: clientId,
275
+ client_secret: clientSecret,
276
+ code: codeParsed,
277
+ redirect_uri: redirectParsed,
278
+ grant_type: "authorization_code",
279
+ code_verifier: codeVerifier
280
+ }).toString()
281
+ });
282
+ const json = await response.json();
283
+ const token = OAuthAccessTokenResponse.safeParse(json);
284
+ if (!token.success) {
285
+ const { success, data } = OAuthAccessTokenErrorResponse.safeParse(json);
286
+ if (!success) {
287
+ throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_GRANT, "Invalid access token response format");
288
+ }
289
+ throw new AuthError(data.error, data?.error_description ?? "Failed to retrieve access token");
305
290
  }
306
- }
291
+ return token.data;
292
+ } catch (error) {
293
+ throw throwAuthError(error, "Failed to create access token");
294
+ }
295
+ };
307
296
 
308
297
  // src/cookie.ts
309
- var import_cookie = require("cookie")
298
+ var import_cookie = require("cookie");
310
299
 
311
300
  // src/assert.ts
312
301
  var isRequest = (value) => {
313
- return typeof Request !== "undefined" && value instanceof Request
314
- }
302
+ return typeof Request !== "undefined" && value instanceof Request;
303
+ };
315
304
 
316
305
  // src/cookie.ts
317
- var import_cookie2 = require("cookie")
318
- var COOKIE_NAME = "aura-auth"
306
+ var import_cookie2 = require("cookie");
307
+ var COOKIE_NAME = "aura-auth";
319
308
  var defaultCookieOptions = {
320
- httpOnly: true,
321
- sameSite: "lax",
322
- path: "/",
323
- maxAge: 60 * 60 * 24 * 15,
324
- }
309
+ httpOnly: true,
310
+ sameSite: "lax",
311
+ path: "/",
312
+ maxAge: 60 * 60 * 24 * 15
313
+ };
325
314
  var defaultStandardCookieConfig = {
326
- secure: false,
327
- httpOnly: true,
328
- prefix: "",
329
- }
315
+ secure: false,
316
+ httpOnly: true,
317
+ prefix: ""
318
+ };
330
319
  var defaultSecureCookieConfig = {
331
- secure: true,
332
- prefix: "__Secure-",
333
- }
320
+ secure: true,
321
+ prefix: "__Secure-"
322
+ };
334
323
  var defaultHostCookieConfig = {
335
- secure: true,
336
- prefix: "__Host-",
337
- path: "/",
338
- domain: void 0,
339
- }
324
+ secure: true,
325
+ prefix: "__Host-",
326
+ path: "/",
327
+ domain: void 0
328
+ };
340
329
  var expiredCookieOptions = {
341
- ...defaultCookieOptions,
342
- expires: /* @__PURE__ */ new Date(0),
343
- maxAge: 0,
344
- }
330
+ ...defaultCookieOptions,
331
+ expires: /* @__PURE__ */ new Date(0),
332
+ maxAge: 0
333
+ };
345
334
  var defineDefaultCookieOptions = (options2) => {
346
- return {
347
- name: options2?.name ?? COOKIE_NAME,
348
- prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
349
- ...defaultCookieOptions,
350
- ...options2,
351
- }
352
- }
335
+ return {
336
+ name: options2?.name ?? COOKIE_NAME,
337
+ prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
338
+ ...defaultCookieOptions,
339
+ ...options2
340
+ };
341
+ };
353
342
  var setCookie = (cookieName, value, options2) => {
354
- const { prefix, name } = defineDefaultCookieOptions(options2)
355
- const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`
356
- return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
357
- ...defaultCookieOptions,
358
- ...options2,
359
- })
360
- }
343
+ const { prefix, name } = defineDefaultCookieOptions(options2);
344
+ const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`;
345
+ return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
346
+ ...defaultCookieOptions,
347
+ ...options2
348
+ });
349
+ };
361
350
  var getCookie = (petition, cookie, options2, optional = false) => {
362
- const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ")
363
- if (!cookies) {
364
- if (optional) {
365
- return ""
366
- }
367
- throw new AuthError("invalid_request", "No cookies found. There is no active session")
351
+ const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ");
352
+ if (!cookies) {
353
+ if (optional) {
354
+ return "";
368
355
  }
369
- const { name, prefix } = defineDefaultCookieOptions(options2)
370
- const parsedCookies = (0, import_cookie.parse)(cookies)
371
- const value = parsedCookies[`${prefix}${name}.${cookie}`]
372
- if (value === void 0) {
373
- if (optional) {
374
- return ""
375
- }
376
- throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`)
356
+ throw new AuthError("invalid_request", "No cookies found. There is no active session");
357
+ }
358
+ const { name, prefix } = defineDefaultCookieOptions(options2);
359
+ const parsedCookies = (0, import_cookie.parse)(cookies);
360
+ const value = parsedCookies[`${prefix}${name}.${cookie}`];
361
+ if (value === void 0) {
362
+ if (optional) {
363
+ return "";
377
364
  }
378
- return value
379
- }
365
+ throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`);
366
+ }
367
+ return value;
368
+ };
380
369
  var createSessionCookie = async (session, cookieOptions, jose) => {
381
- try {
382
- const encoded = await jose.encodeJWT(session)
383
- return setCookie("sessionToken", encoded, cookieOptions)
384
- } catch (error) {
385
- throw new AuthError("server_error", "Failed to create session cookie", { cause: error })
386
- }
387
- }
370
+ try {
371
+ const encoded = await jose.encodeJWT(session);
372
+ return setCookie("sessionToken", encoded, cookieOptions);
373
+ } catch (error) {
374
+ throw new AuthError("server_error", "Failed to create session cookie", { cause: error });
375
+ }
376
+ };
388
377
  var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
389
- const name = cookieOptions.name ?? COOKIE_NAME
390
- const isSecure = trustedProxyHeaders
391
- ? request.url.startsWith("https://") ||
392
- request.headers.get("X-Forwarded-Proto") === "https" ||
393
- request.headers.get("Forwarded")?.includes("proto=https")
394
- : request.url.startsWith("https://")
395
- if (!cookieOptions.options?.httpOnly) {
396
- console.warn(
397
- "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
398
- )
378
+ const name = cookieOptions.name ?? COOKIE_NAME;
379
+ const isSecure = trustedProxyHeaders ? request.url.startsWith("https://") || request.headers.get("X-Forwarded-Proto") === "https" || request.headers.get("Forwarded")?.includes("proto=https") : request.url.startsWith("https://");
380
+ if (!cookieOptions.options?.httpOnly) {
381
+ console.warn(
382
+ "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
383
+ );
384
+ }
385
+ if (cookieOptions.options?.domain === "*") {
386
+ console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.");
387
+ }
388
+ if (!isSecure) {
389
+ const options2 = cookieOptions.options;
390
+ if (options2?.secure) {
391
+ console.warn(
392
+ "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
393
+ );
399
394
  }
400
- if (cookieOptions.options?.domain === "*") {
401
- console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.")
395
+ if (options2?.sameSite == "none") {
396
+ console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.");
402
397
  }
403
- if (!isSecure) {
404
- const options2 = cookieOptions.options
405
- if (options2?.secure) {
406
- console.warn(
407
- "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
408
- )
409
- }
410
- if (options2?.sameSite == "none") {
411
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.")
412
- }
413
- if (process.env.NODE_ENV === "production") {
414
- console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.")
415
- }
416
- return {
417
- ...defaultCookieOptions,
418
- ...cookieOptions.options,
419
- sameSite: options2?.sameSite === "none" ? "lax" : (options2?.sameSite ?? "lax"),
420
- ...defaultStandardCookieConfig,
421
- name,
422
- }
398
+ if (process.env.NODE_ENV === "production") {
399
+ console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.");
423
400
  }
424
- return cookieOptions.strategy === "host"
425
- ? {
426
- ...defaultCookieOptions,
427
- ...cookieOptions.options,
428
- ...defaultHostCookieConfig,
429
- name,
430
- }
431
- : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name }
432
- }
401
+ return {
402
+ ...defaultCookieOptions,
403
+ ...cookieOptions.options,
404
+ sameSite: options2?.sameSite === "none" ? "lax" : options2?.sameSite ?? "lax",
405
+ ...defaultStandardCookieConfig,
406
+ name
407
+ };
408
+ }
409
+ return cookieOptions.strategy === "host" ? {
410
+ ...defaultCookieOptions,
411
+ ...cookieOptions.options,
412
+ ...defaultHostCookieConfig,
413
+ name
414
+ } : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name };
415
+ };
433
416
  var expireCookie = (name, options2) => {
434
- return setCookie(name, "", { ...options2, ...expiredCookieOptions })
435
- }
417
+ return setCookie(name, "", { ...options2, ...expiredCookieOptions });
418
+ };
436
419
 
437
420
  // src/actions/callback/callback.ts
438
421
  var callbackConfig = (oauth) => {
439
- return (0, import_router2.createEndpointConfig)("/callback/:oauth", {
440
- schemas: {
441
- searchParams: OAuthAuthorizationResponse,
442
- params: import_zod.default.object({
443
- oauth: import_zod.default.enum(Object.keys(oauth)),
444
- }),
445
- },
446
- middlewares: [
447
- (ctx) => {
448
- const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams)
449
- if (response.success) {
450
- const { error, error_description } = response.data
451
- throw new AuthError(error, error_description ?? "OAuth Authorization Error")
452
- }
453
- return ctx
454
- },
455
- ],
456
- })
457
- }
422
+ return (0, import_router2.createEndpointConfig)("/callback/:oauth", {
423
+ schemas: {
424
+ searchParams: OAuthAuthorizationResponse,
425
+ params: import_zod.default.object({
426
+ oauth: import_zod.default.enum(Object.keys(oauth))
427
+ })
428
+ },
429
+ middlewares: [
430
+ (ctx) => {
431
+ const response = OAuthAuthorizationErrorResponse.safeParse(ctx.searchParams);
432
+ if (response.success) {
433
+ const { error, error_description } = response.data;
434
+ throw new AuthError(error, error_description ?? "OAuth Authorization Error");
435
+ }
436
+ return ctx;
437
+ }
438
+ ]
439
+ });
440
+ };
458
441
  var callbackAction = (oauth) => {
459
- return (0, import_router2.createEndpoint)(
460
- "GET",
461
- "/callback/:oauth",
462
- async (ctx) => {
463
- const {
464
- request,
465
- params: { oauth: oauth2 },
466
- searchParams: { code, state },
467
- context: { oauth: providers, cookies, jose, trustedProxyHeaders },
468
- } = ctx
469
- try {
470
- const oauthConfig = providers[oauth2]
471
- const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders)
472
- const cookieState = getCookie(request, "state", cookieOptions)
473
- const cookieRedirectTo = getCookie(request, "redirect_to", cookieOptions)
474
- const cookieRedirectURI = getCookie(request, "redirect_uri", cookieOptions)
475
- const codeVerifier = getCookie(request, "code_verifier", cookieOptions)
476
- if (!equals(cookieState, state)) {
477
- throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Mismatching state")
478
- }
479
- const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier)
480
- const sanitized = sanitizeURL(cookieRedirectTo)
481
- if (!isValidRelativePath(sanitized)) {
482
- throw new AuthError(
483
- ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST,
484
- "Invalid redirect path. Potential open redirect attack detected."
485
- )
486
- }
487
- const headers = new Headers(cacheControl)
488
- headers.set("Location", sanitized)
489
- const userInfo = await getUserInfo(oauthConfig, accessToken.access_token)
490
- const sessionCookie = await createSessionCookie(userInfo, cookieOptions, jose)
491
- const csrfToken = await createCSRF(jose)
492
- const csrfCookie = setCookie(
493
- "csrfToken",
494
- csrfToken,
495
- secureCookieOptions(
496
- request,
497
- {
498
- ...cookies,
499
- strategy: "host",
500
- },
501
- trustedProxyHeaders
502
- )
503
- )
504
- headers.set("Set-Cookie", sessionCookie)
505
- headers.append("Set-Cookie", expireCookie("state", cookieOptions))
506
- headers.append("Set-Cookie", expireCookie("redirect_uri", cookieOptions))
507
- headers.append("Set-Cookie", expireCookie("redirect_to", cookieOptions))
508
- headers.append("Set-Cookie", expireCookie("code_verifier", cookieOptions))
509
- headers.append("Set-Cookie", csrfCookie)
510
- return Response.json({ oauth: oauth2 }, { status: 302, headers })
511
- } catch (error) {
512
- if (isAuthError(error)) {
513
- const { type, message } = error
514
- return AuraResponse.json(
515
- { error: type, error_description: message },
516
- { status: import_router2.statusCode.BAD_REQUEST }
517
- )
518
- }
519
- return AuraResponse.json(
520
- {
521
- error: ERROR_RESPONSE.ACCESS_TOKEN.INVALID_CLIENT,
522
- error_description: "An unexpected error occurred",
523
- },
524
- { status: import_router2.statusCode.INTERNAL_SERVER_ERROR }
525
- )
526
- }
527
- },
528
- callbackConfig(oauth)
529
- )
530
- }
442
+ return (0, import_router2.createEndpoint)(
443
+ "GET",
444
+ "/callback/:oauth",
445
+ async (ctx) => {
446
+ const {
447
+ request,
448
+ params: { oauth: oauth2 },
449
+ searchParams: { code, state },
450
+ context: { oauth: providers, cookies, jose, trustedProxyHeaders }
451
+ } = ctx;
452
+ try {
453
+ const oauthConfig = providers[oauth2];
454
+ const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders);
455
+ const cookieState = getCookie(request, "state", cookieOptions);
456
+ const cookieRedirectTo = getCookie(request, "redirect_to", cookieOptions);
457
+ const cookieRedirectURI = getCookie(request, "redirect_uri", cookieOptions);
458
+ const codeVerifier = getCookie(request, "code_verifier", cookieOptions);
459
+ if (!equals(cookieState, state)) {
460
+ throw new AuthError(ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST, "Mismatching state");
461
+ }
462
+ const accessToken = await createAccessToken(oauthConfig, cookieRedirectURI, code, codeVerifier);
463
+ const sanitized = sanitizeURL(cookieRedirectTo);
464
+ if (!isValidRelativePath(sanitized)) {
465
+ throw new AuthError(
466
+ ERROR_RESPONSE.ACCESS_TOKEN.INVALID_REQUEST,
467
+ "Invalid redirect path. Potential open redirect attack detected."
468
+ );
469
+ }
470
+ const headers = new Headers(cacheControl);
471
+ headers.set("Location", sanitized);
472
+ const userInfo = await getUserInfo(oauthConfig, accessToken.access_token);
473
+ const sessionCookie = await createSessionCookie(userInfo, cookieOptions, jose);
474
+ const csrfToken = await createCSRF(jose);
475
+ const csrfCookie = setCookie(
476
+ "csrfToken",
477
+ csrfToken,
478
+ secureCookieOptions(
479
+ request,
480
+ {
481
+ ...cookies,
482
+ strategy: "host"
483
+ },
484
+ trustedProxyHeaders
485
+ )
486
+ );
487
+ headers.set("Set-Cookie", sessionCookie);
488
+ headers.append("Set-Cookie", expireCookie("state", cookieOptions));
489
+ headers.append("Set-Cookie", expireCookie("redirect_uri", cookieOptions));
490
+ headers.append("Set-Cookie", expireCookie("redirect_to", cookieOptions));
491
+ headers.append("Set-Cookie", expireCookie("code_verifier", cookieOptions));
492
+ headers.append("Set-Cookie", csrfCookie);
493
+ return Response.json({ oauth: oauth2 }, { status: 302, headers });
494
+ } catch (error) {
495
+ if (isAuthError(error)) {
496
+ const { type, message } = error;
497
+ return AuraResponse.json(
498
+ { error: type, error_description: message },
499
+ { status: import_router2.statusCode.BAD_REQUEST }
500
+ );
501
+ }
502
+ return AuraResponse.json(
503
+ {
504
+ error: ERROR_RESPONSE.ACCESS_TOKEN.INVALID_CLIENT,
505
+ error_description: "An unexpected error occurred"
506
+ },
507
+ { status: import_router2.statusCode.INTERNAL_SERVER_ERROR }
508
+ );
509
+ }
510
+ },
511
+ callbackConfig(oauth)
512
+ );
513
+ };
531
514
  // Annotate the CommonJS export names for ESM import in node:
532
- 0 &&
533
- (module.exports = {
534
- callbackAction,
535
- })
515
+ 0 && (module.exports = {
516
+ callbackAction
517
+ });