faire-auth 1.0.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 (221) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +34 -0
  3. package/dist/access-B5bBI4uT.mjs +39 -0
  4. package/dist/access-Crt-IJ2P.cjs +51 -0
  5. package/dist/adapter-factory-BXei1QRX.mjs +881 -0
  6. package/dist/adapter-factory-DT-_2aHJ.cjs +893 -0
  7. package/dist/adapters/drizzle-adapter/index.cjs +208 -0
  8. package/dist/adapters/drizzle-adapter/index.d.cts +48 -0
  9. package/dist/adapters/drizzle-adapter/index.d.mts +48 -0
  10. package/dist/adapters/drizzle-adapter/index.mjs +207 -0
  11. package/dist/adapters/index.cjs +23 -0
  12. package/dist/adapters/index.d.cts +157 -0
  13. package/dist/adapters/index.d.mts +157 -0
  14. package/dist/adapters/index.mjs +17 -0
  15. package/dist/adapters/kysely-adapter/index.cjs +11 -0
  16. package/dist/adapters/kysely-adapter/index.d.cts +52 -0
  17. package/dist/adapters/kysely-adapter/index.d.mts +52 -0
  18. package/dist/adapters/kysely-adapter/index.mjs +9 -0
  19. package/dist/adapters/memory-adapter/index.cjs +9 -0
  20. package/dist/adapters/memory-adapter/index.d.cts +15 -0
  21. package/dist/adapters/memory-adapter/index.d.mts +15 -0
  22. package/dist/adapters/memory-adapter/index.mjs +9 -0
  23. package/dist/adapters/mongodb-adapter/index.cjs +9 -0
  24. package/dist/adapters/mongodb-adapter/index.d.cts +4 -0
  25. package/dist/adapters/mongodb-adapter/index.d.mts +4 -0
  26. package/dist/adapters/mongodb-adapter/index.mjs +9 -0
  27. package/dist/adapters/prisma-adapter/index.cjs +156 -0
  28. package/dist/adapters/prisma-adapter/index.d.cts +35 -0
  29. package/dist/adapters/prisma-adapter/index.d.mts +35 -0
  30. package/dist/adapters/prisma-adapter/index.mjs +155 -0
  31. package/dist/adapters/test.cjs +797 -0
  32. package/dist/adapters/test.d.cts +82 -0
  33. package/dist/adapters/test.d.mts +82 -0
  34. package/dist/adapters/test.mjs +793 -0
  35. package/dist/api/index.cjs +20 -0
  36. package/dist/api/index.d.cts +3 -0
  37. package/dist/api/index.d.mts +3 -0
  38. package/dist/api/index.mjs +20 -0
  39. package/dist/api/middleware/index.cjs +16 -0
  40. package/dist/api/middleware/index.d.cts +16 -0
  41. package/dist/api/middleware/index.d.mts +16 -0
  42. package/dist/api/middleware/index.mjs +11 -0
  43. package/dist/api-Bm89BLgN.cjs +1899 -0
  44. package/dist/api-_B7qO28y.mjs +1892 -0
  45. package/dist/auth-Bo9PDt5j.cjs +739 -0
  46. package/dist/auth-Ds4AG4h4.mjs +709 -0
  47. package/dist/bearer-0SeEmaS4.mjs +54 -0
  48. package/dist/bearer-CHeREcGT.cjs +60 -0
  49. package/dist/bun-sqlite-dialect-CfkBo2v5.mjs +155 -0
  50. package/dist/bun-sqlite-dialect-wuaC2-gh.cjs +156 -0
  51. package/dist/chunk-Ceigfy4P.mjs +39 -0
  52. package/dist/chunk-oakRccI5.cjs +60 -0
  53. package/dist/client/index.cjs +22 -0
  54. package/dist/client/index.d.cts +8 -0
  55. package/dist/client/index.d.mts +8 -0
  56. package/dist/client/index.mjs +19 -0
  57. package/dist/client/lynx/index.cjs +79 -0
  58. package/dist/client/lynx/index.d.cts +156 -0
  59. package/dist/client/lynx/index.d.mts +156 -0
  60. package/dist/client/lynx/index.mjs +76 -0
  61. package/dist/client/plugins/index.cjs +11 -0
  62. package/dist/client/plugins/index.d.cts +17 -0
  63. package/dist/client/plugins/index.d.mts +17 -0
  64. package/dist/client/plugins/index.mjs +10 -0
  65. package/dist/client/react/index.cjs +79 -0
  66. package/dist/client/react/index.d.cts +156 -0
  67. package/dist/client/react/index.d.mts +156 -0
  68. package/dist/client/react/index.mjs +76 -0
  69. package/dist/client/solid/index.cjs +51 -0
  70. package/dist/client/solid/index.d.cts +90 -0
  71. package/dist/client/solid/index.d.mts +90 -0
  72. package/dist/client/solid/index.mjs +50 -0
  73. package/dist/client/svelte/index.cjs +28 -0
  74. package/dist/client/svelte/index.d.cts +110 -0
  75. package/dist/client/svelte/index.d.mts +110 -0
  76. package/dist/client/svelte/index.mjs +28 -0
  77. package/dist/client/vue/index.cjs +68 -0
  78. package/dist/client/vue/index.d.cts +123 -0
  79. package/dist/client/vue/index.d.mts +123 -0
  80. package/dist/client/vue/index.mjs +67 -0
  81. package/dist/cookies-B5xeA6i8.cjs +456 -0
  82. package/dist/cookies-Ch1JfQIz.mjs +367 -0
  83. package/dist/crypto/index.cjs +11 -0
  84. package/dist/crypto/index.d.cts +22 -0
  85. package/dist/crypto/index.d.mts +22 -0
  86. package/dist/crypto/index.mjs +5 -0
  87. package/dist/crypto-CcTxYH82.cjs +57 -0
  88. package/dist/crypto-CyQRFtkq.mjs +41 -0
  89. package/dist/db/index.cjs +40 -0
  90. package/dist/db/index.d.cts +4 -0
  91. package/dist/db/index.d.mts +4 -0
  92. package/dist/db/index.mjs +16 -0
  93. package/dist/db-BTKyYu-_.cjs +1180 -0
  94. package/dist/db-xiJtoDgz.mjs +1119 -0
  95. package/dist/defu-B0Svx_x4.cjs +34 -0
  96. package/dist/defu-SZkpHhbR.mjs +28 -0
  97. package/dist/email-verification-C-AsfJsb.cjs +247 -0
  98. package/dist/email-verification-CWhj2qfb.mjs +228 -0
  99. package/dist/hono-BEq1NYVX.cjs +526 -0
  100. package/dist/hono-Cdukwu5K.cjs +13 -0
  101. package/dist/hono-CoKYWnXA.mjs +7 -0
  102. package/dist/hono-Covz10jU.mjs +508 -0
  103. package/dist/hono-DOM31WQz.d.cts +18 -0
  104. package/dist/hono-DuE14mmj.d.mts +18 -0
  105. package/dist/index-B-WeOMzg.d.cts +13350 -0
  106. package/dist/index-B09P9p5_.d.cts +33 -0
  107. package/dist/index-B5_0QTLg.d.mts +3 -0
  108. package/dist/index-B7SKyR_a.d.cts +3 -0
  109. package/dist/index-BVHscLQl.d.cts +992 -0
  110. package/dist/index-C2-2QDyS.d.cts +35 -0
  111. package/dist/index-CTwrVluH.d.mts +41 -0
  112. package/dist/index-CWAqWfoZ.d.cts +27 -0
  113. package/dist/index-CYSShrFx.d.mts +27 -0
  114. package/dist/index-Qu-iJGNr.d.mts +992 -0
  115. package/dist/index-cs4Sh0En.d.cts +41 -0
  116. package/dist/index-jlessPI0.d.mts +13350 -0
  117. package/dist/index-ppgcFe12.d.mts +33 -0
  118. package/dist/index-to0RO38U.d.mts +35 -0
  119. package/dist/index.cjs +85 -0
  120. package/dist/index.d.cts +5 -0
  121. package/dist/index.d.mts +5 -0
  122. package/dist/index.mjs +27 -0
  123. package/dist/integrations/next-js.cjs +50 -0
  124. package/dist/integrations/next-js.d.cts +23 -0
  125. package/dist/integrations/next-js.d.mts +23 -0
  126. package/dist/integrations/next-js.mjs +49 -0
  127. package/dist/integrations/node.cjs +139 -0
  128. package/dist/integrations/node.d.cts +22 -0
  129. package/dist/integrations/node.d.mts +22 -0
  130. package/dist/integrations/node.mjs +134 -0
  131. package/dist/integrations/react-start.cjs +37 -0
  132. package/dist/integrations/react-start.d.cts +17 -0
  133. package/dist/integrations/react-start.d.mts +17 -0
  134. package/dist/integrations/react-start.mjs +37 -0
  135. package/dist/integrations/solid-start.cjs +14 -0
  136. package/dist/integrations/solid-start.d.cts +13 -0
  137. package/dist/integrations/solid-start.d.mts +13 -0
  138. package/dist/integrations/solid-start.mjs +13 -0
  139. package/dist/integrations/svelte-kit.cjs +52 -0
  140. package/dist/integrations/svelte-kit.d.cts +42 -0
  141. package/dist/integrations/svelte-kit.d.mts +42 -0
  142. package/dist/integrations/svelte-kit.mjs +49 -0
  143. package/dist/ip-B5SwXaMB.cjs +54 -0
  144. package/dist/ip-BjNYspCH.mjs +36 -0
  145. package/dist/json-B1v2qRTQ.mjs +24 -0
  146. package/dist/json-CcJ2HjGo.cjs +30 -0
  147. package/dist/kysely-adapter-Bxi7sPdG.cjs +288 -0
  148. package/dist/kysely-adapter-DRuoT_X8.mjs +270 -0
  149. package/dist/logged-CyGfp8_H.mjs +187 -0
  150. package/dist/logged-DQK3C64b.cjs +193 -0
  151. package/dist/memory-adapter-BlnDIAAX.cjs +154 -0
  152. package/dist/memory-adapter-Db3tsJTn.mjs +148 -0
  153. package/dist/middleware-CE6OhDkq.mjs +29 -0
  154. package/dist/middleware-CWvRH4EW.cjs +47 -0
  155. package/dist/mongodb-adapter-C_qGQED5.mjs +291 -0
  156. package/dist/mongodb-adapter-C_qfK87x.cjs +297 -0
  157. package/dist/node-sqlite-dialect-BfBzyOAg.mjs +155 -0
  158. package/dist/node-sqlite-dialect-mJWC8LWQ.cjs +156 -0
  159. package/dist/oauth2/index.cjs +25 -0
  160. package/dist/oauth2/index.d.cts +42 -0
  161. package/dist/oauth2/index.d.mts +42 -0
  162. package/dist/oauth2/index.mjs +16 -0
  163. package/dist/oauth2-B8M0lW9l.mjs +159 -0
  164. package/dist/oauth2-BLeOEi7Y.cjs +177 -0
  165. package/dist/origin-check-8Gajklvh.mjs +228 -0
  166. package/dist/origin-check-id9lTnqZ.cjs +246 -0
  167. package/dist/parser-CdncAl9i.cjs +83 -0
  168. package/dist/parser-CeAer-RM.mjs +71 -0
  169. package/dist/passkey-B6N20LSS.cjs +512 -0
  170. package/dist/passkey-DJsR_GX3.mjs +505 -0
  171. package/dist/plugins/access/index.cjs +4 -0
  172. package/dist/plugins/access/index.d.cts +2 -0
  173. package/dist/plugins/access/index.d.mts +2 -0
  174. package/dist/plugins/access/index.mjs +3 -0
  175. package/dist/plugins/bearer/index.cjs +7 -0
  176. package/dist/plugins/bearer/index.d.cts +4 -0
  177. package/dist/plugins/bearer/index.d.mts +4 -0
  178. package/dist/plugins/bearer/index.mjs +7 -0
  179. package/dist/plugins/index.cjs +49 -0
  180. package/dist/plugins/index.d.cts +9326 -0
  181. package/dist/plugins/index.d.mts +9326 -0
  182. package/dist/plugins/index.mjs +26 -0
  183. package/dist/plugins/passkey/index.cjs +15 -0
  184. package/dist/plugins/passkey/index.d.cts +4 -0
  185. package/dist/plugins/passkey/index.d.mts +4 -0
  186. package/dist/plugins/passkey/index.mjs +15 -0
  187. package/dist/plugins-C1lm2Wj3.cjs +5254 -0
  188. package/dist/plugins-Dai1QkRU.mjs +5199 -0
  189. package/dist/request-1NL_1lyJ.mjs +58 -0
  190. package/dist/request-CPNlp-DK.cjs +100 -0
  191. package/dist/schema-D-qjygfE.cjs +179 -0
  192. package/dist/schema-DTIwLLmf.mjs +125 -0
  193. package/dist/session-De9POJTW.cjs +641 -0
  194. package/dist/session-rH8ougDl.mjs +538 -0
  195. package/dist/social-providers/index.cjs +10 -0
  196. package/dist/social-providers/index.d.cts +2 -0
  197. package/dist/social-providers/index.d.mts +2 -0
  198. package/dist/social-providers/index.mjs +5 -0
  199. package/dist/social-providers-DcFNUT0S.cjs +13 -0
  200. package/dist/social-providers-DoYJhBe3.mjs +9 -0
  201. package/dist/state--f7fwIGh.cjs +99 -0
  202. package/dist/state-CqJfCIl9.mjs +86 -0
  203. package/dist/test-utils/index.cjs +27492 -0
  204. package/dist/test-utils/index.d.cts +4584 -0
  205. package/dist/test-utils/index.d.mts +4584 -0
  206. package/dist/test-utils/index.mjs +27490 -0
  207. package/dist/types/index.cjs +0 -0
  208. package/dist/types/index.d.cts +3 -0
  209. package/dist/types/index.d.mts +3 -0
  210. package/dist/types/index.mjs +1 -0
  211. package/dist/url-BoUuoIwZ.mjs +88 -0
  212. package/dist/url-D2yvKaM7.cjs +118 -0
  213. package/dist/utils/cookies.cjs +51 -0
  214. package/dist/utils/cookies.d.cts +179 -0
  215. package/dist/utils/cookies.d.mts +179 -0
  216. package/dist/utils/cookies.mjs +7 -0
  217. package/dist/utils-44aDDP8f.cjs +2 -0
  218. package/dist/utils-D4vZd1-9.mjs +4 -0
  219. package/dist/vanilla-Bu2PmFzE.cjs +30 -0
  220. package/dist/vanilla-TfHqeiC7.mjs +25 -0
  221. package/package.json +470 -0
