@aura-stack/auth 0.1.0-rc.7 → 0.1.0-rc.9

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 (117) hide show
  1. package/dist/@types/index.cjs +15 -15
  2. package/dist/@types/index.d.ts +31 -7
  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 +20 -15
  11. package/dist/actions/callback/access-token.js +4 -8
  12. package/dist/actions/callback/callback.cjs +455 -437
  13. package/dist/actions/callback/callback.d.ts +12 -10
  14. package/dist/actions/callback/callback.js +12 -16
  15. package/dist/actions/callback/userinfo.cjs +134 -131
  16. package/dist/actions/callback/userinfo.d.ts +9 -9
  17. package/dist/actions/callback/userinfo.js +6 -10
  18. package/dist/actions/csrfToken/csrfToken.cjs +171 -162
  19. package/dist/actions/csrfToken/csrfToken.d.ts +3 -3
  20. package/dist/actions/csrfToken/csrfToken.js +8 -12
  21. package/dist/actions/index.cjs +773 -746
  22. package/dist/actions/index.d.ts +13 -13
  23. package/dist/actions/index.js +18 -34
  24. package/dist/actions/session/session.cjs +155 -149
  25. package/dist/actions/session/session.d.ts +3 -3
  26. package/dist/actions/session/session.js +7 -11
  27. package/dist/actions/signIn/authorization.cjs +249 -231
  28. package/dist/actions/signIn/authorization.d.ts +18 -12
  29. package/dist/actions/signIn/authorization.js +6 -16
  30. package/dist/actions/signIn/signIn.cjs +423 -396
  31. package/dist/actions/signIn/signIn.d.ts +10 -10
  32. package/dist/actions/signIn/signIn.js +10 -14
  33. package/dist/actions/signOut/signOut.cjs +440 -417
  34. package/dist/actions/signOut/signOut.d.ts +3 -3
  35. package/dist/actions/signOut/signOut.js +11 -15
  36. package/dist/assert.cjs +36 -35
  37. package/dist/assert.d.ts +4 -4
  38. package/dist/assert.js +2 -10
  39. package/dist/chunk-256KIVJL.js +96 -85
  40. package/dist/chunk-42XB3YCW.js +17 -19
  41. package/dist/chunk-6SM22VVJ.js +10 -13
  42. package/dist/chunk-CAKJT3KS.js +69 -84
  43. package/dist/chunk-E3OXBRYF.js +17 -19
  44. package/dist/chunk-EBPE35JT.js +26 -28
  45. package/dist/chunk-FIPU4MLT.js +16 -18
  46. package/dist/chunk-FJUDBLCP.js +43 -50
  47. package/dist/chunk-FKRDCWBF.js +17 -19
  48. package/dist/chunk-GZU3RBTB.js +40 -51
  49. package/dist/chunk-HGJ4TXY4.js +100 -132
  50. package/dist/chunk-HMRKN75I.js +63 -63
  51. package/dist/chunk-IKHPGFCW.js +9 -11
  52. package/dist/chunk-JAPMIE6S.js +5 -7
  53. package/dist/chunk-KRNOMBXQ.js +17 -19
  54. package/dist/chunk-LLR722CL.js +70 -91
  55. package/dist/chunk-RLT4RFKV.js +30 -39
  56. package/dist/chunk-SJPDVKUS.js +88 -107
  57. package/dist/chunk-SMQO5WD7.js +16 -26
  58. package/dist/chunk-STHEPPUZ.js +6 -8
  59. package/dist/chunk-UJJ7R56J.js +37 -47
  60. package/dist/chunk-UTDLUEEG.js +25 -0
  61. package/dist/chunk-VFTYH33W.js +37 -54
  62. package/dist/chunk-XXJKNKGQ.js +23 -33
  63. package/dist/chunk-ZV4BH47P.js +134 -132
  64. package/dist/cookie.cjs +175 -169
  65. package/dist/cookie.d.ts +51 -23
  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 +8 -15
  70. package/dist/headers.cjs +28 -28
  71. package/dist/headers.d.ts +2 -2
  72. package/dist/headers.js +2 -6
  73. package/dist/index-DpfbvTZ_.d.ts +298 -249
  74. package/dist/index.cjs +969 -933
  75. package/dist/index.d.ts +31 -10
  76. package/dist/index.js +50 -70
  77. package/dist/jose.cjs +67 -52
  78. package/dist/jose.d.ts +8 -8
  79. package/dist/jose.js +5 -9
  80. package/dist/oauth/bitbucket.cjs +38 -38
  81. package/dist/oauth/bitbucket.d.ts +7 -7
  82. package/dist/oauth/bitbucket.js +2 -6
  83. package/dist/oauth/discord.cjs +48 -48
  84. package/dist/oauth/discord.d.ts +7 -7
  85. package/dist/oauth/discord.js +2 -6
  86. package/dist/oauth/figma.cjs +39 -39
  87. package/dist/oauth/figma.d.ts +7 -7
  88. package/dist/oauth/figma.js +2 -6
  89. package/dist/oauth/github.cjs +31 -31
  90. package/dist/oauth/github.d.ts +7 -7
  91. package/dist/oauth/github.js +2 -6
  92. package/dist/oauth/gitlab.cjs +39 -39
  93. package/dist/oauth/gitlab.d.ts +7 -7
  94. package/dist/oauth/gitlab.js +2 -6
  95. package/dist/oauth/index.cjs +180 -180
  96. package/dist/oauth/index.d.ts +26 -7
  97. package/dist/oauth/index.js +9 -36
  98. package/dist/oauth/spotify.cjs +39 -39
  99. package/dist/oauth/spotify.d.ts +7 -7
  100. package/dist/oauth/spotify.js +2 -6
  101. package/dist/oauth/x.cjs +39 -39
  102. package/dist/oauth/x.d.ts +7 -7
  103. package/dist/oauth/x.js +2 -6
  104. package/dist/response.cjs +27 -27
  105. package/dist/response.d.ts +2 -2
  106. package/dist/response.js +2 -6
  107. package/dist/schemas.cjs +91 -91
  108. package/dist/schemas.d.ts +126 -93
  109. package/dist/schemas.js +18 -18
  110. package/dist/secure.cjs +98 -95
  111. package/dist/secure.d.ts +17 -17
  112. package/dist/secure.js +4 -18
  113. package/dist/utils.cjs +132 -119
  114. package/dist/utils.d.ts +26 -11
  115. package/dist/utils.js +21 -21
  116. package/package.json +1 -1
  117. package/dist/chunk-X7M4CQTN.js +0 -25
