@aura-stack/auth 0.1.0-rc.1

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 (141) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -0
  3. package/dist/@types/index.cjs +18 -0
  4. package/dist/@types/index.d.cts +9 -0
  5. package/dist/@types/index.d.ts +9 -0
  6. package/dist/@types/index.js +1 -0
  7. package/dist/@types/router.d.cjs +1 -0
  8. package/dist/@types/router.d.d.cts +16 -0
  9. package/dist/@types/router.d.d.ts +16 -0
  10. package/dist/@types/router.d.js +0 -0
  11. package/dist/@types/utility.cjs +18 -0
  12. package/dist/@types/utility.d.cts +6 -0
  13. package/dist/@types/utility.d.ts +6 -0
  14. package/dist/@types/utility.js +1 -0
  15. package/dist/actions/callback/access-token.cjs +170 -0
  16. package/dist/actions/callback/access-token.d.cts +30 -0
  17. package/dist/actions/callback/access-token.d.ts +30 -0
  18. package/dist/actions/callback/access-token.js +8 -0
  19. package/dist/actions/callback/callback.cjs +517 -0
  20. package/dist/actions/callback/callback.d.cts +13 -0
  21. package/dist/actions/callback/callback.d.ts +13 -0
  22. package/dist/actions/callback/callback.js +16 -0
  23. package/dist/actions/callback/userinfo.cjs +165 -0
  24. package/dist/actions/callback/userinfo.d.cts +22 -0
  25. package/dist/actions/callback/userinfo.d.ts +22 -0
  26. package/dist/actions/callback/userinfo.js +10 -0
  27. package/dist/actions/csrfToken/csrfToken.cjs +207 -0
  28. package/dist/actions/csrfToken/csrfToken.d.cts +5 -0
  29. package/dist/actions/csrfToken/csrfToken.d.ts +5 -0
  30. package/dist/actions/csrfToken/csrfToken.js +12 -0
  31. package/dist/actions/index.cjs +864 -0
  32. package/dist/actions/index.d.cts +14 -0
  33. package/dist/actions/index.d.ts +14 -0
  34. package/dist/actions/index.js +34 -0
  35. package/dist/actions/session/session.cjs +191 -0
  36. package/dist/actions/session/session.d.cts +5 -0
  37. package/dist/actions/session/session.d.ts +5 -0
  38. package/dist/actions/session/session.js +11 -0
  39. package/dist/actions/signIn/authorization.cjs +274 -0
  40. package/dist/actions/signIn/authorization.d.cts +45 -0
  41. package/dist/actions/signIn/authorization.d.ts +45 -0
  42. package/dist/actions/signIn/authorization.js +16 -0
  43. package/dist/actions/signIn/signIn.cjs +469 -0
  44. package/dist/actions/signIn/signIn.d.cts +13 -0
  45. package/dist/actions/signIn/signIn.d.ts +13 -0
  46. package/dist/actions/signIn/signIn.js +14 -0
  47. package/dist/actions/signOut/signOut.cjs +490 -0
  48. package/dist/actions/signOut/signOut.d.cts +8 -0
  49. package/dist/actions/signOut/signOut.d.ts +8 -0
  50. package/dist/actions/signOut/signOut.js +15 -0
  51. package/dist/assert.cjs +44 -0
  52. package/dist/assert.d.ts +5 -0
  53. package/dist/assert.js +10 -0
  54. package/dist/chunk-256KIVJL.js +99 -0
  55. package/dist/chunk-42XB3YCW.js +22 -0
  56. package/dist/chunk-6SM22VVJ.js +18 -0
  57. package/dist/chunk-CAKJT3KS.js +92 -0
  58. package/dist/chunk-E3OXBRYF.js +22 -0
  59. package/dist/chunk-EBPE35JT.js +31 -0
  60. package/dist/chunk-FIPU4MLT.js +21 -0
  61. package/dist/chunk-FJUDBLCP.js +59 -0
  62. package/dist/chunk-FKRDCWBF.js +22 -0
  63. package/dist/chunk-GZU3RBTB.js +62 -0
  64. package/dist/chunk-HGJ4TXY4.js +137 -0
  65. package/dist/chunk-HMRKN75I.js +74 -0
  66. package/dist/chunk-IKHPGFCW.js +14 -0
  67. package/dist/chunk-ITQ7352M.js +0 -0
  68. package/dist/chunk-JAPMIE6S.js +10 -0
  69. package/dist/chunk-KRNOMBXQ.js +22 -0
  70. package/dist/chunk-LLR722CL.js +96 -0
  71. package/dist/chunk-PG7UYFG5.js +0 -0
  72. package/dist/chunk-RLT4RFKV.js +45 -0
  73. package/dist/chunk-SJPDVKUS.js +112 -0
  74. package/dist/chunk-SMQO5WD7.js +30 -0
  75. package/dist/chunk-STHEPPUZ.js +11 -0
  76. package/dist/chunk-UJJ7R56J.js +52 -0
  77. package/dist/chunk-VFTYH33W.js +61 -0
  78. package/dist/chunk-X7M4CQTN.js +25 -0
  79. package/dist/chunk-XXJKNKGQ.js +37 -0
  80. package/dist/chunk-ZV4BH47P.js +154 -0
  81. package/dist/cookie.cjs +201 -0
  82. package/dist/cookie.d.ts +95 -0
  83. package/dist/cookie.js +36 -0
  84. package/dist/error.cjs +88 -0
  85. package/dist/error.d.ts +64 -0
  86. package/dist/error.js +16 -0
  87. package/dist/headers.cjs +35 -0
  88. package/dist/headers.d.ts +9 -0
  89. package/dist/headers.js +6 -0
  90. package/dist/index-CGRZ0wrw.d.ts +530 -0
  91. package/dist/index.cjs +1089 -0
  92. package/dist/index.d.ts +43 -0
  93. package/dist/index.js +75 -0
  94. package/dist/jose.cjs +68 -0
  95. package/dist/jose.d.ts +20 -0
  96. package/dist/jose.js +9 -0
  97. package/dist/oauth/bitbucket.cjs +45 -0
  98. package/dist/oauth/bitbucket.d.cts +9 -0
  99. package/dist/oauth/bitbucket.d.ts +9 -0
  100. package/dist/oauth/bitbucket.js +6 -0
  101. package/dist/oauth/discord.cjs +55 -0
  102. package/dist/oauth/discord.d.cts +9 -0
  103. package/dist/oauth/discord.d.ts +9 -0
  104. package/dist/oauth/discord.js +6 -0
  105. package/dist/oauth/figma.cjs +46 -0
  106. package/dist/oauth/figma.d.cts +9 -0
  107. package/dist/oauth/figma.d.ts +9 -0
  108. package/dist/oauth/figma.js +6 -0
  109. package/dist/oauth/github.cjs +38 -0
  110. package/dist/oauth/github.d.cts +9 -0
  111. package/dist/oauth/github.d.ts +9 -0
  112. package/dist/oauth/github.js +6 -0
  113. package/dist/oauth/gitlab.cjs +46 -0
  114. package/dist/oauth/gitlab.d.cts +9 -0
  115. package/dist/oauth/gitlab.d.ts +9 -0
  116. package/dist/oauth/gitlab.js +6 -0
  117. package/dist/oauth/index.cjs +213 -0
  118. package/dist/oauth/index.d.cts +9 -0
  119. package/dist/oauth/index.d.ts +9 -0
  120. package/dist/oauth/index.js +36 -0
  121. package/dist/oauth/spotify.cjs +46 -0
  122. package/dist/oauth/spotify.d.cts +9 -0
  123. package/dist/oauth/spotify.d.ts +9 -0
  124. package/dist/oauth/spotify.js +6 -0
  125. package/dist/oauth/x.cjs +46 -0
  126. package/dist/oauth/x.d.cts +9 -0
  127. package/dist/oauth/x.d.ts +9 -0
  128. package/dist/oauth/x.js +6 -0
  129. package/dist/response.cjs +34 -0
  130. package/dist/response.d.ts +10 -0
  131. package/dist/response.js +6 -0
  132. package/dist/schemas.cjs +105 -0
  133. package/dist/schemas.d.ts +130 -0
  134. package/dist/schemas.js +20 -0
  135. package/dist/secure.cjs +120 -0
  136. package/dist/secure.d.ts +43 -0
  137. package/dist/secure.js +18 -0
  138. package/dist/utils.cjs +141 -0
  139. package/dist/utils.d.ts +45 -0
  140. package/dist/utils.js +23 -0
  141. package/package.json +70 -0