@@ -0,0 +1,538 @@
1
+ import { t as contextStorage } from "./hono-CoKYWnXA.mjs";
2
+ import { t as safeJSONParse } from "./json-B1v2qRTQ.mjs";
3
+ import { n as cookies_exports, o as deleteSessionCookie, v as setCookieCache, y as setSessionCookie } from "./cookies-Ch1JfQIz.mjs";
4
+ import { t as logged_default } from "./logged-CyGfp8_H.mjs";
5
+ import { t as getBaseURL } from "./url-BoUuoIwZ.mjs";
6
+ import { r as createMiddleware, t as createErrorHandler } from "./middleware-CE6OhDkq.mjs";
7
+ import { isTest, logger } from "@faire-auth/core/env";
8
+ import { APIError, BASE_ERROR_CODES } from "@faire-auth/core/error";
9
+ import { buildRouteBundle, createRoute, createRouteAppWrapper, initRenderer, req, res } from "@faire-auth/core/factory";
10
+ import { Definitions, False, Routes, SCHEMAS, True, isPromise } from "@faire-auth/core/static";
11
+ import { getDate, isContextLike, isExecOpts, withOverlays } from "@faire-auth/core/utils";
12
+ import { base64Url, binary, createHMAC } from "@faire-auth/core/datatypes";
13
+ import { HTTPException } from "hono/http-exception";
14
+ import * as z$1 from "zod";
15
+ import { looseSessionSchema, looseUserSchema } from "@faire-auth/core/db";
16
+
17
+ //#region src/api/middleware/context.ts
18
+ /**
19
+ * Initializes the context middleware.
20
+ * @template O - The options type.
21
+ * @param options - The FaireAuth options.
22
+ * @param context - The auth context.
23
+ * @returns The middleware function.
24
+ */
25
+ const initContextMiddleware = (options, context, api) => createMiddleware()(async (ctx, next) => {
26
+ ctx.set("context", context);
27
+ ctx.set("api", api);
28
+ ctx.set("path", ctx.req.path.slice((options.basePath ?? "/api/auth").length));
29
+ return await next();
30
+ });
31
+
32
+ //#endregion
33
+ //#region src/api/middleware/hooks.ts
34
+ const runHooks = async (ctx, hooks) => {
35
+ let response = void 0;
36
+ for (const hook of hooks) if (hook.matcher(ctx)) try {
37
+ const maybePromise = hook.handler(ctx);
38
+ const result = isPromise(maybePromise) ? await maybePromise : maybePromise;
39
+ if (result instanceof Response) response = result;
40
+ } catch (error) {
41
+ ctx.error = error;
42
+ }
43
+ return response;
44
+ };
45
+ const getHooks = (options) => {
46
+ const beforeHooks = [];
47
+ const afterHooks = [];
48
+ if (options.hooks?.before != null) beforeHooks.push({
49
+ matcher: () => true,
50
+ handler: options.hooks.before(options)
51
+ });
52
+ if (options.hooks?.after != null) afterHooks.push({
53
+ matcher: () => true,
54
+ handler: options.hooks.after(options)
55
+ });
56
+ options.plugins?.forEach((p) => {
57
+ p.hooks?.before?.forEach((h) => beforeHooks.push({
58
+ matcher: h.matcher,
59
+ handler: h.handler(options)
60
+ }));
61
+ p.hooks?.after?.forEach((h) => afterHooks.push({
62
+ matcher: h.matcher,
63
+ handler: h.handler(options)
64
+ }));
65
+ });
66
+ return {
67
+ beforeHooks,
68
+ afterHooks
69
+ };
70
+ };
71
+ /**
72
+ * Initializes the hooks middleware.
73
+ * @template O - The options type.
74
+ * @param options - The FaireAuth options.
75
+ * @returns The middleware function.
76
+ */
77
+ const initHooksMiddleware = (options) => {
78
+ const { beforeHooks, afterHooks } = getHooks(options);
79
+ return createMiddleware()(async (ctx, next) => {
80
+ const before = await runHooks(ctx, beforeHooks);
81
+ if (before instanceof Response) return before;
82
+ await next();
83
+ const after = await runHooks(ctx, afterHooks);
84
+ if (after instanceof Response) ctx.res = after;
85
+ });
86
+ };
87
+
88
+ //#endregion
89
+ //#region src/api/middleware/on-error.ts
90
+ /**
91
+ * Initializes the error handler.
92
+ * @param options - The FaireAuth options.
93
+ * @returns The error handler function.
94
+ */
95
+ const initErrorHandler = (options) => createErrorHandler()(async (e, ctx) => {
96
+ const ret = ctx.finalized === true ? ctx.res : e instanceof Response ? e : e instanceof HTTPException ? e.getResponse() : ctx.json({
97
+ success: False,
98
+ ...options.onAPIError?.exposeMessage === true && { message: e.message }
99
+ }, 500);
100
+ if (e instanceof APIError && e.statusText === "FOUND") return ret;
101
+ if (options.onAPIError?.throw === true) throw e;
102
+ if (options.onAPIError?.onError) {
103
+ const res$1 = options.onAPIError.onError(e, ctx);
104
+ if (isPromise(res$1)) await res$1;
105
+ return ret;
106
+ }
107
+ const optLogLevel = options.logger?.level;
108
+ const critLog = ctx.get("context")?.logger ?? console;
109
+ const log = optLogLevel === "error" || optLogLevel === "warn" || optLogLevel === "debug" ? logger : void 0;
110
+ if (options.logger?.disabled !== true) {
111
+ if (e != null && typeof e === "object" && "message" in e && typeof e.message === "string") {
112
+ if (e.message.includes("no column") || e.message.includes("column") || e.message.includes("relation") || e.message.includes("table") || e.message.includes("does not exist")) {
113
+ critLog.error(e.message);
114
+ return ret;
115
+ }
116
+ }
117
+ if (e instanceof APIError) {
118
+ if (e.statusText === "INTERNAL_SERVER_ERROR") critLog.error(e.statusText, e);
119
+ log?.error(e.message);
120
+ } else critLog.error(e != null && typeof e === "object" && "name" in e ? e.name : "", e);
121
+ }
122
+ return ret;
123
+ });
124
+
125
+ //#endregion
126
+ //#region src/api/middleware/server-api.ts
127
+ /**
128
+ * Middleware that sets a flag indicating the route was called from the server-side API.
129
+ * This should only be used with localApp in createEndpoint to provide permissions depth.
130
+ */
131
+ const serverApiMiddleware = createMiddleware()(async (ctx, next) => {
132
+ ctx.set("isServer", true);
133
+ return await next();
134
+ });
135
+
136
+ //#endregion
137
+ //#region src/utils/hono.ts
138
+ const createDefaultExecutionCtx = (ctx) => {
139
+ Object.defineProperty(ctx, "executionCtx", {
140
+ get: () => ({
141
+ waitUntil: (promise) => ctx.get("toAwait").push(promise),
142
+ passThroughOnException: () => {},
143
+ props: {}
144
+ }),
145
+ configurable: true,
146
+ enumerable: true
147
+ });
148
+ };
149
+
150
+ //#endregion
151
+ //#region src/api/middleware/set-execution-ctx.ts
152
+ /**
153
+ * Sets the default execution context if not already present.
154
+ * Manages promises to await after the middleware chain.
155
+ */
156
+ const setDefaultExecutionCtx = createMiddleware()(async (ctx, next) => {
157
+ ctx.set("toAwait", []);
158
+ let hasDefaultExecutionCtx = false;
159
+ try {
160
+ ctx.executionCtx;
161
+ } catch {
162
+ createDefaultExecutionCtx(ctx);
163
+ hasDefaultExecutionCtx = true;
164
+ }
165
+ await next();
166
+ if (hasDefaultExecutionCtx === true) await Promise.allSettled(ctx.get("toAwait"));
167
+ });
168
+
169
+ //#endregion
170
+ //#region src/api/middleware/set-renderer.ts
171
+ /**
172
+ * Sets the renderer for the context.
173
+ *
174
+ * @todo `options.hono?.advanced?.cbor === true ? cborRespond : ctx.json`
175
+ */
176
+ const setRenderer = createMiddleware()(async (ctx, next) => {
177
+ ctx.setRenderer(initRenderer(ctx));
178
+ return await next();
179
+ });
180
+
181
+ //#endregion
182
+ //#region src/api/factory/endpoint.ts
183
+ /**
184
+ * Creates an auth endpoint.
185
+ * @template C - The route config type.
186
+ * @param config - The route configuration.
187
+ * @param handler - The route handler function.
188
+ * @param hook - Optional route hook.
189
+ * @returns The auth endpoint function.
190
+ */
191
+ const createEndpoint = (config, handler, hook) => {
192
+ let bundle = null;
193
+ return ((options) => {
194
+ const resolvedHandler = handler(options);
195
+ let localApp = null;
196
+ const execute = logged_default.wrap(async (...args) => {
197
+ if (!bundle) throw new Error(`${config.operationId} config() must be called before using execute()!`);
198
+ const [inputOrCtx, maybeCtx] = args;
199
+ const { input, ctx, opts } = isContextLike(inputOrCtx) ? {
200
+ input: void 0,
201
+ ctx: inputOrCtx,
202
+ opts: void 0
203
+ } : isContextLike(maybeCtx) ? {
204
+ input: inputOrCtx,
205
+ ctx: maybeCtx,
206
+ opts: void 0
207
+ } : isExecOpts(inputOrCtx) ? {
208
+ input: void 0,
209
+ ctx: void 0,
210
+ opts: inputOrCtx
211
+ } : {
212
+ input: inputOrCtx,
213
+ ctx: void 0,
214
+ opts: isExecOpts(maybeCtx) ? maybeCtx : void 0
215
+ };
216
+ if (ctx == null) {
217
+ if (localApp == null) throw new Error(`${config.operationId} handler() must be called before using server-side execute()!`);
218
+ const res$1 = localApp.fetch(new Request(...bundle.builder(input, opts?.headers)));
219
+ if (opts?.returnHeaders === true) return res$1 instanceof Response ? bundle.parser(res$1).then((r) => ({
220
+ headers: res$1.headers,
221
+ response: r
222
+ })) : res$1.then((re) => bundle.parser(re).then((r) => ({
223
+ headers: re.headers,
224
+ response: r
225
+ })));
226
+ if (opts?.asResponse === true) return res$1;
227
+ return Promise.resolve(res$1).then((r) => bundle.parser(r));
228
+ }
229
+ const out = await resolvedHandler(withOverlays(ctx, input, config), async () => {
230
+ throw new Error("next() called in manual execution when response was expected");
231
+ });
232
+ return bundle.parser(out);
233
+ }, config.operationId, "immediate");
234
+ execute.toArgs = (builtSchemas, context, api, routeHook = hook) => {
235
+ if (!bundle) bundle = buildRouteBundle(config, resolvedHandler, getBaseURL(options.baseURL, options.basePath), options, builtSchemas, routeHook, context.logger);
236
+ else if (!isTest()) context.logger.warn(`${bundle.resolvedConfig.operationId} config() already initialized`);
237
+ if (!localApp) localApp = createRouteAppWrapper(bundle.routeApp, [
238
+ serverApiMiddleware,
239
+ setDefaultExecutionCtx,
240
+ setRenderer,
241
+ initContextMiddleware(options, context, api),
242
+ contextStorage(),
243
+ initHooksMiddleware(options)
244
+ ], initErrorHandler(options), options.basePath);
245
+ else if (!isTest()) context.logger.warn(`${config.operationId} handler() was called when already initialized`);
246
+ return [
247
+ bundle.resolvedConfig,
248
+ resolvedHandler,
249
+ routeHook
250
+ ];
251
+ };
252
+ return execute;
253
+ });
254
+ };
255
+ const createAPI = (endpoints) => endpoints;
256
+
257
+ //#endregion
258
+ //#region src/api/schema/session.ts
259
+ const getSessionQuerySchema = z$1.object({
260
+ disableCookieCache: z$1.boolean().or(z$1.string().transform((v) => v === "true")).openapi({
261
+ param: {
262
+ in: "query",
263
+ name: "disableCookieCache"
264
+ },
265
+ description: "Disable cookie cache and fetch session from database"
266
+ }),
267
+ disableRefresh: z$1.boolean().or(z$1.string().transform((v) => v === "true")).openapi({
268
+ param: {
269
+ in: "query",
270
+ name: "disableRefresh"
271
+ },
272
+ description: "Disable session refresh. Useful for checking session status, without updating the session"
273
+ })
274
+ }).partial();
275
+ const revokeSessionSchema = z$1.object({ token: z$1.string().openapi({ description: "The token to revoke" }) });
276
+
277
+ //#endregion
278
+ //#region src/api/routes/session.ts
279
+ const getSessionRoute = createRoute({
280
+ operationId: Routes.GET_SESSION,
281
+ method: "get",
282
+ path: "/get-session",
283
+ description: "Get the current session",
284
+ request: req().qry(getSessionQuerySchema).bld(),
285
+ responses: res(SCHEMAS[Definitions.SESSION_USER].default).err(401, "Failed to get session or expired").zod().err(500, "Unexpected Error").bld()
286
+ });
287
+ const getSession = createEndpoint(getSessionRoute, (options) => async (ctx) => {
288
+ const { disableCookieCache, disableRefresh } = ctx.req.valid("query");
289
+ const context = ctx.get("context");
290
+ try {
291
+ const sessionCookieToken = await (0, cookies_exports.getSignedCookie)(ctx, context.secret, context.authCookies.sessionToken.name);
292
+ if (sessionCookieToken == null) return ctx.render({
293
+ success: False,
294
+ message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION
295
+ }, 401);
296
+ if (sessionCookieToken === false) return ctx.render({
297
+ success: False,
298
+ message: BASE_ERROR_CODES.SESSION_EXPIRED
299
+ }, 401);
300
+ const sessionDataCookie = (0, cookies_exports.getCookie)(ctx, context.authCookies.sessionData.name);
301
+ const sessionDataPayload = sessionDataCookie != null ? safeJSONParse(binary.decode(base64Url.decode(sessionDataCookie))) : null;
302
+ if (sessionDataPayload) {
303
+ if (!await createHMAC("SHA-256", "base64urlnopad").verify(context.secret, JSON.stringify({
304
+ ...sessionDataPayload.session,
305
+ expiresAt: sessionDataPayload.expiresAt
306
+ }), sessionDataPayload.signature)) {
307
+ (0, cookies_exports.deleteCookie)(ctx, context.authCookies.sessionData.name, context.authCookies.sessionData.options);
308
+ return ctx.render({
309
+ success: False,
310
+ message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION
311
+ }, 401);
312
+ }
313
+ }
314
+ const dontRememberMe = await (0, cookies_exports.getSignedCookie)(ctx, context.secret, context.authCookies.dontRememberToken.name);
315
+ /**
316
+ * If session data is present in the cookie, return it
317
+ */
318
+ if (sessionDataPayload?.session && options.session?.cookieCache?.enabled === true && disableCookieCache !== true) {
319
+ const { session: session$1 } = sessionDataPayload;
320
+ if (!(session$1.session.createdAt instanceof Date) || !(session$1.session.updatedAt instanceof Date) || !(session$1.session.expiresAt instanceof Date) || !(session$1.user.createdAt instanceof Date) || !(session$1.user.updatedAt instanceof Date)) console.warn("not date ln 122");
321
+ if (!(sessionDataPayload.expiresAt < Date.now() || session$1.session.expiresAt < /* @__PURE__ */ new Date())) {
322
+ ctx.set("session", session$1);
323
+ return ctx.render(session$1, 200);
324
+ }
325
+ (0, cookies_exports.deleteCookie)(ctx, context.authCookies.sessionData.name, context.authCookies.sessionData.options);
326
+ }
327
+ const session = await context.internalAdapter.findSession(sessionCookieToken);
328
+ ctx.set("session", session);
329
+ if (!session || session.session.expiresAt < /* @__PURE__ */ new Date()) {
330
+ deleteSessionCookie(ctx);
331
+ if (session) {
332
+ await context.internalAdapter.deleteSession(session.session.token);
333
+ return ctx.render({
334
+ success: False,
335
+ message: BASE_ERROR_CODES.SESSION_EXPIRED
336
+ }, 401);
337
+ }
338
+ return ctx.render({
339
+ success: False,
340
+ message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION
341
+ }, 401);
342
+ }
343
+ /**
344
+ * We don't need to update the session if the user doesn't want to be remembered
345
+ * or if the session refresh is disabled
346
+ */
347
+ if (dontRememberMe != null && dontRememberMe !== false || disableRefresh === true) return ctx.render(session, 200);
348
+ const { expiresIn, updateAge } = context.sessionConfig;
349
+ if (session.session.expiresAt.valueOf() - expiresIn * 1e3 + updateAge * 1e3 <= Date.now() && !options.session?.disableSessionRefresh) {
350
+ const updatedSession = await context.internalAdapter.updateSession(session.session.token, {
351
+ expiresAt: getDate(context.sessionConfig.expiresIn, "sec"),
352
+ updatedAt: /* @__PURE__ */ new Date()
353
+ });
354
+ if (updatedSession == null) {
355
+ /**
356
+ * Handle case where session update fails (e.g., concurrent deletion)
357
+ */
358
+ deleteSessionCookie(ctx);
359
+ return ctx.render({
360
+ success: False,
361
+ message: BASE_ERROR_CODES.FAILED_TO_CREATE_SESSION
362
+ }, 401);
363
+ }
364
+ const maxAge = (updatedSession.expiresAt.valueOf() - Date.now()) / 1e3;
365
+ await setSessionCookie(ctx, options, {
366
+ session: updatedSession,
367
+ user: session.user
368
+ }, false, { maxAge });
369
+ if (!(updatedSession.createdAt instanceof Date) || !(updatedSession.updatedAt instanceof Date) || !(updatedSession.expiresAt instanceof Date) || !(session.user.createdAt instanceof Date) || !(session.user.updatedAt instanceof Date)) console.warn("not date ln 220");
370
+ return ctx.render({
371
+ session: updatedSession,
372
+ user: session.user
373
+ }, 200);
374
+ }
375
+ if (options.session?.cookieCache?.enabled === true) await setCookieCache(ctx, options, session, dontRememberMe);
376
+ if (!(session.session.createdAt instanceof Date) || !(session.session.updatedAt instanceof Date) || !(session.session.expiresAt instanceof Date) || !(session.user.createdAt instanceof Date) || !(session.user.updatedAt instanceof Date)) console.warn("not date ln 231");
377
+ return ctx.render(session, 200);
378
+ } catch (error) {
379
+ context.logger.error("INTERNAL_SERVER_ERROR", error);
380
+ return ctx.render({
381
+ success: False,
382
+ message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION
383
+ }, 500);
384
+ }
385
+ });
386
+ const getSessionFromCtx = async (ctx, config) => {
387
+ const session = ctx.get("session");
388
+ if (session) return session;
389
+ const newSession = await ctx.get("api").getSession({ query: { ...config && config } }, ctx).then(async (s) => s.success === true ? {
390
+ success: true,
391
+ data: {
392
+ session: looseSessionSchema.parse(s.data.session),
393
+ user: looseUserSchema.parse(s.data.user)
394
+ }
395
+ } : s);
396
+ if (newSession.success === false) return ctx.render(session ?? {
397
+ success: False,
398
+ message: BASE_ERROR_CODES.FAILED_TO_GET_SESSION
399
+ }, 401);
400
+ ctx.set("session", newSession.data);
401
+ return newSession.data;
402
+ };
403
+ /**
404
+ * The middleware forces the endpoint to require a valid session.
405
+ */
406
+ const sessionMiddleware = () => createMiddleware()(async (ctx, next) => {
407
+ const session = await getSessionFromCtx(ctx);
408
+ if (session instanceof Response) return session;
409
+ return await next();
410
+ });
411
+ /**
412
+ * This middleware forces the endpoint to require a valid session and ignores cookie cache.
413
+ * This should be used for sensitive operations like password changes, account deletion, etc.
414
+ * to ensure that revoked sessions cannot be used even if they're still cached in cookies.
415
+ */
416
+ const sensitiveSessionMiddleware = createMiddleware()(async (ctx, next) => {
417
+ const session = await getSessionFromCtx(ctx, { disableCookieCache: true });
418
+ if (session instanceof Response) return session;
419
+ return await next();
420
+ });
421
+ /**
422
+ * This middleware allows you to call the endpoint on the client if session is valid.
423
+ * However, if called on the server, no session is required.
424
+ */
425
+ const requestOnlySessionMiddleware = createMiddleware()(async (ctx, next) => {
426
+ const session = await getSessionFromCtx(ctx);
427
+ if (session instanceof Response && ctx.get("isServer") !== true) return session;
428
+ return await next();
429
+ });
430
+ /**
431
+ * This middleware forces the endpoint to require a valid session,
432
+ * as well as making sure the session is fresh before proceeding.
433
+ *
434
+ * Session freshness check will be skipped if the session config's freshAge
435
+ * is set to 0
436
+ */
437
+ const freshSessionMiddleware = createMiddleware()(async (ctx, next) => {
438
+ const session = await getSessionFromCtx(ctx);
439
+ if (session instanceof Response) return session;
440
+ const context = ctx.get("context");
441
+ if (context.sessionConfig.freshAge === 0) return await next();
442
+ const lastUpdated = (session.session.updatedAt ?? session.session.createdAt).valueOf();
443
+ if (!(Date.now() - lastUpdated < context.sessionConfig.freshAge * 1e3)) return ctx.render({
444
+ success: False,
445
+ message: "Session is not fresh"
446
+ }, 403);
447
+ return await next();
448
+ });
449
+ const listSessionsRoute = createRoute({
450
+ operationId: Routes.LIST_SESSIONS,
451
+ method: "get",
452
+ path: "/list-sessions",
453
+ description: "List all active sessions for the user",
454
+ middleware: [sessionMiddleware()],
455
+ responses: res(SCHEMAS[Definitions.SESSIONS_LIST].default).err(500).bld()
456
+ });
457
+ const listSessions = createEndpoint(listSessionsRoute, (_options) => async (ctx) => {
458
+ try {
459
+ const activeSessions = (await ctx.get("context").internalAdapter.listSessions(ctx.get("session").user.id)).filter((s) => s.expiresAt > /* @__PURE__ */ new Date());
460
+ return ctx.render(activeSessions, 200);
461
+ } catch (e) {
462
+ ctx.get("context").logger.error(e instanceof Error ? e.message : String(e), e);
463
+ return ctx.render({
464
+ success: False,
465
+ message: "Internal server error"
466
+ }, 500);
467
+ }
468
+ });
469
+ const revokeSessionRoute = createRoute({
470
+ operationId: Routes.REVOKE_SESSION,
471
+ method: "post",
472
+ path: "/revoke-session",
473
+ description: "Revoke a single session",
474
+ middleware: [sensitiveSessionMiddleware],
475
+ request: req().bdy(revokeSessionSchema).bld(),
476
+ responses: res(SCHEMAS[Definitions.SUCCESS].default).zod().err(400).err(401).err(500).bld()
477
+ });
478
+ const revokeSession = createEndpoint(revokeSessionRoute, (_options) => async (ctx) => {
479
+ const context = ctx.get("context");
480
+ const session = ctx.get("session");
481
+ const { token } = ctx.req.valid("json");
482
+ const foundSession = await context.internalAdapter.findSession(token);
483
+ if (!foundSession) return ctx.render({
484
+ success: False,
485
+ message: "Session not found"
486
+ }, 400);
487
+ if (foundSession.session.userId !== session.user.id) return ctx.render({ success: False }, 401);
488
+ try {
489
+ await context.internalAdapter.deleteSession(token);
490
+ } catch (error) {
491
+ context.logger.error(error != null && typeof error === "object" && "name" in error ? String(error.name) : "Unknown Error", error);
492
+ return ctx.render({
493
+ success: False,
494
+ message: "Internal server error"
495
+ }, 500);
496
+ }
497
+ return ctx.render({ success: True }, 200);
498
+ });
499
+ const revokeSessionsRoute = createRoute({
500
+ operationId: Routes.REVOKE_SESSIONS,
501
+ method: "post",
502
+ path: "/revoke-sessions",
503
+ description: "Revoke all sessions for the user",
504
+ middleware: [sensitiveSessionMiddleware],
505
+ responses: res(SCHEMAS[Definitions.SUCCESS].default).err(500).bld()
506
+ });
507
+ const revokeSessions = createEndpoint(revokeSessionsRoute, (_options) => async (ctx) => {
508
+ const context = ctx.get("context");
509
+ const session = ctx.get("session");
510
+ try {
511
+ await context.internalAdapter.deleteSessions(session.user.id);
512
+ } catch (error) {
513
+ context.logger.error(error != null && typeof error === "object" && "name" in error ? String(error.name) : "Unknown Error", error);
514
+ return ctx.render({
515
+ success: False,
516
+ message: "Internal server error"
517
+ }, 500);
518
+ }
519
+ return ctx.render({ success: True }, 200);
520
+ });
521
+ const revokeOtherSessionsRoute = createRoute({
522
+ operationId: Routes.REVOKE_OTHER_SESSIONS,
523
+ method: "post",
524
+ path: "/revoke-other-sessions",
525
+ description: "Revoke all other sessions for the user except the current one",
526
+ middleware: [sensitiveSessionMiddleware],
527
+ responses: res(SCHEMAS[Definitions.SUCCESS].default).bld()
528
+ });
529
+ const revokeOtherSessions = createEndpoint(revokeOtherSessionsRoute, (_options) => async (ctx) => {
530
+ const context = ctx.get("context");
531
+ const session = ctx.get("session");
532
+ const otherSessions = (await context.internalAdapter.listSessions(session.user.id)).filter((session$1) => session$1.expiresAt > /* @__PURE__ */ new Date()).filter((sess) => sess.token !== session.session.token);
533
+ await Promise.all(otherSessions.map(async (session$1) => context.internalAdapter.deleteSession(session$1.token)));
534
+ return ctx.render({ success: True }, 200);
535
+ });
536
+
537
+ //#endregion
538
+ export { initContextMiddleware as _, requestOnlySessionMiddleware as a, revokeSessions as c, createAPI as d, createEndpoint as f, initHooksMiddleware as g, initErrorHandler as h, listSessions as i, sensitiveSessionMiddleware as l, setDefaultExecutionCtx as m, getSession as n, revokeOtherSessions as o, setRenderer as p, getSessionFromCtx as r, revokeSession as s, freshSessionMiddleware as t, sessionMiddleware as u };
@@ -0,0 +1,10 @@
1
+ const require_social_providers = require('../social-providers-DcFNUT0S.cjs');
2
+
3
+
4
+ var __faire_auth_core_social_providers = require("@faire-auth/core/social-providers");
5
+ Object.keys(__faire_auth_core_social_providers).forEach(function (k) {
6
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
7
+ enumerable: true,
8
+ get: function () { return __faire_auth_core_social_providers[k]; }
9
+ });
10
+ });
@@ -0,0 +1,2 @@
1
+ import "../index-B7SKyR_a.cjs";
2
+ export * from "@faire-auth/core/social-providers";
@@ -0,0 +1,2 @@
1
+ import "../index-B5_0QTLg.mjs";
2
+ export * from "@faire-auth/core/social-providers";
@@ -0,0 +1,5 @@
1
+ import "../social-providers-DoYJhBe3.mjs";
2
+
3
+ export * from "@faire-auth/core/social-providers"
4
+
5
+ export { };
@@ -0,0 +1,13 @@
1
+ const require_chunk = require('./chunk-oakRccI5.cjs');
2
+
3
+ //#region src/social-providers/index.ts
4
+ var social_providers_exports = {};
5
+ require_chunk.__reExport(social_providers_exports, require("@faire-auth/core/social-providers"));
6
+
7
+ //#endregion
8
+ Object.defineProperty(exports, 'social_providers_exports', {
9
+ enumerable: true,
10
+ get: function () {
11
+ return social_providers_exports;
12
+ }
13
+ });
@@ -0,0 +1,9 @@
1
+ import { r as __reExport } from "./chunk-Ceigfy4P.mjs";
2
+
3
+ //#region src/social-providers/index.ts
4
+ var social_providers_exports = {};
5
+ import * as import___faire_auth_core_social_providers from "@faire-auth/core/social-providers";
6
+ __reExport(social_providers_exports, import___faire_auth_core_social_providers);
7
+
8
+ //#endregion
9
+ export { social_providers_exports as t };
@@ -0,0 +1,99 @@
1
+ const require_chunk = require('./chunk-oakRccI5.cjs');
2
+ const require_crypto = require('./crypto-CcTxYH82.cjs');
3
+ let __faire_auth_core_error = require("@faire-auth/core/error");
4
+ let __faire_auth_core_factory = require("@faire-auth/core/factory");
5
+ let zod = require("zod");
6
+ zod = require_chunk.__toESM(zod);
7
+
8
+ //#region src/oauth2/state.ts
9
+ const generateState = async (ctx, link, options) => {
10
+ let { callbackURL, errorCallbackURL, newUserCallbackURL, requestSignUp } = ctx.req.valid("json");
11
+ callbackURL = callbackURL ?? options?.baseURL;
12
+ if (callbackURL == null) throw new __faire_auth_core_error.APIError("BAD_REQUEST", { message: "callbackURL or baseURL is required" });
13
+ const context = ctx.get("context");
14
+ const codeVerifier = (0, require_crypto.crypto_exports.generateRandomString)(128);
15
+ const state = (0, require_crypto.crypto_exports.generateRandomString)(32);
16
+ const data = JSON.stringify({
17
+ callbackURL,
18
+ codeVerifier,
19
+ ...errorCallbackURL && { errorURL: errorCallbackURL },
20
+ ...newUserCallbackURL && { newUserURL: newUserCallbackURL },
21
+ expiresAt: Date.now() + 600 * 1e3,
22
+ ...link && { link },
23
+ ...requestSignUp && { requestSignUp }
24
+ });
25
+ const expiresAt = /* @__PURE__ */ new Date();
26
+ expiresAt.setMinutes(expiresAt.getMinutes() + 10);
27
+ const verification = await context.internalAdapter.createVerificationValue({
28
+ value: data,
29
+ identifier: state,
30
+ expiresAt
31
+ });
32
+ if (verification == null) {
33
+ context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database");
34
+ throw new __faire_auth_core_error.APIError("INTERNAL_SERVER_ERROR", { message: "Unable to create verification" });
35
+ }
36
+ return {
37
+ state: verification.identifier,
38
+ codeVerifier
39
+ };
40
+ };
41
+ const parsingSchema = zod.object({
42
+ callbackURL: zod.string(),
43
+ codeVerifier: zod.string(),
44
+ errorURL: zod.string().optional(),
45
+ newUserURL: zod.string().optional(),
46
+ expiresAt: zod.number(),
47
+ link: zod.object({
48
+ email: __faire_auth_core_factory.emailSchema,
49
+ userId: zod.coerce.string()
50
+ }).optional(),
51
+ requestSignUp: zod.boolean().optional()
52
+ });
53
+ const parseState = async (ctx, options) => {
54
+ let state;
55
+ try {
56
+ state = ctx.req.valid("json").state;
57
+ } catch {
58
+ state = ctx.req.valid("query").state;
59
+ }
60
+ const context = ctx.get("context");
61
+ const data = await context.internalAdapter.findVerificationValue(state);
62
+ if (data == null) {
63
+ context.logger.error("State Mismatch. Verification not found", { state });
64
+ const errorURL = options.onAPIError?.errorURL ?? `${context.baseURL}/error`;
65
+ return {
66
+ type: "redirect",
67
+ response: ctx.redirect(`${errorURL}?error=please_restart_the_process`, 302)
68
+ };
69
+ }
70
+ const parsedData = parsingSchema.parse(JSON.parse(data.value));
71
+ parsedData.errorURL ??= `${context.baseURL}/error`;
72
+ if (parsedData.expiresAt < Date.now()) {
73
+ await context.internalAdapter.deleteVerificationValue(data.id);
74
+ const errorURL = options.onAPIError?.errorURL ?? `${context.baseURL}/error`;
75
+ return {
76
+ type: "redirect",
77
+ response: ctx.redirect(`${errorURL}?error=please_restart_the_process`, 302)
78
+ };
79
+ }
80
+ await context.internalAdapter.deleteVerificationValue(data.id);
81
+ return {
82
+ type: "success",
83
+ data: parsedData
84
+ };
85
+ };
86
+
87
+ //#endregion
88
+ Object.defineProperty(exports, 'generateState', {
89
+ enumerable: true,
90
+ get: function () {
91
+ return generateState;
92
+ }
93
+ });
94
+ Object.defineProperty(exports, 'parseState', {
95
+ enumerable: true,
96
+ get: function () {
97
+ return parseState;
98
+ }
99
+ });