@@ -1,517 +1,535 @@
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)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
9
+ for (var name in all) __defProp(target, name, { get: all[name], enumerable: true })
10
+ }
12
11
  var __copyProps = (to, from, except, desc) => {
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);
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)
29
31
 
30
32
  // src/actions/callback/callback.ts
31
- var callback_exports = {};
33
+ var callback_exports = {}
32
34
  __export(callback_exports, {
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");
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")
38
40
 
39
41
  // src/secure.ts
40
- var import_node_crypto = __toESM(require("crypto"), 1);
42
+ var import_node_crypto = __toESM(require("crypto"), 1)
41
43
 
42
44
  // src/utils.ts
43
- var import_router = require("@aura-stack/router");
45
+ var import_router = require("@aura-stack/router")
44
46
 
45
47
  // src/error.ts
46
48
  var AuthError = class extends Error {
47
- constructor(type, message) {
48
- super(message);
49
- this.type = type;
50
- this.name = "AuthError";
51
- }
52
- };
49
+ constructor(type, message) {
50
+ super(message)
51
+ this.type = type
52
+ this.name = "AuthError"
53
+ }
54
+ }
53
55
  var isAuthError = (error) => {
54
- return error instanceof AuthError;
55
- };
56
+ return error instanceof AuthError
57
+ }
56
58
  var throwAuthError = (error, message) => {
57
- if (error instanceof Error) {
58
- if (isAuthError(error)) {
59
- throw error;
59
+ if (error instanceof Error) {
60
+ if (isAuthError(error)) {
61
+ throw error
62
+ }
63
+ throw new AuthError("invalid_request", error.message ?? message)
60
64
  }
61
- throw new AuthError("invalid_request", error.message ?? message);
62
- }
63
- };
65
+ }
64
66
  var ERROR_RESPONSE = {
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
- };
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
+ }
83
85
 
84
86
  // src/utils.ts
85
87
  var equals = (a, b) => {
86
- if (a === null || b === null || a === void 0 || b === void 0) return false;
87
- return a === b;
88
- };
88
+ if (a === null || b === null || a === void 0 || b === void 0) return false
89
+ return a === b
90
+ }
89
91
  var sanitizeURL = (url2) => {
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(/\/+$/, "");
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()
116
131
  }