@@ -0,0 +1,14 @@
1
+ export { signInAction } from './signIn/signIn.cjs';
2
+ export { callbackAction } from './callback/callback.cjs';
3
+ export { sessionAction } from './session/session.cjs';
4
+ export { signOutAction } from './signOut/signOut.cjs';
5
+ export { csrfTokenAction } from './csrfToken/csrfToken.cjs';
6
+ import '@aura-stack/router';
7
+ import '../index-B1vDUGwh.cjs';
8
+ import 'zod/v4';
9
+ import '../jose.cjs';
10
+ import '@aura-stack/jose/jose';
11
+ import '../schemas.cjs';
12
+ import 'zod/v4/core';
13
+ import 'cookie';
14
+ import '../@types/utility.cjs';
@@ -0,0 +1,14 @@
1
+ export { signInAction } from './signIn/signIn.js';
2
+ export { callbackAction } from './callback/callback.js';
3
+ export { sessionAction } from './session/session.js';
4
+ export { signOutAction } from './signOut/signOut.js';
5
+ export { csrfTokenAction } from './csrfToken/csrfToken.js';
6
+ import '@aura-stack/router';
7
+ import '../index-CGRZ0wrw.js';
8
+ import 'zod/v4';
9
+ import '../jose.js';
10
+ import '@aura-stack/jose/jose';
11
+ import '../schemas.js';
12
+ import 'zod/v4/core';
13
+ import 'cookie';
14
+ import '../@types/utility.js';
@@ -0,0 +1,34 @@
1
+ import "../chunk-ITQ7352M.js";
2
+ import {
3
+ csrfTokenAction
4
+ } from "../chunk-SMQO5WD7.js";
5
+ import {
6
+ sessionAction
7
+ } from "../chunk-XXJKNKGQ.js";
8
+ import {
9
+ signInAction
10
+ } from "../chunk-LLR722CL.js";
11
+ import {
12
+ signOutAction
13
+ } from "../chunk-SJPDVKUS.js";
14
+ import "../chunk-CAKJT3KS.js";
15
+ import {
16
+ callbackAction
17
+ } from "../chunk-HGJ4TXY4.js";
18
+ import "../chunk-RLT4RFKV.js";
19
+ import "../chunk-UJJ7R56J.js";
20
+ import "../chunk-ZV4BH47P.js";
21
+ import "../chunk-6SM22VVJ.js";
22
+ import "../chunk-STHEPPUZ.js";
23
+ import "../chunk-GZU3RBTB.js";
24
+ import "../chunk-256KIVJL.js";
25
+ import "../chunk-FJUDBLCP.js";
26
+ import "../chunk-JAPMIE6S.js";
27
+ import "../chunk-HMRKN75I.js";
28
+ export {
29
+ callbackAction,
30
+ csrfTokenAction,
31
+ sessionAction,
32
+ signInAction,
33
+ signOutAction
34
+ };
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/actions/session/session.ts
21
+ var session_exports = {};
22
+ __export(session_exports, {
23
+ sessionAction: () => sessionAction
24
+ });
25
+ module.exports = __toCommonJS(session_exports);
26
+ var import_router2 = require("@aura-stack/router");
27
+
28
+ // src/utils.ts
29
+ var import_router = require("@aura-stack/router");
30
+
31
+ // src/error.ts
32
+ var AuthError = class extends Error {
33
+ constructor(type, message) {
34
+ super(message);
35
+ this.type = type;
36
+ this.name = "AuthError";
37
+ }
38
+ };
39
+
40
+ // src/utils.ts
41
+ var toISOString = (date) => {
42
+ return new Date(date).toISOString();
43
+ };
44
+
45
+ // src/headers.ts
46
+ var cacheControl = {
47
+ "Cache-Control": "no-store",
48
+ Pragma: "no-cache",
49
+ Expires: "0",
50
+ Vary: "Cookie"
51
+ };
52
+
53
+ // src/cookie.ts
54
+ var import_cookie = require("cookie");
55
+
56
+ // src/assert.ts
57
+ var isRequest = (value) => {
58
+ return typeof Request !== "undefined" && value instanceof Request;
59
+ };
60
+
61
+ // src/cookie.ts
62
+ var import_cookie2 = require("cookie");
63
+ var COOKIE_NAME = "aura-auth";
64
+ var defaultCookieOptions = {
65
+ httpOnly: true,
66
+ sameSite: "lax",
67
+ path: "/",
68
+ maxAge: 60 * 60 * 24 * 15
69
+ };
70
+ var defaultStandardCookieConfig = {
71
+ secure: false,
72
+ httpOnly: true,
73
+ prefix: ""
74
+ };
75
+ var defaultSecureCookieConfig = {
76
+ secure: true,
77
+ prefix: "__Secure-"
78
+ };
79
+ var defaultHostCookieConfig = {
80
+ secure: true,
81
+ prefix: "__Host-",
82
+ path: "/",
83
+ domain: void 0
84
+ };
85
+ var expiredCookieOptions = {
86
+ ...defaultCookieOptions,
87
+ expires: /* @__PURE__ */ new Date(0),
88
+ maxAge: 0
89
+ };
90
+ var defineDefaultCookieOptions = (options) => {
91
+ return {
92
+ name: options?.name ?? COOKIE_NAME,
93
+ prefix: options?.prefix ?? (options?.secure ? "__Secure-" : ""),
94
+ ...defaultCookieOptions,
95
+ ...options
96
+ };
97
+ };
98
+ var setCookie = (cookieName, value, options) => {
99
+ const { prefix, name } = defineDefaultCookieOptions(options);
100
+ const cookieNameWithPrefix = `${prefix}${name}.${cookieName}`;
101
+ return (0, import_cookie.serialize)(cookieNameWithPrefix, value, {
102
+ ...defaultCookieOptions,
103
+ ...options
104
+ });
105
+ };
106
+ var getCookie = (petition, cookie, options, optional = false) => {
107
+ const cookies = isRequest(petition) ? petition.headers.get("Cookie") : petition.headers.getSetCookie().join("; ");
108
+ if (!cookies) {
109
+ if (optional) {
110
+ return "";
111
+ }
112
+ throw new AuthError("invalid_request", "No cookies found. There is no active session");
113
+ }
114
+ const { name, prefix } = defineDefaultCookieOptions(options);
115
+ const parsedCookies = (0, import_cookie.parse)(cookies);
116
+ const value = parsedCookies[`${prefix}${name}.${cookie}`];
117
+ if (value === void 0) {
118
+ if (optional) {
119
+ return "";
120
+ }
121
+ throw new AuthError("invalid_request", `Cookie "${cookie}" not found. There is no active session`);
122
+ }
123
+ return value;
124
+ };
125
+ var secureCookieOptions = (request, cookieOptions, trustedProxyHeaders) => {
126
+ const name = cookieOptions.name ?? COOKIE_NAME;
127
+ 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://");
128
+ if (!cookieOptions.options?.httpOnly) {
129
+ console.warn(
130
+ "[WARNING]: Cookie is configured without HttpOnly. This allows JavaScript access via document.cookie and increases XSS risk."
131
+ );
132
+ }
133
+ if (cookieOptions.options?.domain === "*") {
134
+ console.warn("[WARNING]: Cookie 'Domain' is set to '*', which is insecure. Avoid wildcard domains.");
135
+ }
136
+ if (!isSecure) {
137
+ const options = cookieOptions.options;
138
+ if (options?.secure) {
139
+ console.warn(
140
+ "[WARNING]: The 'Secure' attribute will be disabled for this cookie. Serve over HTTPS to enforce Secure cookies."
141
+ );
142
+ }
143
+ if (options?.sameSite == "none") {
144
+ console.warn("[WARNING]: SameSite=None without a secure connection can be blocked by browsers.");
145
+ }
146
+ if (process.env.NODE_ENV === "production") {
147
+ console.warn("[WARNING]: In production, ensure cookies are served over HTTPS to maintain security.");
148
+ }
149
+ return {
150
+ ...defaultCookieOptions,
151
+ ...cookieOptions.options,
152
+ sameSite: options?.sameSite === "none" ? "lax" : options?.sameSite ?? "lax",
153
+ ...defaultStandardCookieConfig,
154
+ name
155
+ };
156
+ }
157
+ return cookieOptions.strategy === "host" ? {
158
+ ...defaultCookieOptions,
159
+ ...cookieOptions.options,
160
+ ...defaultHostCookieConfig,
161
+ name
162
+ } : { ...defaultCookieOptions, ...cookieOptions.options, ...defaultSecureCookieConfig, name };
163
+ };
164
+ var expireCookie = (name, options) => {
165
+ return setCookie(name, "", { ...options, ...expiredCookieOptions });
166
+ };
167
+
168
+ // src/actions/session/session.ts
169
+ var sessionAction = (0, import_router2.createEndpoint)("GET", "/session", async (ctx) => {
170
+ const {
171
+ request,
172
+ context: { cookies, jose, trustedProxyHeaders }
173
+ } = ctx;
174
+ const cookieOptions = secureCookieOptions(request, cookies, trustedProxyHeaders);
175
+ try {
176
+ const session = getCookie(request, "sessionToken", cookieOptions);
177
+ const decoded = await jose.decodeJWT(session);
178
+ const { exp, iat, jti, nbf, ...user } = decoded;
179
+ const headers = new Headers(cacheControl);
180
+ return Response.json({ user, expires: toISOString(exp * 1e3) }, { headers });
181
+ } catch {
182
+ const headers = new Headers(cacheControl);
183
+ const sessionCookie = expireCookie("sessionToken", cookieOptions);
184
+ headers.set("Set-Cookie", sessionCookie);
185
+ return Response.json({ authenticated: false, message: "Unauthorized" }, { status: 401, headers });
186
+ }
187
+ });
188
+ // Annotate the CommonJS export names for ESM import in node:
189
+ 0 && (module.exports = {
190
+ sessionAction
191
+ });
@@ -0,0 +1,5 @@
1
+ import * as _aura_stack_router from '@aura-stack/router';
2
+
3
+ declare const sessionAction: _aura_stack_router.RouteEndpoint<"GET", "/session", {}>;
4
+
5
+ export { sessionAction };
@@ -0,0 +1,5 @@
1
+ import * as _aura_stack_router from '@aura-stack/router';
2
+
3
+ declare const sessionAction: _aura_stack_router.RouteEndpoint<"GET", "/session", {}>;
4
+
5
+ export { sessionAction };
@@ -0,0 +1,11 @@
1
+ import {
2
+ sessionAction
3
+ } from "../../chunk-XXJKNKGQ.js";
4
+ import "../../chunk-ZV4BH47P.js";
5
+ import "../../chunk-6SM22VVJ.js";
6
+ import "../../chunk-STHEPPUZ.js";
7
+ import "../../chunk-256KIVJL.js";
8
+ import "../../chunk-FJUDBLCP.js";
9
+ export {
10
+ sessionAction
11
+ };
@@ -0,0 +1,274 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/actions/signIn/authorization.ts
21
+ var authorization_exports = {};
22
+ __export(authorization_exports, {
23
+ createAuthorizationURL: () => createAuthorizationURL,
24
+ createRedirectTo: () => createRedirectTo,
25
+ createRedirectURI: () => createRedirectURI,
26
+ getOriginURL: () => getOriginURL
27
+ });
28
+ module.exports = __toCommonJS(authorization_exports);
29
+
30
+ // src/assert.ts
31
+ var isValidURL = (value) => {
32
+ if (value.includes("\r\n") || value.includes("\n") || value.includes("\r")) return false;
33
+ const regex = /^https?:\/\/(?:[a-zA-Z0-9._-]+|localhost|\[[0-9a-fA-F:]+\])(?::\d{1,5})?(?:\/[a-zA-Z0-9._~!$&'()*+,;=:@-]*)*\/?$/;
34
+ return regex.test(value);
35
+ };
36
+
37
+ // src/schemas.ts
38
+ var import_v4 = require("zod/v4");
39
+ var OAuthProviderConfigSchema = (0, import_v4.object)({
40
+ authorizeURL: (0, import_v4.url)(),
41
+ accessToken: (0, import_v4.url)(),
42
+ scope: (0, import_v4.string)().optional(),
43
+ userInfo: (0, import_v4.url)(),
44
+ responseType: (0, import_v4.enum)(["code", "token", "id_token"]),
45
+ clientId: (0, import_v4.string)(),
46
+ clientSecret: (0, import_v4.string)()
47
+ });
48
+ var OAuthAuthorization = OAuthProviderConfigSchema.extend({
49
+ redirectURI: (0, import_v4.string)(),
50
+ state: (0, import_v4.string)(),
51
+ codeChallenge: (0, import_v4.string)(),
52
+ codeChallengeMethod: (0, import_v4.enum)(["plain", "S256"])
53
+ });
54
+ var OAuthAuthorizationResponse = (0, import_v4.object)({
55
+ state: (0, import_v4.string)(),
56
+ code: (0, import_v4.string)()
57
+ });
58
+ var OAuthAuthorizationErrorResponse = (0, import_v4.object)({
59
+ error: (0, import_v4.enum)([
60
+ "invalid_request",
61
+ "unauthorized_client",
62
+ "access_denied",
63
+ "unsupported_response_type",
64
+ "invalid_scope",
65
+ "server_error",
66
+ "temporarily_unavailable"
67
+ ]),
68
+ error_description: (0, import_v4.string)().optional(),
69
+ error_uri: (0, import_v4.string)().optional(),
70
+ state: (0, import_v4.string)()
71
+ });
72
+ var OAuthAccessToken = OAuthProviderConfigSchema.extend({
73
+ redirectURI: (0, import_v4.string)(),
74
+ code: (0, import_v4.string)(),
75
+ codeVerifier: (0, import_v4.string)().min(43).max(128)
76
+ });
77
+ var OAuthAccessTokenResponse = (0, import_v4.object)({
78
+ access_token: (0, import_v4.string)(),
79
+ token_type: (0, import_v4.string)(),
80
+ expires_in: (0, import_v4.number)().optional(),
81
+ refresh_token: (0, import_v4.string)().optional(),
82
+ scope: (0, import_v4.string)().optional()
83
+ });
84
+ var OAuthAccessTokenErrorResponse = (0, import_v4.object)({
85
+ error: (0, import_v4.enum)([
86
+ "invalid_request",
87
+ "invalid_client",
88
+ "invalid_grant",
89
+ "unauthorized_client",
90
+ "unsupported_grant_type",
91
+ "invalid_scope"
92
+ ]),
93
+ error_description: (0, import_v4.string)().optional(),
94
+ error_uri: (0, import_v4.string)().optional()
95
+ });
96
+ var OAuthErrorResponse = (0, import_v4.object)({
97
+ error: (0, import_v4.string)(),
98
+ error_description: (0, import_v4.string)().optional()
99
+ });
100
+
101
+ // src/utils.ts
102
+ var import_router = require("@aura-stack/router");
103
+
104
+ // src/error.ts
105
+ var AuthError = class extends Error {
106
+ constructor(type, message) {
107
+ super(message);
108
+ this.type = type;
109
+ this.name = "AuthError";
110
+ }
111
+ };
112
+ var InvalidRedirectToError = class extends AuthError {
113
+ constructor(message = "The redirectTo parameter does not match the hosted origin.") {
114
+ super("invalid_redirect_to", message);
115
+ this.name = "InvalidRedirectToError";
116
+ }
117
+ };
118
+ var isAuthError = (error) => {
119
+ return error instanceof AuthError;
120
+ };
121
+ var ERROR_RESPONSE = {
122
+ AUTHORIZATION: {
123
+ INVALID_REQUEST: "invalid_request",
124
+ UNAUTHORIZED_CLIENT: "unauthorized_client",
125
+ ACCESS_DENIED: "access_denied",
126
+ UNSUPPORTED_RESPONSE_TYPE: "unsupported_response_type",
127
+ INVALID_SCOPE: "invalid_scope",
128
+ SERVER_ERROR: "server_error",
129
+ TEMPORARILY_UNAVAILABLE: "temporarily_unavailable"
130
+ },
131
+ ACCESS_TOKEN: {
132
+ INVALID_REQUEST: "invalid_request",
133
+ INVALID_CLIENT: "invalid_client",
134
+ INVALID_GRANT: "invalid_grant",
135
+ UNAUTHORIZED_CLIENT: "unauthorized_client",
136
+ UNSUPPORTED_GRANT_TYPE: "unsupported_grant_type",
137
+ INVALID_SCOPE: "invalid_scope"
138
+ }
139
+ };
140
+
141
+ // src/utils.ts
142
+ var toSnakeCase = (str) => {
143
+ return str.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").toLowerCase().replace(/^_+/, "");
144
+ };
145
+ var toUpperCase = (str) => {
146
+ return str.toUpperCase();
147
+ };
148
+ var toCastCase = (obj, type = "snake") => {
149
+ return Object.entries(obj).reduce((previous, [key, value]) => {
150
+ const newKey = type === "snake" ? toSnakeCase(key) : toUpperCase(key);
151
+ return { ...previous, [newKey]: value };
152
+ }, {});
153
+ };
154
+ var equals = (a, b) => {
155
+ if (a === null || b === null || a === void 0 || b === void 0) return false;
156
+ return a === b;
157
+ };
158
+ var sanitizeURL = (url2) => {
159
+ try {
160
+ let decodedURL = decodeURIComponent(url2).trim();
161
+ const protocolMatch = decodedURL.match(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)/);
162
+ let protocol = "";
163
+ let rest = decodedURL;
164
+ if (protocolMatch) {
165
+ protocol = protocolMatch[1];
166
+ rest = decodedURL.slice(protocol.length);
167
+ const slashIndex = rest.indexOf("/");
168
+ if (slashIndex === -1) {
169
+ return protocol + rest;
170
+ }
171
+ const domain = rest.slice(0, slashIndex);
172
+ let path = rest.slice(slashIndex).replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
173
+ if (path !== "/" && path.endsWith("/")) {
174
+ path = path.replace(/\/+$/, "/");
175
+ } else if (path !== "/") {
176
+ path = path.replace(/\/+$/, "");
177
+ }
178
+ return protocol + domain + path;
179
+ }
180
+ let sanitized = decodedURL.replace(/\/\.\.\//g, "/").replace(/\/\.\.$/, "").replace(/\.{2,}/g, "").replace(/\/{2,}/g, "/");
181
+ if (sanitized !== "/" && sanitized.endsWith("/")) {
182
+ sanitized = sanitized.replace(/\/+$/, "/");
183
+ } else if (sanitized !== "/") {
184
+ sanitized = sanitized.replace(/\/+$/, "");
185
+ }
186
+ return sanitized;
187
+ } catch {
188
+ return url2.trim();
189
+ }
190
+ };
191
+ var getNormalizedOriginPath = (path) => {
192
+ try {
193
+ const url2 = new URL(path);
194
+ url2.hash = "";
195
+ url2.search = "";
196
+ return `${url2.origin}${url2.pathname}`;
197
+ } catch {
198
+ return sanitizeURL(path);
199
+ }
200
+ };
201
+
202
+ // src/actions/signIn/authorization.ts
203
+ var createAuthorizationURL = (oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod) => {
204
+ const parsed = OAuthAuthorization.safeParse({ ...oauthConfig, redirectURI, state, codeChallenge, codeChallengeMethod });
205
+ if (!parsed.success) {
206
+ throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.SERVER_ERROR, "Invalid OAuth configuration");
207
+ }
208
+ const { authorizeURL, ...options2 } = parsed.data;
209
+ const { userInfo, accessToken, clientSecret, ...required } = options2;
210
+ const searchParams = new URLSearchParams(toCastCase(required));
211
+ return `${authorizeURL}?${searchParams}`;
212
+ };
213
+ var getOriginURL = (request, trustedProxyHeaders) => {
214
+ const headers = request.headers;
215
+ if (trustedProxyHeaders) {
216
+ const protocol = headers.get("X-Forwarded-Proto") ?? headers.get("Forwarded")?.match(/proto=([^;]+)/i)?.[1] ?? "http";
217
+ const host = headers.get("X-Forwarded-Host") ?? headers.get("Host") ?? headers.get("Forwarded")?.match(/host=([^;]+)/i)?.[1] ?? null;
218
+ return new URL(`${protocol}://${host}${getNormalizedOriginPath(new URL(request.url).pathname)}`);
219
+ } else {
220
+ return new URL(getNormalizedOriginPath(request.url));
221
+ }
222
+ };
223
+ var createRedirectURI = (request, oauth, basePath, trustedProxyHeaders) => {
224
+ const url2 = getOriginURL(request, trustedProxyHeaders);
225
+ return `${url2.origin}${basePath}/callback/${oauth}`;
226
+ };
227
+ var createRedirectTo = (request, redirectTo, trustedProxyHeaders) => {
228
+ try {
229
+ const headers = request.headers;
230
+ const origin = headers.get("Origin");
231
+ const referer = headers.get("Referer");
232
+ let hostedURL = getOriginURL(request, trustedProxyHeaders);
233
+ if (redirectTo) {
234
+ if (redirectTo.startsWith("/")) {
235
+ return sanitizeURL(redirectTo);
236
+ }
237
+ const redirectToURL = new URL(sanitizeURL(getNormalizedOriginPath(redirectTo)));
238
+ if (!isValidURL(redirectTo) || !equals(redirectToURL.origin, hostedURL.origin)) {
239
+ throw new InvalidRedirectToError();
240
+ }
241
+ return sanitizeURL(redirectToURL.pathname);
242
+ }
243
+ if (referer) {
244
+ const refererURL = new URL(sanitizeURL(referer));
245
+ if (!isValidURL(referer) || !equals(refererURL.origin, hostedURL.origin)) {
246
+ throw new AuthError(
247
+ ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST,
248
+ "The referer of the request does not match the hosted origin."
249
+ );
250
+ }
251
+ return sanitizeURL(refererURL.pathname);
252
+ }
253
+ if (origin) {
254
+ const originURL = new URL(sanitizeURL(getNormalizedOriginPath(origin)));
255
+ if (!isValidURL(origin) || !equals(originURL.origin, hostedURL.origin)) {
256
+ throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).");
257
+ }
258
+ return sanitizeURL(originURL.pathname);
259
+ }
260
+ return "/";
261
+ } catch (error) {
262
+ if (isAuthError(error)) {
263
+ throw error;
264
+ }
265
+ throw new AuthError(ERROR_RESPONSE.AUTHORIZATION.INVALID_REQUEST, "Invalid origin (potential CSRF).");
266
+ }
267
+ };
268
+ // Annotate the CommonJS export names for ESM import in node:
269
+ 0 && (module.exports = {
270
+ createAuthorizationURL,
271
+ createRedirectTo,
272
+ createRedirectURI,
273
+ getOriginURL
274
+ });
@@ -0,0 +1,45 @@
1
+ import { O as OAuthProviderCredentials } from '../../index-B1vDUGwh.cjs';
2
+ import 'zod/v4';
3
+ import '../../jose.cjs';
4
+ import '@aura-stack/jose/jose';
5
+ import '../../schemas.cjs';
6
+ import 'zod/v4/core';
7
+ import '@aura-stack/router';
8
+ import 'cookie';
9
+ import '../../@types/utility.cjs';
10
+
11
+ /**
12
+ * Constructs the request URI for the Authorization Request to the third-party OAuth service. It includes
13
+ * the necessary query parameters such as `client_id`, `redirect_uri`, `response_type`, `scope`, `state`,
14
+ * `code_challenge`, and `code_challenge_method`.
15
+ *
16
+ * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
17
+ * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4
18
+ *
19
+ * @param oauthConfig - The OAuth configuration for the third-party service.
20
+ * @param redirectURI - The redirect URI where the OAuth service will send the user after authorization.
21
+ * @param state - A unique string used to maintain state between the request and callback.
22
+ */
23
+ declare const createAuthorizationURL: (oauthConfig: OAuthProviderCredentials, redirectURI: string, state: string, codeChallenge: string, codeChallengeMethod: string) => string;
24
+ declare const getOriginURL: (request: Request, trustedProxyHeaders?: boolean) => URL;
25
+ /**
26
+ * Creates the redirect URI for the OAuth callback based on the original request URL and the OAuth provider.
27
+ *
28
+ * @param requestURL - the original request URL
29
+ * @param oauth - OAuth provider name
30
+ * @returns The redirect URI for the OAuth callback.
31
+ */
32
+ declare const createRedirectURI: (request: Request, oauth: string, basePath: string, trustedProxyHeaders?: boolean) => string;
33
+ /**
34
+ * Verifies if the request's origin matches the expected origin. It accepts the redirectTo search
35
+ * parameter for redirection. It checks the 'Referer' header of the request with the origin where
36
+ * the authentication flow is hosted. If they do not match, it throws an AuthError to avoid
37
+ * potential `Open URL Redirection` attacks.
38
+ *
39
+ * @param request The incoming request object
40
+ * @param redirectTo Optional redirectTo parameter to override the referer
41
+ * @returns The pathname of the referer URL if origins match
42
+ */
43
+ declare const createRedirectTo: (request: Request, redirectTo?: string, trustedProxyHeaders?: boolean) => string;
44
+
45
+ export { createAuthorizationURL, createRedirectTo, createRedirectURI, getOriginURL };
@@ -0,0 +1,45 @@
1
+ import { O as OAuthProviderCredentials } from '../../index-CGRZ0wrw.js';
2
+ import 'zod/v4';
3
+ import '../../jose.js';
4
+ import '@aura-stack/jose/jose';
5
+ import '../../schemas.js';
6
+ import 'zod/v4/core';
7
+ import '@aura-stack/router';
8
+ import 'cookie';
9
+ import '../../@types/utility.js';
10
+
11
+ /**
12
+ * Constructs the request URI for the Authorization Request to the third-party OAuth service. It includes
13
+ * the necessary query parameters such as `client_id`, `redirect_uri`, `response_type`, `scope`, `state`,
14
+ * `code_challenge`, and `code_challenge_method`.
15
+ *
16
+ * @see https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.1
17
+ * @see https://datatracker.ietf.org/doc/html/rfc7636#section-4
18
+ *
19
+ * @param oauthConfig - The OAuth configuration for the third-party service.
20
+ * @param redirectURI - The redirect URI where the OAuth service will send the user after authorization.
21
+ * @param state - A unique string used to maintain state between the request and callback.
22
+ */
23
+ declare const createAuthorizationURL: (oauthConfig: OAuthProviderCredentials, redirectURI: string, state: string, codeChallenge: string, codeChallengeMethod: string) => string;
24
+ declare const getOriginURL: (request: Request, trustedProxyHeaders?: boolean) => URL;
25
+ /**
26
+ * Creates the redirect URI for the OAuth callback based on the original request URL and the OAuth provider.
27
+ *
28
+ * @param requestURL - the original request URL
29
+ * @param oauth - OAuth provider name
30
+ * @returns The redirect URI for the OAuth callback.
31
+ */
32
+ declare const createRedirectURI: (request: Request, oauth: string, basePath: string, trustedProxyHeaders?: boolean) => string;
33
+ /**
34
+ * Verifies if the request's origin matches the expected origin. It accepts the redirectTo search
35
+ * parameter for redirection. It checks the 'Referer' header of the request with the origin where
36
+ * the authentication flow is hosted. If they do not match, it throws an AuthError to avoid
37
+ * potential `Open URL Redirection` attacks.
38
+ *
39
+ * @param request The incoming request object
40
+ * @param redirectTo Optional redirectTo parameter to override the referer
41
+ * @returns The pathname of the referer URL if origins match
42
+ */
43
+ declare const createRedirectTo: (request: Request, redirectTo?: string, trustedProxyHeaders?: boolean) => string;
44
+
45
+ export { createAuthorizationURL, createRedirectTo, createRedirectURI, getOriginURL };
@@ -0,0 +1,16 @@
1
+ import {
2
+ createAuthorizationURL,
3
+ createRedirectTo,
4
+ createRedirectURI,
5
+ getOriginURL
6
+ } from "../../chunk-CAKJT3KS.js";
7
+ import "../../chunk-6SM22VVJ.js";
8
+ import "../../chunk-256KIVJL.js";
9
+ import "../../chunk-FJUDBLCP.js";
10
+ import "../../chunk-HMRKN75I.js";
11
+ export {
12
+ createAuthorizationURL,
13
+ createRedirectTo,
14
+ createRedirectURI,
15
+ getOriginURL
16
+ };