117
- return sanitized;
118
- } catch {
119
- return url2.trim();
120
- }
121
- };
132
+ }
122
133
  var isValidRelativePath = (path) => {
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
- };
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
+ }
130
141
 
131
142
  // src/secure.ts
132
143
  var generateSecure = (length = 32) => {
133
- return import_node_crypto.default.randomBytes(length).toString("base64url");
134
- };
144
+ return import_node_crypto.default.randomBytes(length).toString("base64url")
145
+ }
135
146
  var createCSRF = async (jose, csrfCookie) => {
136
- try {
137
- const token = generateSecure(32);
138
- if (csrfCookie) {
139
- await jose.verifyJWS(csrfCookie);
140
- return 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 })
141
157
  }
142
- return jose.signJWS({ token });
143
- } catch {
144
- const token = generateSecure(32);
145
- return jose.signJWS({ token });
146
- }
147
- };
158
+ }
148
159
 
149
160
  // src/headers.ts
150
161
  var cacheControl = {
151
- "Cache-Control": "no-store",
152
- Pragma: "no-cache",
153
- Expires: "0",
154
- Vary: "Cookie"
155
- };
162
+ "Cache-Control": "no-store",
163
+ Pragma: "no-cache",
164
+ Expires: "0",
165
+ Vary: "Cookie",
166
+ }
156
167
 
157
168
  // src/schemas.ts
158
- var import_v4 = require("zod/v4");
169
+ var import_v4 = require("zod/v4")
159
170
  var OAuthProviderConfigSchema = (0, import_v4.object)({
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
- });
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
+ })
168
179
  var OAuthAuthorization = OAuthProviderConfigSchema.extend({
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
- });
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
+ })
174
185
  var OAuthAuthorizationResponse = (0, import_v4.object)({
175
- state: (0, import_v4.string)(),
176
- code: (0, import_v4.string)()
177
- });
186
+ state: (0, import_v4.string)(),
187
+ code: (0, import_v4.string)(),
188
+ })
178
189
  var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
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
- });
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
+ })
192
203
  var OAuthAccessToken = OAuthProviderConfigSchema.extend({
193
- redirectURI: (0, import_v4.string)(),
194
- code: (0, import_v4.string)(),
195
- codeVerifier: (0, import_v4.string)().min(43).max(128)
196
- });
204
+ redirectURI: (0, import_v4.string)(),
205
+ code: (0, import_v4.string)(),
206
+ codeVerifier: (0, import_v4.string)().min(43).max(128),
207
+ })
197
208
  var OAuthAccessTokenResponse = (0, import_v4.object)({
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
- });
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
+ })
204
215
  var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
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
- });
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
+ })
216
227
  var OAuthErrorResponse = (0, import_v4.object)({
217
- error: (0, import_v4.string)(),
218
- error_description: (0, import_v4.string)().optional()
219
- });
228
+ error: (0, import_v4.string)(),
229
+ error_description: (0, import_v4.string)().optional(),
230
+ })
220
231
 
221
232
  // src/actions/callback/userinfo.ts
222
233
  var getDefaultUserInfo = (profile) => {
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
- };
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
+ }
231
242
  var getUserInfo = async (oauthConfig, accessToken) => {
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.");
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")
245
260
  }
246
- return oauthConfig?.profile ? oauthConfig.profile(json) : getDefaultUserInfo(json);
247
- } catch (error) {
248
- throw throwAuthError(error, "Failed to retrieve userinfo");
249
- }
250
- };
261
+ }
251
262
 
252
263
  // src/response.ts
253
264
  var AuraResponse = class extends Response {
254
- static json(body, init) {
255
- return Response.json(body, init);
256
- }
257
- };
265
+ static json(body, init) {
266
+ return Response.json(body, init)
267
+ }
268
+ }
258
269
 
259
270
  // src/actions/callback/access-token.ts
260
271
  var createAccessToken = async (oauthConfig, redirectURI, code, codeVerifier) => {
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");
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")
290
305
  }
291
- return token.data;
292
- } catch (error) {
293
- throw throwAuthError(error, "Failed to create access token");
294
- }
295
- };
306
+ }
296
307
 
297
308
  // src/cookie.ts
298
- var import_cookie = require("cookie");
309
+ var import_cookie = require("cookie")
299
310
 
300
311
  // src/assert.ts
301
312
  var isRequest = (value) => {
302
- return typeof Request !== "undefined" && value instanceof Request;
303
- };
313
+ return typeof Request !== "undefined" && value instanceof Request
314
+ }
304
315
 
305
316
  // src/cookie.ts
306
- var import_cookie2 = require("cookie");
307
- var COOKIE_NAME = "aura-auth";
317
+ var import_cookie2 = require("cookie")
318
+ var COOKIE_NAME = "aura-auth"
308
319
  var defaultCookieOptions = {
309
- httpOnly: true,
310
- sameSite: "lax",
311
- path: "/",
312
- maxAge: 60 * 60 * 24 * 15
313
- };
320
+ httpOnly: true,
321
+ sameSite: "lax",
322
+ path: "/",
323
+ maxAge: 60 * 60 * 24 * 15,
324
+ }
314
325
  var defaultStandardCookieConfig = {
315
- secure: false,
316
- httpOnly: true,
317
- prefix: ""
318
- };
326
+ secure: false,
327
+ httpOnly: true,
328
+ prefix: "",
329
+ }
319
330
  var defaultSecureCookieConfig = {
320
- secure: true,
321
- prefix: "__Secure-"
322
- };
331
+ secure: true,
332
+ prefix: "__Secure-",
333
+ }
323
334
  var defaultHostCookieConfig = {
324
- secure: true,
325
- prefix: "__Host-",
326
- path: "/",
327
- domain: void 0
328
- };
335
+ secure: true,
336
+ prefix: "__Host-",
337
+ path: "/",
338
+ domain: void 0,
339
+ }
329
340
  var expiredCookieOptions = {
330
- ...defaultCookieOptions,
331
- expires: /* @__PURE__ */ new Date(0),
332
- maxAge: 0
333
- };
334
- var defineDefaultCookieOptions = (options2) => {
335
- return {
336
- name: options2?.name ?? COOKIE_NAME,
337
- prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
338
341
  ...defaultCookieOptions,
339
- ...options2
340
- };
341
- };
342
+ expires: /* @__PURE__ */ new Date(0),
343
+ maxAge: 0,
344
+ }
345
+ var defineDefaultCookieOptions = (options2) => {
346
+ return {
347
+ name: options2?.name ?? COOKIE_NAME,
348
+ prefix: options2?.prefix ?? (options2?.secure ? "__Secure-" : ""),
349
+ ...defaultCookieOptions,
350
+ ...options2,
351
+ }
352
+ }
342
353
  var setCookie = (cookieName, value, options2) => {
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
- };
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
+ }
350
361
  var getCookie = (petition, cookie, options2, optional = false) => {
351
- const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ");
352
- if (!cookies) {
353
- if (optional) {
354
- return "";
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")
355
368
  }
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 "";
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`)
364
377
  }
365
- throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`);
366
- }
367
- return value;
368
- };
378
+ return value
379
+ }
369
380
  var createSessionCookie = async (session, cookieOptions, jose) => {
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
- };
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
+ }
377
388
  var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
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
- );
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
+ )
394
399
  }
395
- if (options2?.sameSite == "none") {
396
- console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.");
400
+ if (cookieOptions.options?.domain === "*") {
401
+ console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.")
397
402
  }
398
- if (process.env.NODE_ENV === "production") {
399
- console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.");
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
+ }
400
423
  }
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
- };
424
+ return cookieOptions.strategy === "host"
425
+ ? {
426
+ ...defaultCookieOptions,
427
+ ...cookieOptions.options,
428
+ ...defaultHostCookieConfig,
429
+ name,
430
+ }
431
+ : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name }
432
+ }
416
433
  var expireCookie = (name, options2) => {
417
- return setCookie(name, "", { ...options2, ...expiredCookieOptions });
418
- };
434
+ return setCookie(name, "", { ...options2, ...expiredCookieOptions })
435
+ }
419
436
 
420
437
  // src/actions/callback/callback.ts
421
438
  var callbackConfig = (oauth) => {
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
- };
441
- var callbackAction = (oauth) => {
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"
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
483
454
  },
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
- };
455
+ ],
456
+ })
457
+ }
458
+ 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
+ }
514
531
  // Annotate the CommonJS export names for ESM import in node:
515
- 0 && (module.exports = {
516
- callbackAction
517
- });
532
+ 0 &&
533
+ (module.exports = {
534
+ callbackAction,
535
+ })