@alepha/react 0.11.10 → 0.11.12
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.
- package/README.md +1 -183
- package/dist/auth/index.browser.js +1460 -0
- package/dist/auth/index.browser.js.map +1 -0
- package/dist/auth/index.cjs +3647 -0
- package/dist/auth/index.cjs.map +1 -0
- package/dist/auth/index.d.cts +564 -0
- package/dist/auth/index.d.cts.map +1 -0
- package/dist/auth/index.d.ts +564 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +3615 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/{index.browser.js → core/index.browser.js} +36 -35
- package/dist/core/index.browser.js.map +1 -0
- package/dist/{index.cjs → core/index.cjs} +141 -140
- package/dist/core/index.cjs.map +1 -0
- package/dist/{index.d.cts → core/index.d.cts} +68 -68
- package/dist/core/index.d.cts.map +1 -0
- package/dist/{index.d.ts → core/index.d.ts} +68 -68
- package/dist/core/index.d.ts.map +1 -0
- package/dist/{index.js → core/index.js} +39 -38
- package/dist/core/index.js.map +1 -0
- package/dist/form/index.cjs +2054 -0
- package/dist/form/index.cjs.map +1 -0
- package/dist/form/index.d.cts +211 -0
- package/dist/form/index.d.cts.map +1 -0
- package/dist/form/index.d.ts +211 -0
- package/dist/form/index.d.ts.map +1 -0
- package/dist/form/index.js +2026 -0
- package/dist/form/index.js.map +1 -0
- package/dist/head/index.browser.js +1503 -0
- package/dist/head/index.browser.js.map +1 -0
- package/dist/head/index.cjs +1908 -0
- package/dist/head/index.cjs.map +1 -0
- package/dist/head/index.d.cts +595 -0
- package/dist/head/index.d.cts.map +1 -0
- package/dist/head/index.d.ts +601 -0
- package/dist/head/index.d.ts.map +1 -0
- package/dist/head/index.js +1880 -0
- package/dist/head/index.js.map +1 -0
- package/dist/i18n/index.cjs +1886 -0
- package/dist/i18n/index.cjs.map +1 -0
- package/dist/i18n/index.d.cts +168 -0
- package/dist/i18n/index.d.cts.map +1 -0
- package/dist/i18n/index.d.ts +168 -0
- package/dist/i18n/index.d.ts.map +1 -0
- package/dist/i18n/index.js +1857 -0
- package/dist/i18n/index.js.map +1 -0
- package/dist/websocket/index.cjs +1774 -0
- package/dist/websocket/index.cjs.map +1 -0
- package/dist/websocket/index.d.cts +118 -0
- package/dist/websocket/index.d.cts.map +1 -0
- package/dist/websocket/index.d.ts +118 -0
- package/dist/websocket/index.d.ts.map +1 -0
- package/dist/websocket/index.js +1750 -0
- package/dist/websocket/index.js.map +1 -0
- package/package.json +89 -67
- package/src/auth/descriptors/$auth.ts +436 -0
- package/src/auth/descriptors/$authApple.ts +8 -0
- package/src/auth/descriptors/$authGithub.ts +81 -0
- package/src/auth/descriptors/$authGoogle.ts +38 -0
- package/src/auth/errors/SessionExpiredError.ts +6 -0
- package/src/auth/hooks/useAuth.ts +31 -0
- package/src/auth/index.browser.ts +16 -0
- package/src/auth/index.shared.ts +3 -0
- package/src/auth/index.ts +47 -0
- package/src/auth/providers/ReactAuthProvider.ts +629 -0
- package/src/auth/schemas/tokenResponseSchema.ts +11 -0
- package/src/auth/schemas/tokensSchema.ts +21 -0
- package/src/auth/schemas/userinfoResponseSchema.ts +10 -0
- package/src/auth/services/ReactAuth.ts +124 -0
- package/src/{components → core/components}/ErrorViewer.tsx +3 -2
- package/src/{components → core/components}/NestedView.tsx +1 -1
- package/src/{contexts → core/contexts}/AlephaContext.ts +1 -1
- package/src/{descriptors → core/descriptors}/$page.ts +4 -4
- package/src/{hooks → core/hooks}/useAction.ts +1 -1
- package/src/{hooks → core/hooks}/useAlepha.ts +1 -1
- package/src/{hooks → core/hooks}/useClient.ts +1 -1
- package/src/{hooks → core/hooks}/useEvents.ts +1 -1
- package/src/{hooks → core/hooks}/useInject.ts +1 -1
- package/src/{hooks → core/hooks}/useQueryParams.ts +1 -1
- package/src/{hooks → core/hooks}/useRouterState.ts +1 -1
- package/src/{hooks → core/hooks}/useSchema.ts +3 -3
- package/src/{hooks → core/hooks}/useStore.ts +2 -2
- package/src/{index.browser.ts → core/index.browser.ts} +4 -4
- package/src/{index.ts → core/index.ts} +6 -6
- package/src/{providers → core/providers}/ReactBrowserProvider.ts +6 -6
- package/src/{providers → core/providers}/ReactBrowserRendererProvider.ts +2 -2
- package/src/{providers → core/providers}/ReactBrowserRouterProvider.ts +3 -3
- package/src/{providers → core/providers}/ReactPageProvider.ts +3 -3
- package/src/{providers → core/providers}/ReactServerProvider.ts +7 -7
- package/src/{services → core/services}/ReactPageServerService.ts +2 -2
- package/src/{services → core/services}/ReactPageService.ts +1 -1
- package/src/{services → core/services}/ReactRouter.ts +1 -1
- package/src/form/components/FormState.tsx +17 -0
- package/src/form/hooks/useForm.ts +47 -0
- package/src/form/hooks/useFormState.ts +130 -0
- package/src/form/index.ts +38 -0
- package/src/form/services/FormModel.ts +548 -0
- package/src/head/descriptors/$head.ts +25 -0
- package/src/head/hooks/useHead.ts +62 -0
- package/src/head/index.browser.ts +25 -0
- package/src/head/index.ts +47 -0
- package/src/head/interfaces/Head.ts +46 -0
- package/src/head/providers/BrowserHeadProvider.ts +105 -0
- package/src/head/providers/HeadProvider.ts +73 -0
- package/src/head/providers/ServerHeadProvider.ts +109 -0
- package/src/i18n/README.md +76 -0
- package/src/i18n/components/Localize.tsx +35 -0
- package/src/i18n/descriptors/$dictionary.ts +65 -0
- package/src/i18n/hooks/useI18n.ts +18 -0
- package/src/i18n/index.ts +34 -0
- package/src/i18n/providers/I18nProvider.ts +277 -0
- package/src/websocket/hooks/useRoom.tsx +223 -0
- package/src/websocket/index.ts +7 -0
- package/dist/index.browser.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- /package/src/{components → core/components}/ClientOnly.tsx +0 -0
- /package/src/{components → core/components}/ErrorBoundary.tsx +0 -0
- /package/src/{components → core/components}/Link.tsx +0 -0
- /package/src/{components → core/components}/NotFound.tsx +0 -0
- /package/src/{contexts → core/contexts}/RouterLayerContext.ts +0 -0
- /package/src/{errors → core/errors}/Redirection.ts +0 -0
- /package/src/{hooks → core/hooks}/useActive.ts +0 -0
- /package/src/{hooks → core/hooks}/useRouter.ts +0 -0
- /package/src/{index.shared.ts → core/index.shared.ts} +0 -0
|
@@ -0,0 +1,3615 @@
|
|
|
1
|
+
import { $atom, $context, $env, $hook, $inject, $module, $use, Alepha, AlephaError, Atom, Descriptor, KIND, createDescriptor, t } from "alepha";
|
|
2
|
+
import { AlephaDateTime, DateTimeProvider } from "alepha/datetime";
|
|
3
|
+
import { $route, AlephaServer, BadRequestError, HttpClient, ServerProvider, ServerRouterProvider, ServerTimingProvider, UnauthorizedError } from "alepha/server";
|
|
4
|
+
import { AlephaServerCache } from "alepha/server/cache";
|
|
5
|
+
import { AlephaServerLinks, LinkProvider, ServerLinksProvider, apiLinksResponseSchema } from "alepha/server/links";
|
|
6
|
+
import { $logger } from "alepha/logger";
|
|
7
|
+
import React, { StrictMode, createContext, createElement, memo, use, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
8
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
9
|
+
import { existsSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { ServerStaticProvider } from "alepha/server/static";
|
|
12
|
+
import { renderToString } from "react-dom/server";
|
|
13
|
+
import { RouterProvider } from "alepha/router";
|
|
14
|
+
import { $cookie, AlephaServerCookies, ServerCookiesProvider } from "alepha/server/cookies";
|
|
15
|
+
import { SecurityError, SecurityProvider, userAccountInfoSchema } from "alepha/security";
|
|
16
|
+
|
|
17
|
+
//#region src/core/services/ReactPageService.ts
|
|
18
|
+
var ReactPageService = class {
|
|
19
|
+
fetch(pathname, options = {}) {
|
|
20
|
+
throw new AlephaError("Fetch is not available for this environment.");
|
|
21
|
+
}
|
|
22
|
+
render(name, options = {}) {
|
|
23
|
+
throw new AlephaError("Render is not available for this environment.");
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/core/descriptors/$page.ts
|
|
29
|
+
/**
|
|
30
|
+
* Main descriptor for defining a React route in the application.
|
|
31
|
+
*
|
|
32
|
+
* The $page descriptor is the core building block for creating type-safe, SSR-enabled React routes.
|
|
33
|
+
* It provides a declarative way to define pages with powerful features:
|
|
34
|
+
*
|
|
35
|
+
* **Routing & Navigation**
|
|
36
|
+
* - URL pattern matching with parameters (e.g., `/users/:id`)
|
|
37
|
+
* - Nested routing with parent-child relationships
|
|
38
|
+
* - Type-safe URL parameter and query string validation
|
|
39
|
+
*
|
|
40
|
+
* **Data Loading**
|
|
41
|
+
* - Server-side data fetching with the `resolve` function
|
|
42
|
+
* - Automatic serialization and hydration for SSR
|
|
43
|
+
* - Access to request context, URL params, and parent data
|
|
44
|
+
*
|
|
45
|
+
* **Component Loading**
|
|
46
|
+
* - Direct component rendering or lazy loading for code splitting
|
|
47
|
+
* - Client-only rendering when browser APIs are needed
|
|
48
|
+
* - Automatic fallback handling during hydration
|
|
49
|
+
*
|
|
50
|
+
* **Performance Optimization**
|
|
51
|
+
* - Static generation for pre-rendered pages at build time
|
|
52
|
+
* - Server-side caching with configurable TTL and providers
|
|
53
|
+
* - Code splitting through lazy component loading
|
|
54
|
+
*
|
|
55
|
+
* **Error Handling**
|
|
56
|
+
* - Custom error handlers with support for redirects
|
|
57
|
+
* - Hierarchical error handling (child → parent)
|
|
58
|
+
* - HTTP status code handling (404, 401, etc.)
|
|
59
|
+
*
|
|
60
|
+
* **Page Animations**
|
|
61
|
+
* - CSS-based enter/exit animations
|
|
62
|
+
* - Dynamic animations based on page state
|
|
63
|
+
* - Custom timing and easing functions
|
|
64
|
+
*
|
|
65
|
+
* **Lifecycle Management**
|
|
66
|
+
* - Server response hooks for headers and status codes
|
|
67
|
+
* - Page leave handlers for cleanup (browser only)
|
|
68
|
+
* - Permission-based access control
|
|
69
|
+
*
|
|
70
|
+
* @example Simple page with data fetching
|
|
71
|
+
* ```typescript
|
|
72
|
+
* const userProfile = $page({
|
|
73
|
+
* path: "/users/:id",
|
|
74
|
+
* schema: {
|
|
75
|
+
* params: t.object({ id: t.int() }),
|
|
76
|
+
* query: t.object({ tab: t.optional(t.text()) })
|
|
77
|
+
* },
|
|
78
|
+
* resolve: async ({ params }) => {
|
|
79
|
+
* const user = await userApi.getUser(params.id);
|
|
80
|
+
* return { user };
|
|
81
|
+
* },
|
|
82
|
+
* lazy: () => import("./UserProfile.tsx")
|
|
83
|
+
* });
|
|
84
|
+
* ```
|
|
85
|
+
*
|
|
86
|
+
* @example Nested routing with error handling
|
|
87
|
+
* ```typescript
|
|
88
|
+
* const projectSection = $page({
|
|
89
|
+
* path: "/projects/:id",
|
|
90
|
+
* children: () => [projectBoard, projectSettings],
|
|
91
|
+
* resolve: async ({ params }) => {
|
|
92
|
+
* const project = await projectApi.get(params.id);
|
|
93
|
+
* return { project };
|
|
94
|
+
* },
|
|
95
|
+
* errorHandler: (error) => {
|
|
96
|
+
* if (HttpError.is(error, 404)) {
|
|
97
|
+
* return <ProjectNotFound />;
|
|
98
|
+
* }
|
|
99
|
+
* }
|
|
100
|
+
* });
|
|
101
|
+
* ```
|
|
102
|
+
*
|
|
103
|
+
* @example Static generation with caching
|
|
104
|
+
* ```typescript
|
|
105
|
+
* const blogPost = $page({
|
|
106
|
+
* path: "/blog/:slug",
|
|
107
|
+
* static: {
|
|
108
|
+
* entries: posts.map(p => ({ params: { slug: p.slug } }))
|
|
109
|
+
* },
|
|
110
|
+
* resolve: async ({ params }) => {
|
|
111
|
+
* const post = await loadPost(params.slug);
|
|
112
|
+
* return { post };
|
|
113
|
+
* }
|
|
114
|
+
* });
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
const $page = (options) => {
|
|
118
|
+
return createDescriptor(PageDescriptor, options);
|
|
119
|
+
};
|
|
120
|
+
var PageDescriptor = class extends Descriptor {
|
|
121
|
+
reactPageService = $inject(ReactPageService);
|
|
122
|
+
onInit() {
|
|
123
|
+
if (this.options.static) this.options.cache ??= { store: {
|
|
124
|
+
provider: "memory",
|
|
125
|
+
ttl: [1, "week"]
|
|
126
|
+
} };
|
|
127
|
+
}
|
|
128
|
+
get name() {
|
|
129
|
+
return this.options.name ?? this.config.propertyKey;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* For testing or build purposes.
|
|
133
|
+
*
|
|
134
|
+
* This will render the page (HTML layout included or not) and return the HTML + context.
|
|
135
|
+
* Only valid for server-side rendering, it will throw an error if called on the client-side.
|
|
136
|
+
*/
|
|
137
|
+
async render(options) {
|
|
138
|
+
return this.reactPageService.render(this.name, options);
|
|
139
|
+
}
|
|
140
|
+
async fetch(options) {
|
|
141
|
+
return this.reactPageService.fetch(this.options.path || "", options);
|
|
142
|
+
}
|
|
143
|
+
match(url) {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
pathname(config) {
|
|
147
|
+
return this.options.path || "";
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
$page[KIND] = PageDescriptor;
|
|
151
|
+
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/core/components/ClientOnly.tsx
|
|
154
|
+
/**
|
|
155
|
+
* A small utility component that renders its children only on the client side.
|
|
156
|
+
*
|
|
157
|
+
* Optionally, you can provide a fallback React node that will be rendered.
|
|
158
|
+
*
|
|
159
|
+
* You should use this component when
|
|
160
|
+
* - you have code that relies on browser-specific APIs
|
|
161
|
+
* - you want to avoid server-side rendering for a specific part of your application
|
|
162
|
+
* - you want to prevent pre-rendering of a component
|
|
163
|
+
*/
|
|
164
|
+
const ClientOnly = (props$1) => {
|
|
165
|
+
const [mounted, setMounted] = useState(false);
|
|
166
|
+
useEffect(() => setMounted(true), []);
|
|
167
|
+
if (props$1.disabled) return props$1.children;
|
|
168
|
+
return mounted ? props$1.children : props$1.fallback;
|
|
169
|
+
};
|
|
170
|
+
var ClientOnly_default = ClientOnly;
|
|
171
|
+
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/core/components/ErrorViewer.tsx
|
|
174
|
+
const ErrorViewer = ({ error, alepha }) => {
|
|
175
|
+
const [expanded, setExpanded] = useState(false);
|
|
176
|
+
if (alepha.isProduction()) return /* @__PURE__ */ jsx(ErrorViewerProduction, {});
|
|
177
|
+
const stackLines = error.stack?.split("\n") ?? [];
|
|
178
|
+
const previewLines = stackLines.slice(0, 5);
|
|
179
|
+
const hiddenLineCount = stackLines.length - previewLines.length;
|
|
180
|
+
const copyToClipboard = (text) => {
|
|
181
|
+
navigator.clipboard.writeText(text).catch((err) => {
|
|
182
|
+
console.error("Clipboard error:", err);
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
const styles = {
|
|
186
|
+
container: {
|
|
187
|
+
padding: "24px",
|
|
188
|
+
backgroundColor: "#FEF2F2",
|
|
189
|
+
color: "#7F1D1D",
|
|
190
|
+
border: "1px solid #FECACA",
|
|
191
|
+
borderRadius: "16px",
|
|
192
|
+
boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
|
|
193
|
+
fontFamily: "monospace",
|
|
194
|
+
maxWidth: "768px",
|
|
195
|
+
margin: "40px auto"
|
|
196
|
+
},
|
|
197
|
+
heading: {
|
|
198
|
+
fontSize: "20px",
|
|
199
|
+
fontWeight: "bold",
|
|
200
|
+
marginBottom: "10px"
|
|
201
|
+
},
|
|
202
|
+
name: {
|
|
203
|
+
fontSize: "16px",
|
|
204
|
+
fontWeight: 600
|
|
205
|
+
},
|
|
206
|
+
message: {
|
|
207
|
+
fontSize: "14px",
|
|
208
|
+
marginBottom: "16px"
|
|
209
|
+
},
|
|
210
|
+
sectionHeader: {
|
|
211
|
+
display: "flex",
|
|
212
|
+
justifyContent: "space-between",
|
|
213
|
+
alignItems: "center",
|
|
214
|
+
fontSize: "12px",
|
|
215
|
+
marginBottom: "4px",
|
|
216
|
+
color: "#991B1B"
|
|
217
|
+
},
|
|
218
|
+
copyButton: {
|
|
219
|
+
fontSize: "12px",
|
|
220
|
+
color: "#DC2626",
|
|
221
|
+
background: "none",
|
|
222
|
+
border: "none",
|
|
223
|
+
cursor: "pointer",
|
|
224
|
+
textDecoration: "underline"
|
|
225
|
+
},
|
|
226
|
+
stackContainer: {
|
|
227
|
+
backgroundColor: "#FEE2E2",
|
|
228
|
+
padding: "12px",
|
|
229
|
+
borderRadius: "8px",
|
|
230
|
+
fontSize: "13px",
|
|
231
|
+
lineHeight: "1.4",
|
|
232
|
+
overflowX: "auto",
|
|
233
|
+
whiteSpace: "pre-wrap"
|
|
234
|
+
},
|
|
235
|
+
expandLine: {
|
|
236
|
+
color: "#F87171",
|
|
237
|
+
cursor: "pointer",
|
|
238
|
+
marginTop: "8px"
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
242
|
+
style: styles.container,
|
|
243
|
+
children: [/* @__PURE__ */ jsxs("div", { children: [
|
|
244
|
+
/* @__PURE__ */ jsx("div", {
|
|
245
|
+
style: styles.heading,
|
|
246
|
+
children: "🔥 Error"
|
|
247
|
+
}),
|
|
248
|
+
/* @__PURE__ */ jsx("div", {
|
|
249
|
+
style: styles.name,
|
|
250
|
+
children: error.name
|
|
251
|
+
}),
|
|
252
|
+
/* @__PURE__ */ jsx("div", {
|
|
253
|
+
style: styles.message,
|
|
254
|
+
children: error.message
|
|
255
|
+
})
|
|
256
|
+
] }), stackLines.length > 0 && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
|
|
257
|
+
style: styles.sectionHeader,
|
|
258
|
+
children: [/* @__PURE__ */ jsx("span", { children: "Stack trace" }), /* @__PURE__ */ jsx("button", {
|
|
259
|
+
type: "button",
|
|
260
|
+
onClick: () => copyToClipboard(error.stack),
|
|
261
|
+
style: styles.copyButton,
|
|
262
|
+
children: "Copy all"
|
|
263
|
+
})]
|
|
264
|
+
}), /* @__PURE__ */ jsxs("pre", {
|
|
265
|
+
style: styles.stackContainer,
|
|
266
|
+
children: [(expanded ? stackLines : previewLines).map((line, i) => /* @__PURE__ */ jsx("div", { children: line }, i)), !expanded && hiddenLineCount > 0 && /* @__PURE__ */ jsxs("div", {
|
|
267
|
+
style: styles.expandLine,
|
|
268
|
+
onClick: () => setExpanded(true),
|
|
269
|
+
children: [
|
|
270
|
+
"+ ",
|
|
271
|
+
hiddenLineCount,
|
|
272
|
+
" more lines..."
|
|
273
|
+
]
|
|
274
|
+
})]
|
|
275
|
+
})] })]
|
|
276
|
+
});
|
|
277
|
+
};
|
|
278
|
+
var ErrorViewer_default = ErrorViewer;
|
|
279
|
+
const ErrorViewerProduction = () => {
|
|
280
|
+
const styles = {
|
|
281
|
+
container: {
|
|
282
|
+
padding: "24px",
|
|
283
|
+
backgroundColor: "#FEF2F2",
|
|
284
|
+
color: "#7F1D1D",
|
|
285
|
+
border: "1px solid #FECACA",
|
|
286
|
+
borderRadius: "16px",
|
|
287
|
+
boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
|
|
288
|
+
fontFamily: "monospace",
|
|
289
|
+
maxWidth: "768px",
|
|
290
|
+
margin: "40px auto",
|
|
291
|
+
textAlign: "center"
|
|
292
|
+
},
|
|
293
|
+
heading: {
|
|
294
|
+
fontSize: "20px",
|
|
295
|
+
fontWeight: "bold",
|
|
296
|
+
marginBottom: "8px"
|
|
297
|
+
},
|
|
298
|
+
name: {
|
|
299
|
+
fontSize: "16px",
|
|
300
|
+
fontWeight: 600,
|
|
301
|
+
marginBottom: "4px"
|
|
302
|
+
},
|
|
303
|
+
message: {
|
|
304
|
+
fontSize: "14px",
|
|
305
|
+
opacity: .85
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
309
|
+
style: styles.container,
|
|
310
|
+
children: [/* @__PURE__ */ jsx("div", {
|
|
311
|
+
style: styles.heading,
|
|
312
|
+
children: "🚨 An error occurred"
|
|
313
|
+
}), /* @__PURE__ */ jsx("div", {
|
|
314
|
+
style: styles.message,
|
|
315
|
+
children: "Something went wrong. Please try again later."
|
|
316
|
+
})]
|
|
317
|
+
});
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
//#endregion
|
|
321
|
+
//#region src/core/contexts/RouterLayerContext.ts
|
|
322
|
+
const RouterLayerContext = createContext(void 0);
|
|
323
|
+
|
|
324
|
+
//#endregion
|
|
325
|
+
//#region src/core/errors/Redirection.ts
|
|
326
|
+
/**
|
|
327
|
+
* Used for Redirection during the page loading.
|
|
328
|
+
*
|
|
329
|
+
* Depends on the context, it can be thrown or just returned.
|
|
330
|
+
*/
|
|
331
|
+
var Redirection = class extends Error {
|
|
332
|
+
redirect;
|
|
333
|
+
constructor(redirect) {
|
|
334
|
+
super("Redirection");
|
|
335
|
+
this.redirect = redirect;
|
|
336
|
+
}
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
//#endregion
|
|
340
|
+
//#region src/core/contexts/AlephaContext.ts
|
|
341
|
+
const AlephaContext = createContext(void 0);
|
|
342
|
+
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region src/core/hooks/useAlepha.ts
|
|
345
|
+
/**
|
|
346
|
+
* Main Alepha hook.
|
|
347
|
+
*
|
|
348
|
+
* It provides access to the Alepha instance within a React component.
|
|
349
|
+
*
|
|
350
|
+
* With Alepha, you can access the core functionalities of the framework:
|
|
351
|
+
*
|
|
352
|
+
* - alepha.state() for state management
|
|
353
|
+
* - alepha.inject() for dependency injection
|
|
354
|
+
* - alepha.events.emit() for event handling
|
|
355
|
+
* etc...
|
|
356
|
+
*/
|
|
357
|
+
const useAlepha = () => {
|
|
358
|
+
const alepha = useContext(AlephaContext);
|
|
359
|
+
if (!alepha) throw new AlephaError("Hook 'useAlepha()' must be used within an AlephaContext.Provider");
|
|
360
|
+
return alepha;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
//#endregion
|
|
364
|
+
//#region src/core/hooks/useEvents.ts
|
|
365
|
+
/**
|
|
366
|
+
* Allow subscribing to multiple Alepha events. See {@link Hooks} for available events.
|
|
367
|
+
*
|
|
368
|
+
* useEvents is fully typed to ensure correct event callback signatures.
|
|
369
|
+
*
|
|
370
|
+
* @example
|
|
371
|
+
* ```tsx
|
|
372
|
+
* useEvents(
|
|
373
|
+
* {
|
|
374
|
+
* "react:transition:begin": (ev) => {
|
|
375
|
+
* console.log("Transition began to:", ev.to);
|
|
376
|
+
* },
|
|
377
|
+
* "react:transition:error": {
|
|
378
|
+
* priority: "first",
|
|
379
|
+
* callback: (ev) => {
|
|
380
|
+
* console.error("Transition error:", ev.error);
|
|
381
|
+
* },
|
|
382
|
+
* },
|
|
383
|
+
* },
|
|
384
|
+
* [],
|
|
385
|
+
* );
|
|
386
|
+
* ```
|
|
387
|
+
*/
|
|
388
|
+
const useEvents = (opts, deps) => {
|
|
389
|
+
const alepha = useAlepha();
|
|
390
|
+
useEffect(() => {
|
|
391
|
+
if (!alepha.isBrowser()) return;
|
|
392
|
+
const subs = [];
|
|
393
|
+
for (const [name, hook] of Object.entries(opts)) subs.push(alepha.events.on(name, hook));
|
|
394
|
+
return () => {
|
|
395
|
+
for (const clear of subs) clear();
|
|
396
|
+
};
|
|
397
|
+
}, deps);
|
|
398
|
+
};
|
|
399
|
+
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/core/hooks/useStore.ts
|
|
402
|
+
function useStore(target, defaultValue) {
|
|
403
|
+
const alepha = useAlepha();
|
|
404
|
+
useMemo(() => {
|
|
405
|
+
if (defaultValue != null && alepha.state.get(target) == null) alepha.state.set(target, defaultValue);
|
|
406
|
+
}, [defaultValue]);
|
|
407
|
+
const [state, setState] = useState(alepha.state.get(target));
|
|
408
|
+
useEffect(() => {
|
|
409
|
+
if (!alepha.isBrowser()) return;
|
|
410
|
+
const key = target instanceof Atom ? target.key : target;
|
|
411
|
+
return alepha.events.on("state:mutate", (ev) => {
|
|
412
|
+
if (ev.key === key) setState(ev.value);
|
|
413
|
+
});
|
|
414
|
+
}, []);
|
|
415
|
+
return [state, (value) => {
|
|
416
|
+
alepha.state.set(target, value);
|
|
417
|
+
}];
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
//#endregion
|
|
421
|
+
//#region src/core/hooks/useRouterState.ts
|
|
422
|
+
const useRouterState = () => {
|
|
423
|
+
const [state] = useStore("alepha.react.router.state");
|
|
424
|
+
if (!state) throw new AlephaError("Missing react router state");
|
|
425
|
+
return state;
|
|
426
|
+
};
|
|
427
|
+
|
|
428
|
+
//#endregion
|
|
429
|
+
//#region src/core/components/ErrorBoundary.tsx
|
|
430
|
+
/**
|
|
431
|
+
* A reusable error boundary for catching rendering errors
|
|
432
|
+
* in any part of the React component tree.
|
|
433
|
+
*/
|
|
434
|
+
var ErrorBoundary = class extends React.Component {
|
|
435
|
+
constructor(props$1) {
|
|
436
|
+
super(props$1);
|
|
437
|
+
this.state = {};
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Update state so the next render shows the fallback UI.
|
|
441
|
+
*/
|
|
442
|
+
static getDerivedStateFromError(error) {
|
|
443
|
+
return { error };
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Lifecycle method called when an error is caught.
|
|
447
|
+
* You can log the error or perform side effects here.
|
|
448
|
+
*/
|
|
449
|
+
componentDidCatch(error, info) {
|
|
450
|
+
if (this.props.onError) this.props.onError(error, info);
|
|
451
|
+
}
|
|
452
|
+
render() {
|
|
453
|
+
if (this.state.error) return this.props.fallback(this.state.error);
|
|
454
|
+
return this.props.children;
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
var ErrorBoundary_default = ErrorBoundary;
|
|
458
|
+
|
|
459
|
+
//#endregion
|
|
460
|
+
//#region src/core/components/NestedView.tsx
|
|
461
|
+
/**
|
|
462
|
+
* A component that renders the current view of the nested router layer.
|
|
463
|
+
*
|
|
464
|
+
* To be simple, it renders the `element` of the current child page of a parent page.
|
|
465
|
+
*
|
|
466
|
+
* @example
|
|
467
|
+
* ```tsx
|
|
468
|
+
* import { NestedView } from "@alepha/react";
|
|
469
|
+
*
|
|
470
|
+
* class App {
|
|
471
|
+
* parent = $page({
|
|
472
|
+
* component: () => <NestedView />,
|
|
473
|
+
* });
|
|
474
|
+
*
|
|
475
|
+
* child = $page({
|
|
476
|
+
* parent: this.root,
|
|
477
|
+
* component: () => <div>Child Page</div>,
|
|
478
|
+
* });
|
|
479
|
+
* }
|
|
480
|
+
* ```
|
|
481
|
+
*/
|
|
482
|
+
const NestedView = (props$1) => {
|
|
483
|
+
const index = use(RouterLayerContext)?.index ?? 0;
|
|
484
|
+
const state = useRouterState();
|
|
485
|
+
const [view, setView] = useState(state.layers[index]?.element);
|
|
486
|
+
const [animation, setAnimation] = useState("");
|
|
487
|
+
const animationExitDuration = useRef(0);
|
|
488
|
+
const animationExitNow = useRef(0);
|
|
489
|
+
useEvents({
|
|
490
|
+
"react:transition:begin": async ({ previous, state: state$1 }) => {
|
|
491
|
+
const layer = previous.layers[index];
|
|
492
|
+
if (`${state$1.url.pathname}/`.startsWith(`${layer?.path}/`)) return;
|
|
493
|
+
const animationExit = parseAnimation(layer.route?.animation, state$1, "exit");
|
|
494
|
+
if (animationExit) {
|
|
495
|
+
const duration = animationExit.duration || 200;
|
|
496
|
+
animationExitNow.current = Date.now();
|
|
497
|
+
animationExitDuration.current = duration;
|
|
498
|
+
setAnimation(animationExit.animation);
|
|
499
|
+
} else {
|
|
500
|
+
animationExitNow.current = 0;
|
|
501
|
+
animationExitDuration.current = 0;
|
|
502
|
+
setAnimation("");
|
|
503
|
+
}
|
|
504
|
+
},
|
|
505
|
+
"react:transition:end": async ({ state: state$1 }) => {
|
|
506
|
+
const layer = state$1.layers[index];
|
|
507
|
+
if (animationExitNow.current) {
|
|
508
|
+
const duration = animationExitDuration.current;
|
|
509
|
+
const diff = Date.now() - animationExitNow.current;
|
|
510
|
+
if (diff < duration) await new Promise((resolve) => setTimeout(resolve, duration - diff));
|
|
511
|
+
}
|
|
512
|
+
if (!layer?.cache) {
|
|
513
|
+
setView(layer?.element);
|
|
514
|
+
const animationEnter = parseAnimation(layer?.route?.animation, state$1, "enter");
|
|
515
|
+
if (animationEnter) setAnimation(animationEnter.animation);
|
|
516
|
+
else setAnimation("");
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}, []);
|
|
520
|
+
let element = view ?? props$1.children ?? null;
|
|
521
|
+
if (animation) element = /* @__PURE__ */ jsx("div", {
|
|
522
|
+
style: {
|
|
523
|
+
display: "flex",
|
|
524
|
+
flex: 1,
|
|
525
|
+
height: "100%",
|
|
526
|
+
width: "100%",
|
|
527
|
+
position: "relative",
|
|
528
|
+
overflow: "hidden"
|
|
529
|
+
},
|
|
530
|
+
children: /* @__PURE__ */ jsx("div", {
|
|
531
|
+
style: {
|
|
532
|
+
height: "100%",
|
|
533
|
+
width: "100%",
|
|
534
|
+
display: "flex",
|
|
535
|
+
animation
|
|
536
|
+
},
|
|
537
|
+
children: element
|
|
538
|
+
})
|
|
539
|
+
});
|
|
540
|
+
if (props$1.errorBoundary === false) return /* @__PURE__ */ jsx(Fragment, { children: element });
|
|
541
|
+
if (props$1.errorBoundary) return /* @__PURE__ */ jsx(ErrorBoundary_default, {
|
|
542
|
+
fallback: props$1.errorBoundary,
|
|
543
|
+
children: element
|
|
544
|
+
});
|
|
545
|
+
return /* @__PURE__ */ jsx(ErrorBoundary_default, {
|
|
546
|
+
fallback: (error) => {
|
|
547
|
+
const result = state.onError(error, state);
|
|
548
|
+
if (result instanceof Redirection) return "Redirection inside ErrorBoundary is not allowed.";
|
|
549
|
+
return result;
|
|
550
|
+
},
|
|
551
|
+
children: element
|
|
552
|
+
});
|
|
553
|
+
};
|
|
554
|
+
var NestedView_default = memo(NestedView);
|
|
555
|
+
function parseAnimation(animationLike, state, type = "enter") {
|
|
556
|
+
if (!animationLike) return;
|
|
557
|
+
const DEFAULT_DURATION = 300;
|
|
558
|
+
const animation = typeof animationLike === "function" ? animationLike(state) : animationLike;
|
|
559
|
+
if (typeof animation === "string") {
|
|
560
|
+
if (type === "exit") return;
|
|
561
|
+
return {
|
|
562
|
+
duration: DEFAULT_DURATION,
|
|
563
|
+
animation: `${DEFAULT_DURATION}ms ${animation}`
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
if (typeof animation === "object") {
|
|
567
|
+
const anim = animation[type];
|
|
568
|
+
const duration = typeof anim === "object" ? anim.duration ?? DEFAULT_DURATION : DEFAULT_DURATION;
|
|
569
|
+
const name = typeof anim === "object" ? anim.name : anim;
|
|
570
|
+
if (type === "exit") return {
|
|
571
|
+
duration,
|
|
572
|
+
animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
|
|
573
|
+
};
|
|
574
|
+
return {
|
|
575
|
+
duration,
|
|
576
|
+
animation: `${duration}ms ${typeof anim === "object" ? anim.timing ?? "" : ""} ${name}`
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
//#endregion
|
|
582
|
+
//#region src/core/components/NotFound.tsx
|
|
583
|
+
function NotFoundPage(props$1) {
|
|
584
|
+
return /* @__PURE__ */ jsx("div", {
|
|
585
|
+
style: {
|
|
586
|
+
height: "100vh",
|
|
587
|
+
display: "flex",
|
|
588
|
+
flexDirection: "column",
|
|
589
|
+
justifyContent: "center",
|
|
590
|
+
alignItems: "center",
|
|
591
|
+
textAlign: "center",
|
|
592
|
+
fontFamily: "sans-serif",
|
|
593
|
+
padding: "1rem",
|
|
594
|
+
...props$1.style
|
|
595
|
+
},
|
|
596
|
+
children: /* @__PURE__ */ jsx("h1", {
|
|
597
|
+
style: {
|
|
598
|
+
fontSize: "1rem",
|
|
599
|
+
marginBottom: "0.5rem"
|
|
600
|
+
},
|
|
601
|
+
children: "404 - This page does not exist"
|
|
602
|
+
})
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
//#endregion
|
|
607
|
+
//#region src/core/providers/ReactPageProvider.ts
|
|
608
|
+
const envSchema$2 = t.object({ REACT_STRICT_MODE: t.boolean({ default: true }) });
|
|
609
|
+
var ReactPageProvider = class {
|
|
610
|
+
log = $logger();
|
|
611
|
+
env = $env(envSchema$2);
|
|
612
|
+
alepha = $inject(Alepha);
|
|
613
|
+
pages = [];
|
|
614
|
+
getPages() {
|
|
615
|
+
return this.pages;
|
|
616
|
+
}
|
|
617
|
+
getConcretePages() {
|
|
618
|
+
const pages = [];
|
|
619
|
+
for (const page of this.pages) {
|
|
620
|
+
if (page.children && page.children.length > 0) continue;
|
|
621
|
+
const fullPath = this.pathname(page.name);
|
|
622
|
+
if (fullPath.includes(":") || fullPath.includes("*")) {
|
|
623
|
+
if (typeof page.static === "object") {
|
|
624
|
+
const entries = page.static.entries;
|
|
625
|
+
if (entries && entries.length > 0) for (const entry of entries) {
|
|
626
|
+
const params = entry.params;
|
|
627
|
+
const path = this.compile(page.path ?? "", params);
|
|
628
|
+
if (!path.includes(":") && !path.includes("*")) pages.push({
|
|
629
|
+
...page,
|
|
630
|
+
name: params[Object.keys(params)[0]],
|
|
631
|
+
path,
|
|
632
|
+
...entry
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
continue;
|
|
637
|
+
}
|
|
638
|
+
pages.push(page);
|
|
639
|
+
}
|
|
640
|
+
return pages;
|
|
641
|
+
}
|
|
642
|
+
page(name) {
|
|
643
|
+
for (const page of this.pages) if (page.name === name) return page;
|
|
644
|
+
throw new AlephaError(`Page '${name}' not found`);
|
|
645
|
+
}
|
|
646
|
+
pathname(name, options = {}) {
|
|
647
|
+
const page = this.page(name);
|
|
648
|
+
if (!page) throw new Error(`Page ${name} not found`);
|
|
649
|
+
let url = page.path ?? "";
|
|
650
|
+
let parent = page.parent;
|
|
651
|
+
while (parent) {
|
|
652
|
+
url = `${parent.path ?? ""}/${url}`;
|
|
653
|
+
parent = parent.parent;
|
|
654
|
+
}
|
|
655
|
+
url = this.compile(url, options.params ?? {});
|
|
656
|
+
if (options.query) {
|
|
657
|
+
const query = new URLSearchParams(options.query);
|
|
658
|
+
if (query.toString()) url += `?${query.toString()}`;
|
|
659
|
+
}
|
|
660
|
+
return url.replace(/\/\/+/g, "/") || "/";
|
|
661
|
+
}
|
|
662
|
+
url(name, options = {}) {
|
|
663
|
+
return new URL(this.pathname(name, options), options.host ?? `http://localhost`);
|
|
664
|
+
}
|
|
665
|
+
root(state) {
|
|
666
|
+
const root = createElement(AlephaContext.Provider, { value: this.alepha }, createElement(NestedView_default, {}, state.layers[0]?.element));
|
|
667
|
+
if (this.env.REACT_STRICT_MODE) return createElement(StrictMode, {}, root);
|
|
668
|
+
return root;
|
|
669
|
+
}
|
|
670
|
+
convertStringObjectToObject = (schema, value) => {
|
|
671
|
+
if (t.schema.isObject(schema) && typeof value === "object") {
|
|
672
|
+
for (const key in schema.properties) if (t.schema.isObject(schema.properties[key]) && typeof value[key] === "string") try {
|
|
673
|
+
value[key] = this.alepha.codec.decode(schema.properties[key], decodeURIComponent(value[key]));
|
|
674
|
+
} catch (e$1) {}
|
|
675
|
+
}
|
|
676
|
+
return value;
|
|
677
|
+
};
|
|
678
|
+
/**
|
|
679
|
+
* Create a new RouterState based on a given route and request.
|
|
680
|
+
* This method resolves the layers for the route, applying any query and params schemas defined in the route.
|
|
681
|
+
* It also handles errors and redirects.
|
|
682
|
+
*/
|
|
683
|
+
async createLayers(route, state, previous = []) {
|
|
684
|
+
let context = {};
|
|
685
|
+
const stack = [{ route }];
|
|
686
|
+
let parent = route.parent;
|
|
687
|
+
while (parent) {
|
|
688
|
+
stack.unshift({ route: parent });
|
|
689
|
+
parent = parent.parent;
|
|
690
|
+
}
|
|
691
|
+
let forceRefresh = false;
|
|
692
|
+
for (let i = 0; i < stack.length; i++) {
|
|
693
|
+
const it = stack[i];
|
|
694
|
+
const route$1 = it.route;
|
|
695
|
+
const config = {};
|
|
696
|
+
try {
|
|
697
|
+
this.convertStringObjectToObject(route$1.schema?.query, state.query);
|
|
698
|
+
config.query = route$1.schema?.query ? this.alepha.codec.decode(route$1.schema.query, state.query) : {};
|
|
699
|
+
} catch (e$1) {
|
|
700
|
+
it.error = e$1;
|
|
701
|
+
break;
|
|
702
|
+
}
|
|
703
|
+
try {
|
|
704
|
+
config.params = route$1.schema?.params ? this.alepha.codec.decode(route$1.schema.params, state.params) : {};
|
|
705
|
+
} catch (e$1) {
|
|
706
|
+
it.error = e$1;
|
|
707
|
+
break;
|
|
708
|
+
}
|
|
709
|
+
it.config = { ...config };
|
|
710
|
+
if (previous?.[i] && !forceRefresh && previous[i].name === route$1.name) {
|
|
711
|
+
const url = (str) => str ? str.replace(/\/\/+/g, "/") : "/";
|
|
712
|
+
if (JSON.stringify({
|
|
713
|
+
part: url(previous[i].part),
|
|
714
|
+
params: previous[i].config?.params ?? {}
|
|
715
|
+
}) === JSON.stringify({
|
|
716
|
+
part: url(route$1.path),
|
|
717
|
+
params: config.params ?? {}
|
|
718
|
+
})) {
|
|
719
|
+
it.props = previous[i].props;
|
|
720
|
+
it.error = previous[i].error;
|
|
721
|
+
it.cache = true;
|
|
722
|
+
context = {
|
|
723
|
+
...context,
|
|
724
|
+
...it.props
|
|
725
|
+
};
|
|
726
|
+
continue;
|
|
727
|
+
}
|
|
728
|
+
forceRefresh = true;
|
|
729
|
+
}
|
|
730
|
+
if (!route$1.resolve) continue;
|
|
731
|
+
try {
|
|
732
|
+
const args = Object.create(state);
|
|
733
|
+
Object.assign(args, config, context);
|
|
734
|
+
const props$1 = await route$1.resolve?.(args) ?? {};
|
|
735
|
+
it.props = { ...props$1 };
|
|
736
|
+
context = {
|
|
737
|
+
...context,
|
|
738
|
+
...props$1
|
|
739
|
+
};
|
|
740
|
+
} catch (e$1) {
|
|
741
|
+
if (e$1 instanceof Redirection) return { redirect: e$1.redirect };
|
|
742
|
+
this.log.error("Page resolver has failed", e$1);
|
|
743
|
+
it.error = e$1;
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
let acc = "";
|
|
748
|
+
for (let i = 0; i < stack.length; i++) {
|
|
749
|
+
const it = stack[i];
|
|
750
|
+
const props$1 = it.props ?? {};
|
|
751
|
+
const params = { ...it.config?.params };
|
|
752
|
+
for (const key of Object.keys(params)) params[key] = String(params[key]);
|
|
753
|
+
acc += "/";
|
|
754
|
+
acc += it.route.path ? this.compile(it.route.path, params) : "";
|
|
755
|
+
const path = acc.replace(/\/+/, "/");
|
|
756
|
+
const localErrorHandler = this.getErrorHandler(it.route);
|
|
757
|
+
if (localErrorHandler) {
|
|
758
|
+
const onErrorParent = state.onError;
|
|
759
|
+
state.onError = (error, context$1) => {
|
|
760
|
+
const result = localErrorHandler(error, context$1);
|
|
761
|
+
if (result === void 0) return onErrorParent(error, context$1);
|
|
762
|
+
return result;
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
if (!it.error) try {
|
|
766
|
+
const element = await this.createElement(it.route, {
|
|
767
|
+
...props$1,
|
|
768
|
+
...context
|
|
769
|
+
});
|
|
770
|
+
state.layers.push({
|
|
771
|
+
name: it.route.name,
|
|
772
|
+
props: props$1,
|
|
773
|
+
part: it.route.path,
|
|
774
|
+
config: it.config,
|
|
775
|
+
element: this.renderView(i + 1, path, element, it.route),
|
|
776
|
+
index: i + 1,
|
|
777
|
+
path,
|
|
778
|
+
route: it.route,
|
|
779
|
+
cache: it.cache
|
|
780
|
+
});
|
|
781
|
+
} catch (e$1) {
|
|
782
|
+
it.error = e$1;
|
|
783
|
+
}
|
|
784
|
+
if (it.error) try {
|
|
785
|
+
let element = await state.onError(it.error, state);
|
|
786
|
+
if (element === void 0) throw it.error;
|
|
787
|
+
if (element instanceof Redirection) return { redirect: element.redirect };
|
|
788
|
+
if (element === null) element = this.renderError(it.error);
|
|
789
|
+
state.layers.push({
|
|
790
|
+
props: props$1,
|
|
791
|
+
error: it.error,
|
|
792
|
+
name: it.route.name,
|
|
793
|
+
part: it.route.path,
|
|
794
|
+
config: it.config,
|
|
795
|
+
element: this.renderView(i + 1, path, element, it.route),
|
|
796
|
+
index: i + 1,
|
|
797
|
+
path,
|
|
798
|
+
route: it.route
|
|
799
|
+
});
|
|
800
|
+
break;
|
|
801
|
+
} catch (e$1) {
|
|
802
|
+
if (e$1 instanceof Redirection) return { redirect: e$1.redirect };
|
|
803
|
+
throw e$1;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
return { state };
|
|
807
|
+
}
|
|
808
|
+
createRedirectionLayer(redirect) {
|
|
809
|
+
return { redirect };
|
|
810
|
+
}
|
|
811
|
+
getErrorHandler(route) {
|
|
812
|
+
if (route.errorHandler) return route.errorHandler;
|
|
813
|
+
let parent = route.parent;
|
|
814
|
+
while (parent) {
|
|
815
|
+
if (parent.errorHandler) return parent.errorHandler;
|
|
816
|
+
parent = parent.parent;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
async createElement(page, props$1) {
|
|
820
|
+
if (page.lazy && page.component) this.log.warn(`Page ${page.name} has both lazy and component options, lazy will be used`);
|
|
821
|
+
if (page.lazy) return createElement((await page.lazy()).default, props$1);
|
|
822
|
+
if (page.component) return createElement(page.component, props$1);
|
|
823
|
+
}
|
|
824
|
+
renderError(error) {
|
|
825
|
+
return createElement(ErrorViewer_default, {
|
|
826
|
+
error,
|
|
827
|
+
alepha: this.alepha
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
renderEmptyView() {
|
|
831
|
+
return createElement(NestedView_default, {});
|
|
832
|
+
}
|
|
833
|
+
href(page, params = {}) {
|
|
834
|
+
const found = this.pages.find((it) => it.name === page.options.name);
|
|
835
|
+
if (!found) throw new Error(`Page ${page.options.name} not found`);
|
|
836
|
+
let url = found.path ?? "";
|
|
837
|
+
let parent = found.parent;
|
|
838
|
+
while (parent) {
|
|
839
|
+
url = `${parent.path ?? ""}/${url}`;
|
|
840
|
+
parent = parent.parent;
|
|
841
|
+
}
|
|
842
|
+
url = this.compile(url, params);
|
|
843
|
+
return url.replace(/\/\/+/g, "/") || "/";
|
|
844
|
+
}
|
|
845
|
+
compile(path, params = {}) {
|
|
846
|
+
for (const [key, value] of Object.entries(params)) path = path.replace(`:${key}`, value);
|
|
847
|
+
return path;
|
|
848
|
+
}
|
|
849
|
+
renderView(index, path, view, page) {
|
|
850
|
+
view ??= this.renderEmptyView();
|
|
851
|
+
const element = page.client ? createElement(ClientOnly_default, typeof page.client === "object" ? page.client : {}, view) : view;
|
|
852
|
+
return createElement(RouterLayerContext.Provider, { value: {
|
|
853
|
+
index,
|
|
854
|
+
path
|
|
855
|
+
} }, element);
|
|
856
|
+
}
|
|
857
|
+
configure = $hook({
|
|
858
|
+
on: "configure",
|
|
859
|
+
handler: () => {
|
|
860
|
+
let hasNotFoundHandler = false;
|
|
861
|
+
const pages = this.alepha.descriptors($page);
|
|
862
|
+
const hasParent = (it) => {
|
|
863
|
+
if (it.options.parent) return true;
|
|
864
|
+
for (const page of pages) if ((page.options.children ? Array.isArray(page.options.children) ? page.options.children : page.options.children() : []).includes(it)) return true;
|
|
865
|
+
};
|
|
866
|
+
for (const page of pages) {
|
|
867
|
+
if (page.options.path === "/*") hasNotFoundHandler = true;
|
|
868
|
+
if (hasParent(page)) continue;
|
|
869
|
+
this.add(this.map(pages, page));
|
|
870
|
+
}
|
|
871
|
+
if (!hasNotFoundHandler && pages.length > 0) this.add({
|
|
872
|
+
path: "/*",
|
|
873
|
+
name: "notFound",
|
|
874
|
+
cache: true,
|
|
875
|
+
component: NotFoundPage,
|
|
876
|
+
onServerResponse: ({ reply }) => {
|
|
877
|
+
reply.status = 404;
|
|
878
|
+
}
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
});
|
|
882
|
+
map(pages, target) {
|
|
883
|
+
const children = target.options.children ? Array.isArray(target.options.children) ? target.options.children : target.options.children() : [];
|
|
884
|
+
const getChildrenFromParent = (it) => {
|
|
885
|
+
const children$1 = [];
|
|
886
|
+
for (const page of pages) if (page.options.parent === it) children$1.push(page);
|
|
887
|
+
return children$1;
|
|
888
|
+
};
|
|
889
|
+
children.push(...getChildrenFromParent(target));
|
|
890
|
+
return {
|
|
891
|
+
...target.options,
|
|
892
|
+
name: target.name,
|
|
893
|
+
parent: void 0,
|
|
894
|
+
children: children.map((it) => this.map(pages, it))
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
add(entry) {
|
|
898
|
+
if (this.alepha.isReady()) throw new AlephaError("Router is already initialized");
|
|
899
|
+
entry.name ??= this.nextId();
|
|
900
|
+
const page = entry;
|
|
901
|
+
page.match = this.createMatch(page);
|
|
902
|
+
this.pages.push(page);
|
|
903
|
+
if (page.children) for (const child of page.children) {
|
|
904
|
+
child.parent = page;
|
|
905
|
+
this.add(child);
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
createMatch(page) {
|
|
909
|
+
let url = page.path ?? "/";
|
|
910
|
+
let target = page.parent;
|
|
911
|
+
while (target) {
|
|
912
|
+
url = `${target.path ?? ""}/${url}`;
|
|
913
|
+
target = target.parent;
|
|
914
|
+
}
|
|
915
|
+
let path = url.replace(/\/\/+/g, "/");
|
|
916
|
+
if (path.endsWith("/") && path !== "/") path = path.slice(0, -1);
|
|
917
|
+
return path;
|
|
918
|
+
}
|
|
919
|
+
_next = 0;
|
|
920
|
+
nextId() {
|
|
921
|
+
this._next += 1;
|
|
922
|
+
return `P${this._next}`;
|
|
923
|
+
}
|
|
924
|
+
};
|
|
925
|
+
const isPageRoute = (it) => {
|
|
926
|
+
return it && typeof it === "object" && typeof it.path === "string" && typeof it.page === "object";
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/core/providers/ReactServerProvider.ts
|
|
931
|
+
const envSchema$1 = t.object({
|
|
932
|
+
REACT_SSR_ENABLED: t.optional(t.boolean()),
|
|
933
|
+
REACT_ROOT_ID: t.text({ default: "root" }),
|
|
934
|
+
REACT_SERVER_TEMPLATE: t.optional(t.text({ size: "rich" }))
|
|
935
|
+
});
|
|
936
|
+
/**
|
|
937
|
+
* React server provider configuration atom
|
|
938
|
+
*/
|
|
939
|
+
const reactServerOptions = $atom({
|
|
940
|
+
name: "alepha.react.server.options",
|
|
941
|
+
schema: t.object({
|
|
942
|
+
publicDir: t.string(),
|
|
943
|
+
staticServer: t.object({
|
|
944
|
+
disabled: t.boolean(),
|
|
945
|
+
path: t.string({ description: "URL path where static files will be served." })
|
|
946
|
+
})
|
|
947
|
+
}),
|
|
948
|
+
default: {
|
|
949
|
+
publicDir: "public",
|
|
950
|
+
staticServer: {
|
|
951
|
+
disabled: false,
|
|
952
|
+
path: "/"
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
});
|
|
956
|
+
var ReactServerProvider = class {
|
|
957
|
+
log = $logger();
|
|
958
|
+
alepha = $inject(Alepha);
|
|
959
|
+
env = $env(envSchema$1);
|
|
960
|
+
pageApi = $inject(ReactPageProvider);
|
|
961
|
+
serverProvider = $inject(ServerProvider);
|
|
962
|
+
serverStaticProvider = $inject(ServerStaticProvider);
|
|
963
|
+
serverRouterProvider = $inject(ServerRouterProvider);
|
|
964
|
+
serverTimingProvider = $inject(ServerTimingProvider);
|
|
965
|
+
ROOT_DIV_REGEX = new RegExp(`<div([^>]*)\\s+id=["']${this.env.REACT_ROOT_ID}["']([^>]*)>(.*?)<\\/div>`, "is");
|
|
966
|
+
preprocessedTemplate = null;
|
|
967
|
+
options = $use(reactServerOptions);
|
|
968
|
+
/**
|
|
969
|
+
* Configure the React server provider.
|
|
970
|
+
*/
|
|
971
|
+
onConfigure = $hook({
|
|
972
|
+
on: "configure",
|
|
973
|
+
handler: async () => {
|
|
974
|
+
const ssrEnabled = this.alepha.descriptors($page).length > 0 && this.env.REACT_SSR_ENABLED !== false;
|
|
975
|
+
this.alepha.state.set("alepha.react.server.ssr", ssrEnabled);
|
|
976
|
+
if (this.alepha.isViteDev()) {
|
|
977
|
+
await this.configureVite(ssrEnabled);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
let root = "";
|
|
981
|
+
if (!this.alepha.isServerless()) {
|
|
982
|
+
root = this.getPublicDirectory();
|
|
983
|
+
if (!root) this.log.warn("Missing static files, static file server will be disabled");
|
|
984
|
+
else {
|
|
985
|
+
this.log.debug(`Using static files from: ${root}`);
|
|
986
|
+
await this.configureStaticServer(root);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
if (ssrEnabled) {
|
|
990
|
+
await this.registerPages(async () => this.template);
|
|
991
|
+
this.log.info("SSR OK");
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
this.log.info("SSR is disabled, use History API fallback");
|
|
995
|
+
this.serverRouterProvider.createRoute({
|
|
996
|
+
path: "*",
|
|
997
|
+
handler: async ({ url, reply }) => {
|
|
998
|
+
if (url.pathname.includes(".")) {
|
|
999
|
+
reply.headers["content-type"] = "text/plain";
|
|
1000
|
+
reply.body = "Not Found";
|
|
1001
|
+
reply.status = 404;
|
|
1002
|
+
return;
|
|
1003
|
+
}
|
|
1004
|
+
reply.headers["content-type"] = "text/html";
|
|
1005
|
+
return this.template;
|
|
1006
|
+
}
|
|
1007
|
+
});
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
get template() {
|
|
1011
|
+
return this.alepha.env.REACT_SERVER_TEMPLATE ?? "<!DOCTYPE html><html lang='en'><head></head><body></body></html>";
|
|
1012
|
+
}
|
|
1013
|
+
async registerPages(templateLoader) {
|
|
1014
|
+
const template = await templateLoader();
|
|
1015
|
+
if (template) this.preprocessedTemplate = this.preprocessTemplate(template);
|
|
1016
|
+
for (const page of this.pageApi.getPages()) {
|
|
1017
|
+
if (page.children?.length) continue;
|
|
1018
|
+
this.log.debug(`+ ${page.match} -> ${page.name}`);
|
|
1019
|
+
this.serverRouterProvider.createRoute({
|
|
1020
|
+
...page,
|
|
1021
|
+
schema: void 0,
|
|
1022
|
+
method: "GET",
|
|
1023
|
+
path: page.match,
|
|
1024
|
+
handler: this.createHandler(page, templateLoader)
|
|
1025
|
+
});
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
/**
|
|
1029
|
+
* Get the public directory path where static files are located.
|
|
1030
|
+
*/
|
|
1031
|
+
getPublicDirectory() {
|
|
1032
|
+
const maybe = [join(process.cwd(), `dist/${this.options.publicDir}`), join(process.cwd(), this.options.publicDir)];
|
|
1033
|
+
for (const it of maybe) if (existsSync(it)) return it;
|
|
1034
|
+
return "";
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Configure the static file server to serve files from the given root directory.
|
|
1038
|
+
*/
|
|
1039
|
+
async configureStaticServer(root) {
|
|
1040
|
+
await this.serverStaticProvider.createStaticServer({
|
|
1041
|
+
root,
|
|
1042
|
+
cacheControl: {
|
|
1043
|
+
maxAge: 3600,
|
|
1044
|
+
immutable: true
|
|
1045
|
+
},
|
|
1046
|
+
...this.options.staticServer
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Configure Vite for SSR.
|
|
1051
|
+
*/
|
|
1052
|
+
async configureVite(ssrEnabled) {
|
|
1053
|
+
if (!ssrEnabled) return;
|
|
1054
|
+
this.log.info("SSR (dev) OK");
|
|
1055
|
+
const url = `http://${process.env.SERVER_HOST}:${process.env.SERVER_PORT}`;
|
|
1056
|
+
await this.registerPages(() => fetch(`${url}/index.html`).then((it) => it.text()).catch(() => void 0));
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* For testing purposes, creates a render function that can be used.
|
|
1060
|
+
*/
|
|
1061
|
+
async render(name, options = {}) {
|
|
1062
|
+
const page = this.pageApi.page(name);
|
|
1063
|
+
const url = new URL(this.pageApi.url(name, options));
|
|
1064
|
+
const state = {
|
|
1065
|
+
url,
|
|
1066
|
+
params: options.params ?? {},
|
|
1067
|
+
query: options.query ?? {},
|
|
1068
|
+
onError: () => null,
|
|
1069
|
+
layers: [],
|
|
1070
|
+
meta: {}
|
|
1071
|
+
};
|
|
1072
|
+
this.log.trace("Rendering", { url });
|
|
1073
|
+
await this.alepha.events.emit("react:server:render:begin", { state });
|
|
1074
|
+
const { redirect } = await this.pageApi.createLayers(page, state);
|
|
1075
|
+
if (redirect) return {
|
|
1076
|
+
state,
|
|
1077
|
+
html: "",
|
|
1078
|
+
redirect
|
|
1079
|
+
};
|
|
1080
|
+
if (!options.html) {
|
|
1081
|
+
this.alepha.state.set("alepha.react.router.state", state);
|
|
1082
|
+
return {
|
|
1083
|
+
state,
|
|
1084
|
+
html: renderToString(this.pageApi.root(state))
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
const template = this.template ?? "";
|
|
1088
|
+
const html = this.renderToHtml(template, state, options.hydration);
|
|
1089
|
+
if (html instanceof Redirection) return {
|
|
1090
|
+
state,
|
|
1091
|
+
html: "",
|
|
1092
|
+
redirect
|
|
1093
|
+
};
|
|
1094
|
+
const result = {
|
|
1095
|
+
state,
|
|
1096
|
+
html
|
|
1097
|
+
};
|
|
1098
|
+
await this.alepha.events.emit("react:server:render:end", result);
|
|
1099
|
+
return result;
|
|
1100
|
+
}
|
|
1101
|
+
createHandler(route, templateLoader) {
|
|
1102
|
+
return async (serverRequest) => {
|
|
1103
|
+
const { url, reply, query, params } = serverRequest;
|
|
1104
|
+
const template = await templateLoader();
|
|
1105
|
+
if (!template) throw new AlephaError("Missing template for SSR rendering");
|
|
1106
|
+
this.log.trace("Rendering page", { name: route.name });
|
|
1107
|
+
const state = {
|
|
1108
|
+
url,
|
|
1109
|
+
params,
|
|
1110
|
+
query,
|
|
1111
|
+
onError: () => null,
|
|
1112
|
+
layers: []
|
|
1113
|
+
};
|
|
1114
|
+
if (this.alepha.has(ServerLinksProvider)) this.alepha.state.set("alepha.server.request.apiLinks", await this.alepha.inject(ServerLinksProvider).getUserApiLinks({
|
|
1115
|
+
user: serverRequest.user,
|
|
1116
|
+
authorization: serverRequest.headers.authorization
|
|
1117
|
+
}));
|
|
1118
|
+
let target = route;
|
|
1119
|
+
while (target) {
|
|
1120
|
+
if (route.can && !route.can()) {
|
|
1121
|
+
reply.status = 403;
|
|
1122
|
+
reply.headers["content-type"] = "text/plain";
|
|
1123
|
+
return "Forbidden";
|
|
1124
|
+
}
|
|
1125
|
+
target = target.parent;
|
|
1126
|
+
}
|
|
1127
|
+
await this.alepha.events.emit("react:server:render:begin", {
|
|
1128
|
+
request: serverRequest,
|
|
1129
|
+
state
|
|
1130
|
+
});
|
|
1131
|
+
this.serverTimingProvider.beginTiming("createLayers");
|
|
1132
|
+
const { redirect } = await this.pageApi.createLayers(route, state);
|
|
1133
|
+
this.serverTimingProvider.endTiming("createLayers");
|
|
1134
|
+
if (redirect) return reply.redirect(redirect);
|
|
1135
|
+
reply.headers["content-type"] = "text/html";
|
|
1136
|
+
reply.headers["cache-control"] = "no-store, no-cache, must-revalidate, proxy-revalidate";
|
|
1137
|
+
reply.headers.pragma = "no-cache";
|
|
1138
|
+
reply.headers.expires = "0";
|
|
1139
|
+
const html = this.renderToHtml(template, state);
|
|
1140
|
+
if (html instanceof Redirection) {
|
|
1141
|
+
reply.redirect(typeof html.redirect === "string" ? html.redirect : this.pageApi.href(html.redirect));
|
|
1142
|
+
return;
|
|
1143
|
+
}
|
|
1144
|
+
const event = {
|
|
1145
|
+
request: serverRequest,
|
|
1146
|
+
state,
|
|
1147
|
+
html
|
|
1148
|
+
};
|
|
1149
|
+
await this.alepha.events.emit("react:server:render:end", event);
|
|
1150
|
+
route.onServerResponse?.(serverRequest);
|
|
1151
|
+
this.log.trace("Page rendered", { name: route.name });
|
|
1152
|
+
return event.html;
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
renderToHtml(template, state, hydration = true) {
|
|
1156
|
+
const element = this.pageApi.root(state);
|
|
1157
|
+
this.alepha.state.set("alepha.react.router.state", state);
|
|
1158
|
+
this.serverTimingProvider.beginTiming("renderToString");
|
|
1159
|
+
let app = "";
|
|
1160
|
+
try {
|
|
1161
|
+
app = renderToString(element);
|
|
1162
|
+
} catch (error) {
|
|
1163
|
+
this.log.error("renderToString has failed, fallback to error handler", error);
|
|
1164
|
+
const element$1 = state.onError(error, state);
|
|
1165
|
+
if (element$1 instanceof Redirection) return element$1;
|
|
1166
|
+
app = renderToString(element$1);
|
|
1167
|
+
this.log.debug("Error handled successfully with fallback");
|
|
1168
|
+
}
|
|
1169
|
+
this.serverTimingProvider.endTiming("renderToString");
|
|
1170
|
+
const response = { html: template };
|
|
1171
|
+
if (hydration) {
|
|
1172
|
+
const { request, context, ...store } = this.alepha.context.als?.getStore() ?? {};
|
|
1173
|
+
const hydrationData = {
|
|
1174
|
+
...store,
|
|
1175
|
+
"alepha.react.router.state": void 0,
|
|
1176
|
+
layers: state.layers.map((it) => ({
|
|
1177
|
+
...it,
|
|
1178
|
+
error: it.error ? {
|
|
1179
|
+
...it.error,
|
|
1180
|
+
name: it.error.name,
|
|
1181
|
+
message: it.error.message,
|
|
1182
|
+
stack: !this.alepha.isProduction() ? it.error.stack : void 0
|
|
1183
|
+
} : void 0,
|
|
1184
|
+
index: void 0,
|
|
1185
|
+
path: void 0,
|
|
1186
|
+
element: void 0,
|
|
1187
|
+
route: void 0
|
|
1188
|
+
}))
|
|
1189
|
+
};
|
|
1190
|
+
const script = `<script>window.__ssr=${JSON.stringify(hydrationData)}<\/script>`;
|
|
1191
|
+
this.fillTemplate(response, app, script);
|
|
1192
|
+
}
|
|
1193
|
+
return response.html;
|
|
1194
|
+
}
|
|
1195
|
+
preprocessTemplate(template) {
|
|
1196
|
+
const bodyCloseIndex = template.match(/<\/body>/i)?.index ?? template.length;
|
|
1197
|
+
const beforeScript = template.substring(0, bodyCloseIndex);
|
|
1198
|
+
const afterScript = template.substring(bodyCloseIndex);
|
|
1199
|
+
const rootDivMatch = beforeScript.match(this.ROOT_DIV_REGEX);
|
|
1200
|
+
if (rootDivMatch) {
|
|
1201
|
+
const beforeDiv = beforeScript.substring(0, rootDivMatch.index);
|
|
1202
|
+
const afterDivStart = rootDivMatch.index + rootDivMatch[0].length;
|
|
1203
|
+
const afterDiv = beforeScript.substring(afterDivStart);
|
|
1204
|
+
return {
|
|
1205
|
+
beforeApp: `${beforeDiv}<div${rootDivMatch[1]} id="${this.env.REACT_ROOT_ID}"${rootDivMatch[2]}>`,
|
|
1206
|
+
afterApp: `</div>${afterDiv}`,
|
|
1207
|
+
beforeScript: "",
|
|
1208
|
+
afterScript
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
const bodyMatch = beforeScript.match(/<body([^>]*)>/i);
|
|
1212
|
+
if (bodyMatch) {
|
|
1213
|
+
const beforeBody = beforeScript.substring(0, bodyMatch.index + bodyMatch[0].length);
|
|
1214
|
+
const afterBody = beforeScript.substring(bodyMatch.index + bodyMatch[0].length);
|
|
1215
|
+
return {
|
|
1216
|
+
beforeApp: `${beforeBody}<div id="${this.env.REACT_ROOT_ID}">`,
|
|
1217
|
+
afterApp: `</div>${afterBody}`,
|
|
1218
|
+
beforeScript: "",
|
|
1219
|
+
afterScript
|
|
1220
|
+
};
|
|
1221
|
+
}
|
|
1222
|
+
return {
|
|
1223
|
+
beforeApp: `<div id="${this.env.REACT_ROOT_ID}">`,
|
|
1224
|
+
afterApp: `</div>`,
|
|
1225
|
+
beforeScript,
|
|
1226
|
+
afterScript
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
1229
|
+
fillTemplate(response, app, script) {
|
|
1230
|
+
if (!this.preprocessedTemplate) this.preprocessedTemplate = this.preprocessTemplate(response.html);
|
|
1231
|
+
response.html = this.preprocessedTemplate.beforeApp + app + this.preprocessedTemplate.afterApp + script + this.preprocessedTemplate.afterScript;
|
|
1232
|
+
}
|
|
1233
|
+
};
|
|
1234
|
+
|
|
1235
|
+
//#endregion
|
|
1236
|
+
//#region src/core/services/ReactPageServerService.ts
|
|
1237
|
+
var ReactPageServerService = class extends ReactPageService {
|
|
1238
|
+
reactServerProvider = $inject(ReactServerProvider);
|
|
1239
|
+
serverProvider = $inject(ServerProvider);
|
|
1240
|
+
async render(name, options = {}) {
|
|
1241
|
+
return this.reactServerProvider.render(name, options);
|
|
1242
|
+
}
|
|
1243
|
+
async fetch(pathname, options = {}) {
|
|
1244
|
+
const response = await fetch(`${this.serverProvider.hostname}/${pathname}`);
|
|
1245
|
+
const html = await response.text();
|
|
1246
|
+
if (options?.html) return {
|
|
1247
|
+
html,
|
|
1248
|
+
response
|
|
1249
|
+
};
|
|
1250
|
+
const match = html.match(this.reactServerProvider.ROOT_DIV_REGEX);
|
|
1251
|
+
if (match) return {
|
|
1252
|
+
html: match[3],
|
|
1253
|
+
response
|
|
1254
|
+
};
|
|
1255
|
+
throw new AlephaError("Invalid HTML response");
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
|
|
1259
|
+
//#endregion
|
|
1260
|
+
//#region src/core/providers/ReactBrowserRouterProvider.ts
|
|
1261
|
+
var ReactBrowserRouterProvider = class extends RouterProvider {
|
|
1262
|
+
log = $logger();
|
|
1263
|
+
alepha = $inject(Alepha);
|
|
1264
|
+
pageApi = $inject(ReactPageProvider);
|
|
1265
|
+
add(entry) {
|
|
1266
|
+
this.pageApi.add(entry);
|
|
1267
|
+
}
|
|
1268
|
+
configure = $hook({
|
|
1269
|
+
on: "configure",
|
|
1270
|
+
handler: async () => {
|
|
1271
|
+
for (const page of this.pageApi.getPages()) if (page.component || page.lazy) this.push({
|
|
1272
|
+
path: page.match,
|
|
1273
|
+
page
|
|
1274
|
+
});
|
|
1275
|
+
}
|
|
1276
|
+
});
|
|
1277
|
+
async transition(url, previous = [], meta = {}) {
|
|
1278
|
+
const { pathname, search } = url;
|
|
1279
|
+
const state = {
|
|
1280
|
+
url,
|
|
1281
|
+
query: {},
|
|
1282
|
+
params: {},
|
|
1283
|
+
layers: [],
|
|
1284
|
+
onError: () => null,
|
|
1285
|
+
meta
|
|
1286
|
+
};
|
|
1287
|
+
await this.alepha.events.emit("react:action:begin", { type: "transition" });
|
|
1288
|
+
await this.alepha.events.emit("react:transition:begin", {
|
|
1289
|
+
previous: this.alepha.state.get("alepha.react.router.state"),
|
|
1290
|
+
state
|
|
1291
|
+
});
|
|
1292
|
+
try {
|
|
1293
|
+
const { route, params } = this.match(pathname);
|
|
1294
|
+
const query = {};
|
|
1295
|
+
if (search) for (const [key, value] of new URLSearchParams(search).entries()) query[key] = String(value);
|
|
1296
|
+
state.query = query;
|
|
1297
|
+
state.params = params ?? {};
|
|
1298
|
+
if (isPageRoute(route)) {
|
|
1299
|
+
const { redirect } = await this.pageApi.createLayers(route.page, state, previous);
|
|
1300
|
+
if (redirect) return redirect;
|
|
1301
|
+
}
|
|
1302
|
+
if (state.layers.length === 0) state.layers.push({
|
|
1303
|
+
name: "not-found",
|
|
1304
|
+
element: createElement(NotFoundPage),
|
|
1305
|
+
index: 0,
|
|
1306
|
+
path: "/"
|
|
1307
|
+
});
|
|
1308
|
+
await this.alepha.events.emit("react:action:success", { type: "transition" });
|
|
1309
|
+
await this.alepha.events.emit("react:transition:success", { state });
|
|
1310
|
+
} catch (e$1) {
|
|
1311
|
+
this.log.error("Transition has failed", e$1);
|
|
1312
|
+
state.layers = [{
|
|
1313
|
+
name: "error",
|
|
1314
|
+
element: this.pageApi.renderError(e$1),
|
|
1315
|
+
index: 0,
|
|
1316
|
+
path: "/"
|
|
1317
|
+
}];
|
|
1318
|
+
await this.alepha.events.emit("react:action:error", {
|
|
1319
|
+
type: "transition",
|
|
1320
|
+
error: e$1
|
|
1321
|
+
});
|
|
1322
|
+
await this.alepha.events.emit("react:transition:error", {
|
|
1323
|
+
error: e$1,
|
|
1324
|
+
state
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
if (previous) for (let i = 0; i < previous.length; i++) {
|
|
1328
|
+
const layer = previous[i];
|
|
1329
|
+
if (state.layers[i]?.name !== layer.name) this.pageApi.page(layer.name)?.onLeave?.();
|
|
1330
|
+
}
|
|
1331
|
+
this.alepha.state.set("alepha.react.router.state", state);
|
|
1332
|
+
await this.alepha.events.emit("react:action:end", { type: "transition" });
|
|
1333
|
+
await this.alepha.events.emit("react:transition:end", { state });
|
|
1334
|
+
}
|
|
1335
|
+
root(state) {
|
|
1336
|
+
return this.pageApi.root(state);
|
|
1337
|
+
}
|
|
1338
|
+
};
|
|
1339
|
+
|
|
1340
|
+
//#endregion
|
|
1341
|
+
//#region src/core/providers/ReactBrowserProvider.ts
|
|
1342
|
+
const envSchema = t.object({ REACT_ROOT_ID: t.text({ default: "root" }) });
|
|
1343
|
+
/**
|
|
1344
|
+
* React browser renderer configuration atom
|
|
1345
|
+
*/
|
|
1346
|
+
const reactBrowserOptions = $atom({
|
|
1347
|
+
name: "alepha.react.browser.options",
|
|
1348
|
+
schema: t.object({ scrollRestoration: t.enum(["top", "manual"]) }),
|
|
1349
|
+
default: { scrollRestoration: "top" }
|
|
1350
|
+
});
|
|
1351
|
+
var ReactBrowserProvider = class {
|
|
1352
|
+
env = $env(envSchema);
|
|
1353
|
+
log = $logger();
|
|
1354
|
+
client = $inject(LinkProvider);
|
|
1355
|
+
alepha = $inject(Alepha);
|
|
1356
|
+
router = $inject(ReactBrowserRouterProvider);
|
|
1357
|
+
dateTimeProvider = $inject(DateTimeProvider);
|
|
1358
|
+
options = $use(reactBrowserOptions);
|
|
1359
|
+
getRootElement() {
|
|
1360
|
+
const root = this.document.getElementById(this.env.REACT_ROOT_ID);
|
|
1361
|
+
if (root) return root;
|
|
1362
|
+
const div = this.document.createElement("div");
|
|
1363
|
+
div.id = this.env.REACT_ROOT_ID;
|
|
1364
|
+
this.document.body.prepend(div);
|
|
1365
|
+
return div;
|
|
1366
|
+
}
|
|
1367
|
+
transitioning;
|
|
1368
|
+
get state() {
|
|
1369
|
+
return this.alepha.state.get("alepha.react.router.state");
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Accessor for Document DOM API.
|
|
1373
|
+
*/
|
|
1374
|
+
get document() {
|
|
1375
|
+
return window.document;
|
|
1376
|
+
}
|
|
1377
|
+
/**
|
|
1378
|
+
* Accessor for History DOM API.
|
|
1379
|
+
*/
|
|
1380
|
+
get history() {
|
|
1381
|
+
return window.history;
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Accessor for Location DOM API.
|
|
1385
|
+
*/
|
|
1386
|
+
get location() {
|
|
1387
|
+
return window.location;
|
|
1388
|
+
}
|
|
1389
|
+
get base() {
|
|
1390
|
+
const base = import.meta.env?.BASE_URL;
|
|
1391
|
+
if (!base || base === "/") return "";
|
|
1392
|
+
return base;
|
|
1393
|
+
}
|
|
1394
|
+
get url() {
|
|
1395
|
+
const url = this.location.pathname + this.location.search;
|
|
1396
|
+
if (this.base) return url.replace(this.base, "");
|
|
1397
|
+
return url;
|
|
1398
|
+
}
|
|
1399
|
+
pushState(path, replace) {
|
|
1400
|
+
const url = this.base + path;
|
|
1401
|
+
if (replace) this.history.replaceState({}, "", url);
|
|
1402
|
+
else this.history.pushState({}, "", url);
|
|
1403
|
+
}
|
|
1404
|
+
async invalidate(props$1) {
|
|
1405
|
+
const previous = [];
|
|
1406
|
+
this.log.trace("Invalidating layers");
|
|
1407
|
+
if (props$1) {
|
|
1408
|
+
const [key] = Object.keys(props$1);
|
|
1409
|
+
const value = props$1[key];
|
|
1410
|
+
for (const layer of this.state.layers) {
|
|
1411
|
+
if (layer.props?.[key]) {
|
|
1412
|
+
previous.push({
|
|
1413
|
+
...layer,
|
|
1414
|
+
props: {
|
|
1415
|
+
...layer.props,
|
|
1416
|
+
[key]: value
|
|
1417
|
+
}
|
|
1418
|
+
});
|
|
1419
|
+
break;
|
|
1420
|
+
}
|
|
1421
|
+
previous.push(layer);
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
await this.render({ previous });
|
|
1425
|
+
}
|
|
1426
|
+
async go(url, options = {}) {
|
|
1427
|
+
this.log.trace(`Going to ${url}`, {
|
|
1428
|
+
url,
|
|
1429
|
+
options
|
|
1430
|
+
});
|
|
1431
|
+
await this.render({
|
|
1432
|
+
url,
|
|
1433
|
+
previous: options.force ? [] : this.state.layers,
|
|
1434
|
+
meta: options.meta
|
|
1435
|
+
});
|
|
1436
|
+
if (this.state.url.pathname + this.state.url.search !== url) {
|
|
1437
|
+
this.pushState(this.state.url.pathname + this.state.url.search);
|
|
1438
|
+
return;
|
|
1439
|
+
}
|
|
1440
|
+
this.pushState(url, options.replace);
|
|
1441
|
+
}
|
|
1442
|
+
async render(options = {}) {
|
|
1443
|
+
const previous = options.previous ?? this.state.layers;
|
|
1444
|
+
const url = options.url ?? this.url;
|
|
1445
|
+
const start = this.dateTimeProvider.now();
|
|
1446
|
+
this.transitioning = {
|
|
1447
|
+
to: url,
|
|
1448
|
+
from: this.state?.url.pathname
|
|
1449
|
+
};
|
|
1450
|
+
this.log.debug("Transitioning...", { to: url });
|
|
1451
|
+
const redirect = await this.router.transition(new URL(`http://localhost${url}`), previous, options.meta);
|
|
1452
|
+
if (redirect) {
|
|
1453
|
+
this.log.info("Redirecting to", { redirect });
|
|
1454
|
+
if (redirect.startsWith("http")) window.location.href = redirect;
|
|
1455
|
+
else return await this.render({ url: redirect });
|
|
1456
|
+
}
|
|
1457
|
+
const ms = this.dateTimeProvider.now().diff(start);
|
|
1458
|
+
this.log.info(`Transition OK [${ms}ms]`, this.transitioning);
|
|
1459
|
+
this.transitioning = void 0;
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Get embedded layers from the server.
|
|
1463
|
+
*/
|
|
1464
|
+
getHydrationState() {
|
|
1465
|
+
try {
|
|
1466
|
+
if ("__ssr" in window && typeof window.__ssr === "object") return window.__ssr;
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
console.error(error);
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
onTransitionEnd = $hook({
|
|
1472
|
+
on: "react:transition:end",
|
|
1473
|
+
handler: () => {
|
|
1474
|
+
if (this.options.scrollRestoration === "top" && typeof window !== "undefined" && !this.alepha.isTest()) {
|
|
1475
|
+
this.log.trace("Restoring scroll position to top");
|
|
1476
|
+
window.scrollTo(0, 0);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
});
|
|
1480
|
+
ready = $hook({
|
|
1481
|
+
on: "ready",
|
|
1482
|
+
handler: async () => {
|
|
1483
|
+
const hydration = this.getHydrationState();
|
|
1484
|
+
const previous = hydration?.layers ?? [];
|
|
1485
|
+
if (hydration) {
|
|
1486
|
+
for (const [key, value] of Object.entries(hydration)) if (key !== "layers") this.alepha.state.set(key, value);
|
|
1487
|
+
}
|
|
1488
|
+
await this.render({ previous });
|
|
1489
|
+
const element = this.router.root(this.state);
|
|
1490
|
+
await this.alepha.events.emit("react:browser:render", {
|
|
1491
|
+
element,
|
|
1492
|
+
root: this.getRootElement(),
|
|
1493
|
+
hydration,
|
|
1494
|
+
state: this.state
|
|
1495
|
+
});
|
|
1496
|
+
window.addEventListener("popstate", () => {
|
|
1497
|
+
if (this.base + this.state.url.pathname === this.location.pathname) return;
|
|
1498
|
+
this.log.debug("Popstate event triggered - rendering new state", { url: this.location.pathname + this.location.search });
|
|
1499
|
+
this.render();
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
});
|
|
1503
|
+
};
|
|
1504
|
+
|
|
1505
|
+
//#endregion
|
|
1506
|
+
//#region src/core/services/ReactRouter.ts
|
|
1507
|
+
var ReactRouter = class {
|
|
1508
|
+
alepha = $inject(Alepha);
|
|
1509
|
+
pageApi = $inject(ReactPageProvider);
|
|
1510
|
+
get state() {
|
|
1511
|
+
return this.alepha.state.get("alepha.react.router.state");
|
|
1512
|
+
}
|
|
1513
|
+
get pages() {
|
|
1514
|
+
return this.pageApi.getPages();
|
|
1515
|
+
}
|
|
1516
|
+
get concretePages() {
|
|
1517
|
+
return this.pageApi.getConcretePages();
|
|
1518
|
+
}
|
|
1519
|
+
get browser() {
|
|
1520
|
+
if (this.alepha.isBrowser()) return this.alepha.inject(ReactBrowserProvider);
|
|
1521
|
+
}
|
|
1522
|
+
isActive(href, options = {}) {
|
|
1523
|
+
const current = this.state.url.pathname;
|
|
1524
|
+
let isActive = current === href || current === `${href}/` || `${current}/` === href;
|
|
1525
|
+
if (options.startWith && !isActive) isActive = current.startsWith(href);
|
|
1526
|
+
return isActive;
|
|
1527
|
+
}
|
|
1528
|
+
path(name, config = {}) {
|
|
1529
|
+
return this.pageApi.pathname(name, {
|
|
1530
|
+
params: {
|
|
1531
|
+
...this.state.params,
|
|
1532
|
+
...config.params
|
|
1533
|
+
},
|
|
1534
|
+
query: config.query
|
|
1535
|
+
});
|
|
1536
|
+
}
|
|
1537
|
+
/**
|
|
1538
|
+
* Reload the current page.
|
|
1539
|
+
* This is equivalent to calling `go()` with the current pathname and search.
|
|
1540
|
+
*/
|
|
1541
|
+
async reload() {
|
|
1542
|
+
if (!this.browser) return;
|
|
1543
|
+
await this.go(this.location.pathname + this.location.search, {
|
|
1544
|
+
replace: true,
|
|
1545
|
+
force: true
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
getURL() {
|
|
1549
|
+
if (!this.browser) return this.state.url;
|
|
1550
|
+
return new URL(this.location.href);
|
|
1551
|
+
}
|
|
1552
|
+
get location() {
|
|
1553
|
+
if (!this.browser) throw new Error("Browser is required");
|
|
1554
|
+
return this.browser.location;
|
|
1555
|
+
}
|
|
1556
|
+
get current() {
|
|
1557
|
+
return this.state;
|
|
1558
|
+
}
|
|
1559
|
+
get pathname() {
|
|
1560
|
+
return this.state.url.pathname;
|
|
1561
|
+
}
|
|
1562
|
+
get query() {
|
|
1563
|
+
const query = {};
|
|
1564
|
+
for (const [key, value] of new URLSearchParams(this.state.url.search).entries()) query[key] = String(value);
|
|
1565
|
+
return query;
|
|
1566
|
+
}
|
|
1567
|
+
async back() {
|
|
1568
|
+
this.browser?.history.back();
|
|
1569
|
+
}
|
|
1570
|
+
async forward() {
|
|
1571
|
+
this.browser?.history.forward();
|
|
1572
|
+
}
|
|
1573
|
+
async invalidate(props$1) {
|
|
1574
|
+
await this.browser?.invalidate(props$1);
|
|
1575
|
+
}
|
|
1576
|
+
async go(path, options) {
|
|
1577
|
+
for (const page of this.pages) if (page.name === path) {
|
|
1578
|
+
await this.browser?.go(this.path(path, options), options);
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
await this.browser?.go(path, options);
|
|
1582
|
+
}
|
|
1583
|
+
anchor(path, options = {}) {
|
|
1584
|
+
let href = path;
|
|
1585
|
+
for (const page of this.pages) if (page.name === path) {
|
|
1586
|
+
href = this.path(path, options);
|
|
1587
|
+
break;
|
|
1588
|
+
}
|
|
1589
|
+
return {
|
|
1590
|
+
href: this.base(href),
|
|
1591
|
+
onClick: (ev) => {
|
|
1592
|
+
ev.stopPropagation();
|
|
1593
|
+
ev.preventDefault();
|
|
1594
|
+
this.go(href, options).catch(console.error);
|
|
1595
|
+
}
|
|
1596
|
+
};
|
|
1597
|
+
}
|
|
1598
|
+
base(path) {
|
|
1599
|
+
const base = import.meta.env?.BASE_URL;
|
|
1600
|
+
if (!base || base === "/") return path;
|
|
1601
|
+
return base + path;
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Set query params.
|
|
1605
|
+
*
|
|
1606
|
+
* @param record
|
|
1607
|
+
* @param options
|
|
1608
|
+
*/
|
|
1609
|
+
setQueryParams(record, options = {}) {
|
|
1610
|
+
const func = typeof record === "function" ? record : () => record;
|
|
1611
|
+
const search = new URLSearchParams(func(this.query)).toString();
|
|
1612
|
+
const state = search ? `${this.pathname}?${search}` : this.pathname;
|
|
1613
|
+
if (options.push) window.history.pushState({}, "", state);
|
|
1614
|
+
else window.history.replaceState({}, "", state);
|
|
1615
|
+
}
|
|
1616
|
+
};
|
|
1617
|
+
|
|
1618
|
+
//#endregion
|
|
1619
|
+
//#region src/core/index.ts
|
|
1620
|
+
/**
|
|
1621
|
+
* Provides full-stack React development with declarative routing, server-side rendering, and client-side hydration.
|
|
1622
|
+
*
|
|
1623
|
+
* The React module enables building modern React applications using the `$page` descriptor on class properties.
|
|
1624
|
+
* It delivers seamless server-side rendering, automatic code splitting, and client-side navigation with full
|
|
1625
|
+
* type safety and schema validation for route parameters and data.
|
|
1626
|
+
*
|
|
1627
|
+
* @see {@link $page}
|
|
1628
|
+
* @module alepha.react
|
|
1629
|
+
*/
|
|
1630
|
+
const AlephaReact = $module({
|
|
1631
|
+
name: "alepha.react",
|
|
1632
|
+
descriptors: [$page],
|
|
1633
|
+
services: [
|
|
1634
|
+
ReactServerProvider,
|
|
1635
|
+
ReactPageProvider,
|
|
1636
|
+
ReactRouter,
|
|
1637
|
+
ReactPageService,
|
|
1638
|
+
ReactPageServerService
|
|
1639
|
+
],
|
|
1640
|
+
register: (alepha) => alepha.with(AlephaDateTime).with(AlephaServer).with(AlephaServerCache).with(AlephaServerLinks).with({
|
|
1641
|
+
provide: ReactPageService,
|
|
1642
|
+
use: ReactPageServerService
|
|
1643
|
+
}).with(ReactServerProvider).with(ReactPageProvider).with(ReactRouter)
|
|
1644
|
+
});
|
|
1645
|
+
|
|
1646
|
+
//#endregion
|
|
1647
|
+
//#region ../../node_modules/oauth4webapi/build/index.js
|
|
1648
|
+
let USER_AGENT$1;
|
|
1649
|
+
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT$1 = `oauth4webapi/v3.8.2`;
|
|
1650
|
+
function looseInstanceOf(input, expected) {
|
|
1651
|
+
if (input == null) return false;
|
|
1652
|
+
try {
|
|
1653
|
+
return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
|
|
1654
|
+
} catch {
|
|
1655
|
+
return false;
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
const ERR_INVALID_ARG_VALUE$1 = "ERR_INVALID_ARG_VALUE";
|
|
1659
|
+
const ERR_INVALID_ARG_TYPE$1 = "ERR_INVALID_ARG_TYPE";
|
|
1660
|
+
function CodedTypeError$1(message, code, cause) {
|
|
1661
|
+
const err = new TypeError(message, { cause });
|
|
1662
|
+
Object.assign(err, { code });
|
|
1663
|
+
return err;
|
|
1664
|
+
}
|
|
1665
|
+
const allowInsecureRequests$1 = Symbol();
|
|
1666
|
+
const clockSkew$1 = Symbol();
|
|
1667
|
+
const clockTolerance$1 = Symbol();
|
|
1668
|
+
const customFetch$1 = Symbol();
|
|
1669
|
+
const modifyAssertion$1 = Symbol();
|
|
1670
|
+
const jweDecrypt = Symbol();
|
|
1671
|
+
const encoder = new TextEncoder();
|
|
1672
|
+
const decoder$1 = new TextDecoder();
|
|
1673
|
+
function buf(input) {
|
|
1674
|
+
if (typeof input === "string") return encoder.encode(input);
|
|
1675
|
+
return decoder$1.decode(input);
|
|
1676
|
+
}
|
|
1677
|
+
let encodeBase64Url;
|
|
1678
|
+
if (Uint8Array.prototype.toBase64) encodeBase64Url = (input) => {
|
|
1679
|
+
if (input instanceof ArrayBuffer) input = new Uint8Array(input);
|
|
1680
|
+
return input.toBase64({
|
|
1681
|
+
alphabet: "base64url",
|
|
1682
|
+
omitPadding: true
|
|
1683
|
+
});
|
|
1684
|
+
};
|
|
1685
|
+
else {
|
|
1686
|
+
const CHUNK_SIZE = 32768;
|
|
1687
|
+
encodeBase64Url = (input) => {
|
|
1688
|
+
if (input instanceof ArrayBuffer) input = new Uint8Array(input);
|
|
1689
|
+
const arr = [];
|
|
1690
|
+
for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
1691
|
+
return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
1692
|
+
};
|
|
1693
|
+
}
|
|
1694
|
+
let decodeBase64Url;
|
|
1695
|
+
if (Uint8Array.fromBase64) decodeBase64Url = (input) => {
|
|
1696
|
+
try {
|
|
1697
|
+
return Uint8Array.fromBase64(input, { alphabet: "base64url" });
|
|
1698
|
+
} catch (cause) {
|
|
1699
|
+
throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
|
|
1700
|
+
}
|
|
1701
|
+
};
|
|
1702
|
+
else decodeBase64Url = (input) => {
|
|
1703
|
+
try {
|
|
1704
|
+
const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
|
|
1705
|
+
const bytes = new Uint8Array(binary.length);
|
|
1706
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
1707
|
+
return bytes;
|
|
1708
|
+
} catch (cause) {
|
|
1709
|
+
throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
|
|
1710
|
+
}
|
|
1711
|
+
};
|
|
1712
|
+
function b64u(input) {
|
|
1713
|
+
if (typeof input === "string") return decodeBase64Url(input);
|
|
1714
|
+
return encodeBase64Url(input);
|
|
1715
|
+
}
|
|
1716
|
+
var UnsupportedOperationError = class extends Error {
|
|
1717
|
+
code;
|
|
1718
|
+
constructor(message, options) {
|
|
1719
|
+
super(message, options);
|
|
1720
|
+
this.name = this.constructor.name;
|
|
1721
|
+
this.code = UNSUPPORTED_OPERATION;
|
|
1722
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
var OperationProcessingError = class extends Error {
|
|
1726
|
+
code;
|
|
1727
|
+
constructor(message, options) {
|
|
1728
|
+
super(message, options);
|
|
1729
|
+
this.name = this.constructor.name;
|
|
1730
|
+
if (options?.code) this.code = options?.code;
|
|
1731
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
1732
|
+
}
|
|
1733
|
+
};
|
|
1734
|
+
function OPE(message, code, cause) {
|
|
1735
|
+
return new OperationProcessingError(message, {
|
|
1736
|
+
code,
|
|
1737
|
+
cause
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
function isJsonObject(input) {
|
|
1741
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) return false;
|
|
1742
|
+
return true;
|
|
1743
|
+
}
|
|
1744
|
+
function prepareHeaders(input) {
|
|
1745
|
+
if (looseInstanceOf(input, Headers)) input = Object.fromEntries(input.entries());
|
|
1746
|
+
const headers$1 = new Headers(input ?? {});
|
|
1747
|
+
if (USER_AGENT$1 && !headers$1.has("user-agent")) headers$1.set("user-agent", USER_AGENT$1);
|
|
1748
|
+
if (headers$1.has("authorization")) throw CodedTypeError$1("\"options.headers\" must not include the \"authorization\" header name", ERR_INVALID_ARG_VALUE$1);
|
|
1749
|
+
return headers$1;
|
|
1750
|
+
}
|
|
1751
|
+
function signal$1(url, value) {
|
|
1752
|
+
if (value !== void 0) {
|
|
1753
|
+
if (typeof value === "function") value = value(url.href);
|
|
1754
|
+
if (!(value instanceof AbortSignal)) throw CodedTypeError$1("\"options.signal\" must return or be an instance of AbortSignal", ERR_INVALID_ARG_TYPE$1);
|
|
1755
|
+
return value;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
function replaceDoubleSlash(pathname) {
|
|
1759
|
+
if (pathname.includes("//")) return pathname.replace("//", "/");
|
|
1760
|
+
return pathname;
|
|
1761
|
+
}
|
|
1762
|
+
function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
|
|
1763
|
+
if (url.pathname === "/") url.pathname = wellKnown;
|
|
1764
|
+
else url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
|
|
1765
|
+
return url;
|
|
1766
|
+
}
|
|
1767
|
+
function appendWellKnown(url, wellKnown) {
|
|
1768
|
+
url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
|
|
1769
|
+
return url;
|
|
1770
|
+
}
|
|
1771
|
+
async function performDiscovery$1(input, urlName, transform, options) {
|
|
1772
|
+
if (!(input instanceof URL)) throw CodedTypeError$1(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE$1);
|
|
1773
|
+
checkProtocol(input, options?.[allowInsecureRequests$1] !== true);
|
|
1774
|
+
const url = transform(new URL(input.href));
|
|
1775
|
+
const headers$1 = prepareHeaders(options?.headers);
|
|
1776
|
+
headers$1.set("accept", "application/json");
|
|
1777
|
+
return (options?.[customFetch$1] || fetch)(url.href, {
|
|
1778
|
+
body: void 0,
|
|
1779
|
+
headers: Object.fromEntries(headers$1.entries()),
|
|
1780
|
+
method: "GET",
|
|
1781
|
+
redirect: "manual",
|
|
1782
|
+
signal: signal$1(url, options?.signal)
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
async function discoveryRequest(issuerIdentifier, options) {
|
|
1786
|
+
return performDiscovery$1(issuerIdentifier, "issuerIdentifier", (url) => {
|
|
1787
|
+
switch (options?.algorithm) {
|
|
1788
|
+
case void 0:
|
|
1789
|
+
case "oidc":
|
|
1790
|
+
appendWellKnown(url, ".well-known/openid-configuration");
|
|
1791
|
+
break;
|
|
1792
|
+
case "oauth2":
|
|
1793
|
+
prependWellKnown(url, ".well-known/oauth-authorization-server");
|
|
1794
|
+
break;
|
|
1795
|
+
default: throw CodedTypeError$1("\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"", ERR_INVALID_ARG_VALUE$1);
|
|
1796
|
+
}
|
|
1797
|
+
return url;
|
|
1798
|
+
}, options);
|
|
1799
|
+
}
|
|
1800
|
+
function assertNumber(input, allow0, it, code, cause) {
|
|
1801
|
+
try {
|
|
1802
|
+
if (typeof input !== "number" || !Number.isFinite(input)) throw CodedTypeError$1(`${it} must be a number`, ERR_INVALID_ARG_TYPE$1, cause);
|
|
1803
|
+
if (input > 0) return;
|
|
1804
|
+
if (allow0) {
|
|
1805
|
+
if (input !== 0) throw CodedTypeError$1(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
1806
|
+
return;
|
|
1807
|
+
}
|
|
1808
|
+
throw CodedTypeError$1(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
1809
|
+
} catch (err) {
|
|
1810
|
+
if (code) throw OPE(err.message, code, cause);
|
|
1811
|
+
throw err;
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
function assertString$1(input, it, code, cause) {
|
|
1815
|
+
try {
|
|
1816
|
+
if (typeof input !== "string") throw CodedTypeError$1(`${it} must be a string`, ERR_INVALID_ARG_TYPE$1, cause);
|
|
1817
|
+
if (input.length === 0) throw CodedTypeError$1(`${it} must not be empty`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
1818
|
+
} catch (err) {
|
|
1819
|
+
if (code) throw OPE(err.message, code, cause);
|
|
1820
|
+
throw err;
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
|
|
1824
|
+
const expected = expectedIssuerIdentifier;
|
|
1825
|
+
if (!(expected instanceof URL) && expected !== _nodiscoverycheck) throw CodedTypeError$1("\"expectedIssuerIdentifier\" must be an instance of URL", ERR_INVALID_ARG_TYPE$1);
|
|
1826
|
+
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
1827
|
+
if (response.status !== 200) throw OPE("\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)", RESPONSE_IS_NOT_CONFORM, response);
|
|
1828
|
+
assertReadableResponse(response);
|
|
1829
|
+
const json = await getResponseJsonBody(response);
|
|
1830
|
+
assertString$1(json.issuer, "\"response\" body \"issuer\" property", INVALID_RESPONSE, { body: json });
|
|
1831
|
+
if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) throw OPE("\"response\" body \"issuer\" property does not match the expected value", JSON_ATTRIBUTE_COMPARISON, {
|
|
1832
|
+
expected: expected.href,
|
|
1833
|
+
body: json,
|
|
1834
|
+
attribute: "issuer"
|
|
1835
|
+
});
|
|
1836
|
+
return json;
|
|
1837
|
+
}
|
|
1838
|
+
function assertApplicationJson(response) {
|
|
1839
|
+
assertContentType(response, "application/json");
|
|
1840
|
+
}
|
|
1841
|
+
function notJson(response, ...types) {
|
|
1842
|
+
let msg = "\"response\" content-type must be ";
|
|
1843
|
+
if (types.length > 2) {
|
|
1844
|
+
const last = types.pop();
|
|
1845
|
+
msg += `${types.join(", ")}, or ${last}`;
|
|
1846
|
+
} else if (types.length === 2) msg += `${types[0]} or ${types[1]}`;
|
|
1847
|
+
else msg += types[0];
|
|
1848
|
+
return OPE(msg, RESPONSE_IS_NOT_JSON, response);
|
|
1849
|
+
}
|
|
1850
|
+
function assertContentType(response, contentType) {
|
|
1851
|
+
if (getContentType(response) !== contentType) throw notJson(response, contentType);
|
|
1852
|
+
}
|
|
1853
|
+
function randomBytes() {
|
|
1854
|
+
return b64u(crypto.getRandomValues(new Uint8Array(32)));
|
|
1855
|
+
}
|
|
1856
|
+
function generateRandomCodeVerifier() {
|
|
1857
|
+
return randomBytes();
|
|
1858
|
+
}
|
|
1859
|
+
function generateRandomState() {
|
|
1860
|
+
return randomBytes();
|
|
1861
|
+
}
|
|
1862
|
+
async function calculatePKCECodeChallenge$1(codeVerifier) {
|
|
1863
|
+
assertString$1(codeVerifier, "codeVerifier");
|
|
1864
|
+
return b64u(await crypto.subtle.digest("SHA-256", buf(codeVerifier)));
|
|
1865
|
+
}
|
|
1866
|
+
function getClockSkew(client) {
|
|
1867
|
+
const skew = client?.[clockSkew$1];
|
|
1868
|
+
return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
|
|
1869
|
+
}
|
|
1870
|
+
function getClockTolerance(client) {
|
|
1871
|
+
const tolerance = client?.[clockTolerance$1];
|
|
1872
|
+
return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
|
|
1873
|
+
}
|
|
1874
|
+
function epochTime() {
|
|
1875
|
+
return Math.floor(Date.now() / 1e3);
|
|
1876
|
+
}
|
|
1877
|
+
function assertAs(as) {
|
|
1878
|
+
if (typeof as !== "object" || as === null) throw CodedTypeError$1("\"as\" must be an object", ERR_INVALID_ARG_TYPE$1);
|
|
1879
|
+
assertString$1(as.issuer, "\"as.issuer\"");
|
|
1880
|
+
}
|
|
1881
|
+
function assertClient(client) {
|
|
1882
|
+
if (typeof client !== "object" || client === null) throw CodedTypeError$1("\"client\" must be an object", ERR_INVALID_ARG_TYPE$1);
|
|
1883
|
+
assertString$1(client.client_id, "\"client.client_id\"");
|
|
1884
|
+
}
|
|
1885
|
+
function ClientSecretPost$1(clientSecret) {
|
|
1886
|
+
assertString$1(clientSecret, "\"clientSecret\"");
|
|
1887
|
+
return (_as, client, body, _headers) => {
|
|
1888
|
+
body.set("client_id", client.client_id);
|
|
1889
|
+
body.set("client_secret", clientSecret);
|
|
1890
|
+
};
|
|
1891
|
+
}
|
|
1892
|
+
function None$1() {
|
|
1893
|
+
return (_as, client, body, _headers) => {
|
|
1894
|
+
body.set("client_id", client.client_id);
|
|
1895
|
+
};
|
|
1896
|
+
}
|
|
1897
|
+
const URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
|
|
1898
|
+
try {
|
|
1899
|
+
return new URL(url, base);
|
|
1900
|
+
} catch {
|
|
1901
|
+
return null;
|
|
1902
|
+
}
|
|
1903
|
+
};
|
|
1904
|
+
function checkProtocol(url, enforceHttps) {
|
|
1905
|
+
if (enforceHttps && url.protocol !== "https:") throw OPE("only requests to HTTPS are allowed", HTTP_REQUEST_FORBIDDEN, url);
|
|
1906
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw OPE("only HTTP and HTTPS requests are allowed", REQUEST_PROTOCOL_FORBIDDEN, url);
|
|
1907
|
+
}
|
|
1908
|
+
function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
|
|
1909
|
+
let url;
|
|
1910
|
+
if (typeof value !== "string" || !(url = URLParse(value))) throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `"as.mtls_endpoint_aliases.${endpoint}"` : `"as.${endpoint}"`}`, value === void 0 ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });
|
|
1911
|
+
checkProtocol(url, enforceHttps);
|
|
1912
|
+
return url;
|
|
1913
|
+
}
|
|
1914
|
+
function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
|
|
1915
|
+
if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
1916
|
+
return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
1917
|
+
}
|
|
1918
|
+
function isDPoPNonceError(err) {
|
|
1919
|
+
if (err instanceof WWWAuthenticateChallengeError) {
|
|
1920
|
+
const { 0: challenge, length } = err.cause;
|
|
1921
|
+
return length === 1 && challenge.scheme === "dpop" && challenge.parameters.error === "use_dpop_nonce";
|
|
1922
|
+
}
|
|
1923
|
+
if (err instanceof ResponseBodyError) return err.error === "use_dpop_nonce";
|
|
1924
|
+
return false;
|
|
1925
|
+
}
|
|
1926
|
+
var ResponseBodyError = class extends Error {
|
|
1927
|
+
cause;
|
|
1928
|
+
code;
|
|
1929
|
+
error;
|
|
1930
|
+
status;
|
|
1931
|
+
error_description;
|
|
1932
|
+
response;
|
|
1933
|
+
constructor(message, options) {
|
|
1934
|
+
super(message, options);
|
|
1935
|
+
this.name = this.constructor.name;
|
|
1936
|
+
this.code = RESPONSE_BODY_ERROR;
|
|
1937
|
+
this.cause = options.cause;
|
|
1938
|
+
this.error = options.cause.error;
|
|
1939
|
+
this.status = options.response.status;
|
|
1940
|
+
this.error_description = options.cause.error_description;
|
|
1941
|
+
Object.defineProperty(this, "response", {
|
|
1942
|
+
enumerable: false,
|
|
1943
|
+
value: options.response
|
|
1944
|
+
});
|
|
1945
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
var AuthorizationResponseError = class extends Error {
|
|
1949
|
+
cause;
|
|
1950
|
+
code;
|
|
1951
|
+
error;
|
|
1952
|
+
error_description;
|
|
1953
|
+
constructor(message, options) {
|
|
1954
|
+
super(message, options);
|
|
1955
|
+
this.name = this.constructor.name;
|
|
1956
|
+
this.code = AUTHORIZATION_RESPONSE_ERROR;
|
|
1957
|
+
this.cause = options.cause;
|
|
1958
|
+
this.error = options.cause.get("error");
|
|
1959
|
+
this.error_description = options.cause.get("error_description") ?? void 0;
|
|
1960
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
1961
|
+
}
|
|
1962
|
+
};
|
|
1963
|
+
var WWWAuthenticateChallengeError = class extends Error {
|
|
1964
|
+
cause;
|
|
1965
|
+
code;
|
|
1966
|
+
response;
|
|
1967
|
+
status;
|
|
1968
|
+
constructor(message, options) {
|
|
1969
|
+
super(message, options);
|
|
1970
|
+
this.name = this.constructor.name;
|
|
1971
|
+
this.code = WWW_AUTHENTICATE_CHALLENGE;
|
|
1972
|
+
this.cause = options.cause;
|
|
1973
|
+
this.status = options.response.status;
|
|
1974
|
+
this.response = options.response;
|
|
1975
|
+
Object.defineProperty(this, "response", { enumerable: false });
|
|
1976
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
1977
|
+
}
|
|
1978
|
+
};
|
|
1979
|
+
const tokenMatch = "[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+";
|
|
1980
|
+
const token68Match = "[a-zA-Z0-9\\-\\._\\~\\+\\/]+[=]{0,2}";
|
|
1981
|
+
const quotedParamMatcher = "(" + tokenMatch + ")\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"";
|
|
1982
|
+
const paramMatcher = "(" + tokenMatch + ")\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)";
|
|
1983
|
+
const schemeRE = /* @__PURE__ */ new RegExp("^[,\\s]*(" + tokenMatch + ")\\s(.*)");
|
|
1984
|
+
const quotedParamRE = /* @__PURE__ */ new RegExp("^[,\\s]*" + quotedParamMatcher + "[,\\s]*(.*)");
|
|
1985
|
+
const unquotedParamRE = /* @__PURE__ */ new RegExp("^[,\\s]*" + paramMatcher + "[,\\s]*(.*)");
|
|
1986
|
+
const token68ParamRE = /* @__PURE__ */ new RegExp("^(" + token68Match + ")(?:$|[,\\s])(.*)");
|
|
1987
|
+
function parseWwwAuthenticateChallenges(response) {
|
|
1988
|
+
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
1989
|
+
const header = response.headers.get("www-authenticate");
|
|
1990
|
+
if (header === null) return;
|
|
1991
|
+
const challenges = [];
|
|
1992
|
+
let rest = header;
|
|
1993
|
+
while (rest) {
|
|
1994
|
+
let match = rest.match(schemeRE);
|
|
1995
|
+
const scheme = match?.["1"].toLowerCase();
|
|
1996
|
+
rest = match?.["2"];
|
|
1997
|
+
if (!scheme) return;
|
|
1998
|
+
const parameters = {};
|
|
1999
|
+
let token68;
|
|
2000
|
+
while (rest) {
|
|
2001
|
+
let key;
|
|
2002
|
+
let value;
|
|
2003
|
+
if (match = rest.match(quotedParamRE)) {
|
|
2004
|
+
[, key, value, rest] = match;
|
|
2005
|
+
if (value.includes("\\")) try {
|
|
2006
|
+
value = JSON.parse(`"${value}"`);
|
|
2007
|
+
} catch {}
|
|
2008
|
+
parameters[key.toLowerCase()] = value;
|
|
2009
|
+
continue;
|
|
2010
|
+
}
|
|
2011
|
+
if (match = rest.match(unquotedParamRE)) {
|
|
2012
|
+
[, key, value, rest] = match;
|
|
2013
|
+
parameters[key.toLowerCase()] = value;
|
|
2014
|
+
continue;
|
|
2015
|
+
}
|
|
2016
|
+
if (match = rest.match(token68ParamRE)) {
|
|
2017
|
+
if (Object.keys(parameters).length) break;
|
|
2018
|
+
[, token68, rest] = match;
|
|
2019
|
+
break;
|
|
2020
|
+
}
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
const challenge = {
|
|
2024
|
+
scheme,
|
|
2025
|
+
parameters
|
|
2026
|
+
};
|
|
2027
|
+
if (token68) challenge.token68 = token68;
|
|
2028
|
+
challenges.push(challenge);
|
|
2029
|
+
}
|
|
2030
|
+
if (!challenges.length) return;
|
|
2031
|
+
return challenges;
|
|
2032
|
+
}
|
|
2033
|
+
async function parseOAuthResponseErrorBody(response) {
|
|
2034
|
+
if (response.status > 399 && response.status < 500) {
|
|
2035
|
+
assertReadableResponse(response);
|
|
2036
|
+
assertApplicationJson(response);
|
|
2037
|
+
try {
|
|
2038
|
+
const json = await response.clone().json();
|
|
2039
|
+
if (isJsonObject(json) && typeof json.error === "string" && json.error.length) return json;
|
|
2040
|
+
} catch {}
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
async function checkOAuthBodyError(response, expected, label) {
|
|
2044
|
+
if (response.status !== expected) {
|
|
2045
|
+
checkAuthenticationChallenges(response);
|
|
2046
|
+
let err;
|
|
2047
|
+
if (err = await parseOAuthResponseErrorBody(response)) {
|
|
2048
|
+
await response.body?.cancel();
|
|
2049
|
+
throw new ResponseBodyError("server responded with an error in the response body", {
|
|
2050
|
+
cause: err,
|
|
2051
|
+
response
|
|
2052
|
+
});
|
|
2053
|
+
}
|
|
2054
|
+
throw OPE(`"response" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
function assertDPoP(option) {
|
|
2058
|
+
if (!branded.has(option)) throw CodedTypeError$1("\"options.DPoP\" is not a valid DPoPHandle", ERR_INVALID_ARG_VALUE$1);
|
|
2059
|
+
}
|
|
2060
|
+
const skipSubjectCheck$1 = Symbol();
|
|
2061
|
+
function getContentType(input) {
|
|
2062
|
+
return input.headers.get("content-type")?.split(";")[0];
|
|
2063
|
+
}
|
|
2064
|
+
async function authenticatedRequest(as, client, clientAuthentication, url, body, headers$1, options) {
|
|
2065
|
+
await clientAuthentication(as, client, body, headers$1);
|
|
2066
|
+
headers$1.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
|
|
2067
|
+
return (options?.[customFetch$1] || fetch)(url.href, {
|
|
2068
|
+
body,
|
|
2069
|
+
headers: Object.fromEntries(headers$1.entries()),
|
|
2070
|
+
method: "POST",
|
|
2071
|
+
redirect: "manual",
|
|
2072
|
+
signal: signal$1(url, options?.signal)
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
|
|
2076
|
+
const url = resolveEndpoint(as, "token_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests$1] !== true);
|
|
2077
|
+
parameters.set("grant_type", grantType);
|
|
2078
|
+
const headers$1 = prepareHeaders(options?.headers);
|
|
2079
|
+
headers$1.set("accept", "application/json");
|
|
2080
|
+
if (options?.DPoP !== void 0) {
|
|
2081
|
+
assertDPoP(options.DPoP);
|
|
2082
|
+
await options.DPoP.addProof(url, headers$1, "POST");
|
|
2083
|
+
}
|
|
2084
|
+
const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers$1, options);
|
|
2085
|
+
options?.DPoP?.cacheNonce(response, url);
|
|
2086
|
+
return response;
|
|
2087
|
+
}
|
|
2088
|
+
async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
|
|
2089
|
+
assertAs(as);
|
|
2090
|
+
assertClient(client);
|
|
2091
|
+
assertString$1(refreshToken, "\"refreshToken\"");
|
|
2092
|
+
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
2093
|
+
parameters.set("refresh_token", refreshToken);
|
|
2094
|
+
return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
|
|
2095
|
+
}
|
|
2096
|
+
const idTokenClaims = /* @__PURE__ */ new WeakMap();
|
|
2097
|
+
const jwtRefs = /* @__PURE__ */ new WeakMap();
|
|
2098
|
+
function getValidatedIdTokenClaims(ref) {
|
|
2099
|
+
if (!ref.id_token) return;
|
|
2100
|
+
const claims = idTokenClaims.get(ref);
|
|
2101
|
+
if (!claims) throw CodedTypeError$1("\"ref\" was already garbage collected or did not resolve from the proper sources", ERR_INVALID_ARG_VALUE$1);
|
|
2102
|
+
return claims;
|
|
2103
|
+
}
|
|
2104
|
+
async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
|
|
2105
|
+
assertAs(as);
|
|
2106
|
+
assertClient(client);
|
|
2107
|
+
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
2108
|
+
await checkOAuthBodyError(response, 200, "Token Endpoint");
|
|
2109
|
+
assertReadableResponse(response);
|
|
2110
|
+
const json = await getResponseJsonBody(response);
|
|
2111
|
+
assertString$1(json.access_token, "\"response\" body \"access_token\" property", INVALID_RESPONSE, { body: json });
|
|
2112
|
+
assertString$1(json.token_type, "\"response\" body \"token_type\" property", INVALID_RESPONSE, { body: json });
|
|
2113
|
+
json.token_type = json.token_type.toLowerCase();
|
|
2114
|
+
if (json.expires_in !== void 0) {
|
|
2115
|
+
let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
|
|
2116
|
+
assertNumber(expiresIn, true, "\"response\" body \"expires_in\" property", INVALID_RESPONSE, { body: json });
|
|
2117
|
+
json.expires_in = expiresIn;
|
|
2118
|
+
}
|
|
2119
|
+
if (json.refresh_token !== void 0) assertString$1(json.refresh_token, "\"response\" body \"refresh_token\" property", INVALID_RESPONSE, { body: json });
|
|
2120
|
+
if (json.scope !== void 0 && typeof json.scope !== "string") throw OPE("\"response\" body \"scope\" property must be a string", INVALID_RESPONSE, { body: json });
|
|
2121
|
+
if (json.id_token !== void 0) {
|
|
2122
|
+
assertString$1(json.id_token, "\"response\" body \"id_token\" property", INVALID_RESPONSE, { body: json });
|
|
2123
|
+
const requiredClaims = [
|
|
2124
|
+
"aud",
|
|
2125
|
+
"exp",
|
|
2126
|
+
"iat",
|
|
2127
|
+
"iss",
|
|
2128
|
+
"sub"
|
|
2129
|
+
];
|
|
2130
|
+
if (client.require_auth_time === true) requiredClaims.push("auth_time");
|
|
2131
|
+
if (client.default_max_age !== void 0) {
|
|
2132
|
+
assertNumber(client.default_max_age, true, "\"client.default_max_age\"");
|
|
2133
|
+
requiredClaims.push("auth_time");
|
|
2134
|
+
}
|
|
2135
|
+
if (additionalRequiredIdTokenClaims?.length) requiredClaims.push(...additionalRequiredIdTokenClaims);
|
|
2136
|
+
const { claims, jwt } = await validateJwt(json.id_token, checkSigningAlgorithm.bind(void 0, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, "RS256"), getClockSkew(client), getClockTolerance(client), decryptFn).then(validatePresence.bind(void 0, requiredClaims)).then(validateIssuer.bind(void 0, as)).then(validateAudience.bind(void 0, client.client_id));
|
|
2137
|
+
if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
|
|
2138
|
+
if (claims.azp === void 0) throw OPE("ID Token \"aud\" (audience) claim includes additional untrusted audiences", JWT_CLAIM_COMPARISON, {
|
|
2139
|
+
claims,
|
|
2140
|
+
claim: "aud"
|
|
2141
|
+
});
|
|
2142
|
+
if (claims.azp !== client.client_id) throw OPE("unexpected ID Token \"azp\" (authorized party) claim value", JWT_CLAIM_COMPARISON, {
|
|
2143
|
+
expected: client.client_id,
|
|
2144
|
+
claims,
|
|
2145
|
+
claim: "azp"
|
|
2146
|
+
});
|
|
2147
|
+
}
|
|
2148
|
+
if (claims.auth_time !== void 0) assertNumber(claims.auth_time, true, "ID Token \"auth_time\" (authentication time)", INVALID_RESPONSE, { claims });
|
|
2149
|
+
jwtRefs.set(response, jwt);
|
|
2150
|
+
idTokenClaims.set(json, claims);
|
|
2151
|
+
}
|
|
2152
|
+
if (recognizedTokenTypes?.[json.token_type] !== void 0) recognizedTokenTypes[json.token_type](response, json);
|
|
2153
|
+
else if (json.token_type !== "dpop" && json.token_type !== "bearer") throw new UnsupportedOperationError("unsupported `token_type` value", { cause: { body: json } });
|
|
2154
|
+
return json;
|
|
2155
|
+
}
|
|
2156
|
+
function checkAuthenticationChallenges(response) {
|
|
2157
|
+
let challenges;
|
|
2158
|
+
if (challenges = parseWwwAuthenticateChallenges(response)) throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", {
|
|
2159
|
+
cause: challenges,
|
|
2160
|
+
response
|
|
2161
|
+
});
|
|
2162
|
+
}
|
|
2163
|
+
async function processRefreshTokenResponse(as, client, response, options) {
|
|
2164
|
+
return processGenericAccessTokenResponse(as, client, response, void 0, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
2165
|
+
}
|
|
2166
|
+
function validateAudience(expected, result) {
|
|
2167
|
+
if (Array.isArray(result.claims.aud)) {
|
|
2168
|
+
if (!result.claims.aud.includes(expected)) throw OPE("unexpected JWT \"aud\" (audience) claim value", JWT_CLAIM_COMPARISON, {
|
|
2169
|
+
expected,
|
|
2170
|
+
claims: result.claims,
|
|
2171
|
+
claim: "aud"
|
|
2172
|
+
});
|
|
2173
|
+
} else if (result.claims.aud !== expected) throw OPE("unexpected JWT \"aud\" (audience) claim value", JWT_CLAIM_COMPARISON, {
|
|
2174
|
+
expected,
|
|
2175
|
+
claims: result.claims,
|
|
2176
|
+
claim: "aud"
|
|
2177
|
+
});
|
|
2178
|
+
return result;
|
|
2179
|
+
}
|
|
2180
|
+
function validateIssuer(as, result) {
|
|
2181
|
+
const expected = as[_expectedIssuer]?.(result) ?? as.issuer;
|
|
2182
|
+
if (result.claims.iss !== expected) throw OPE("unexpected JWT \"iss\" (issuer) claim value", JWT_CLAIM_COMPARISON, {
|
|
2183
|
+
expected,
|
|
2184
|
+
claims: result.claims,
|
|
2185
|
+
claim: "iss"
|
|
2186
|
+
});
|
|
2187
|
+
return result;
|
|
2188
|
+
}
|
|
2189
|
+
const branded = /* @__PURE__ */ new WeakSet();
|
|
2190
|
+
function brand(searchParams) {
|
|
2191
|
+
branded.add(searchParams);
|
|
2192
|
+
return searchParams;
|
|
2193
|
+
}
|
|
2194
|
+
const nopkce = Symbol();
|
|
2195
|
+
async function authorizationCodeGrantRequest(as, client, clientAuthentication, callbackParameters, redirectUri, codeVerifier, options) {
|
|
2196
|
+
assertAs(as);
|
|
2197
|
+
assertClient(client);
|
|
2198
|
+
if (!branded.has(callbackParameters)) throw CodedTypeError$1("\"callbackParameters\" must be an instance of URLSearchParams obtained from \"validateAuthResponse()\", or \"validateJwtAuthResponse()", ERR_INVALID_ARG_VALUE$1);
|
|
2199
|
+
assertString$1(redirectUri, "\"redirectUri\"");
|
|
2200
|
+
const code = getURLSearchParameter(callbackParameters, "code");
|
|
2201
|
+
if (!code) throw OPE("no authorization code in \"callbackParameters\"", INVALID_RESPONSE);
|
|
2202
|
+
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
2203
|
+
parameters.set("redirect_uri", redirectUri);
|
|
2204
|
+
parameters.set("code", code);
|
|
2205
|
+
if (codeVerifier !== nopkce) {
|
|
2206
|
+
assertString$1(codeVerifier, "\"codeVerifier\"");
|
|
2207
|
+
parameters.set("code_verifier", codeVerifier);
|
|
2208
|
+
}
|
|
2209
|
+
return tokenEndpointRequest(as, client, clientAuthentication, "authorization_code", parameters, options);
|
|
2210
|
+
}
|
|
2211
|
+
const jwtClaimNames = {
|
|
2212
|
+
aud: "audience",
|
|
2213
|
+
c_hash: "code hash",
|
|
2214
|
+
client_id: "client id",
|
|
2215
|
+
exp: "expiration time",
|
|
2216
|
+
iat: "issued at",
|
|
2217
|
+
iss: "issuer",
|
|
2218
|
+
jti: "jwt id",
|
|
2219
|
+
nonce: "nonce",
|
|
2220
|
+
s_hash: "state hash",
|
|
2221
|
+
sub: "subject",
|
|
2222
|
+
ath: "access token hash",
|
|
2223
|
+
htm: "http method",
|
|
2224
|
+
htu: "http uri",
|
|
2225
|
+
cnf: "confirmation",
|
|
2226
|
+
auth_time: "authentication time"
|
|
2227
|
+
};
|
|
2228
|
+
function validatePresence(required, result) {
|
|
2229
|
+
for (const claim of required) if (result.claims[claim] === void 0) throw OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, { claims: result.claims });
|
|
2230
|
+
return result;
|
|
2231
|
+
}
|
|
2232
|
+
const expectNoNonce = Symbol();
|
|
2233
|
+
const skipAuthTimeCheck = Symbol();
|
|
2234
|
+
async function processAuthorizationCodeResponse(as, client, response, options) {
|
|
2235
|
+
if (typeof options?.expectedNonce === "string" || typeof options?.maxAge === "number" || options?.requireIdToken) return processAuthorizationCodeOpenIDResponse(as, client, response, options.expectedNonce, options.maxAge, options[jweDecrypt], options.recognizedTokenTypes);
|
|
2236
|
+
return processAuthorizationCodeOAuth2Response(as, client, response, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
2237
|
+
}
|
|
2238
|
+
async function processAuthorizationCodeOpenIDResponse(as, client, response, expectedNonce, maxAge, decryptFn, recognizedTokenTypes) {
|
|
2239
|
+
const additionalRequiredClaims = [];
|
|
2240
|
+
switch (expectedNonce) {
|
|
2241
|
+
case void 0:
|
|
2242
|
+
expectedNonce = expectNoNonce;
|
|
2243
|
+
break;
|
|
2244
|
+
case expectNoNonce: break;
|
|
2245
|
+
default:
|
|
2246
|
+
assertString$1(expectedNonce, "\"expectedNonce\" argument");
|
|
2247
|
+
additionalRequiredClaims.push("nonce");
|
|
2248
|
+
}
|
|
2249
|
+
maxAge ??= client.default_max_age;
|
|
2250
|
+
switch (maxAge) {
|
|
2251
|
+
case void 0:
|
|
2252
|
+
maxAge = skipAuthTimeCheck;
|
|
2253
|
+
break;
|
|
2254
|
+
case skipAuthTimeCheck: break;
|
|
2255
|
+
default:
|
|
2256
|
+
assertNumber(maxAge, true, "\"maxAge\" argument");
|
|
2257
|
+
additionalRequiredClaims.push("auth_time");
|
|
2258
|
+
}
|
|
2259
|
+
const result = await processGenericAccessTokenResponse(as, client, response, additionalRequiredClaims, decryptFn, recognizedTokenTypes);
|
|
2260
|
+
assertString$1(result.id_token, "\"response\" body \"id_token\" property", INVALID_RESPONSE, { body: result });
|
|
2261
|
+
const claims = getValidatedIdTokenClaims(result);
|
|
2262
|
+
if (maxAge !== skipAuthTimeCheck) {
|
|
2263
|
+
const now = epochTime() + getClockSkew(client);
|
|
2264
|
+
const tolerance = getClockTolerance(client);
|
|
2265
|
+
if (claims.auth_time + maxAge < now - tolerance) throw OPE("too much time has elapsed since the last End-User authentication", JWT_TIMESTAMP_CHECK, {
|
|
2266
|
+
claims,
|
|
2267
|
+
now,
|
|
2268
|
+
tolerance,
|
|
2269
|
+
claim: "auth_time"
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
if (expectedNonce === expectNoNonce) {
|
|
2273
|
+
if (claims.nonce !== void 0) throw OPE("unexpected ID Token \"nonce\" claim value", JWT_CLAIM_COMPARISON, {
|
|
2274
|
+
expected: void 0,
|
|
2275
|
+
claims,
|
|
2276
|
+
claim: "nonce"
|
|
2277
|
+
});
|
|
2278
|
+
} else if (claims.nonce !== expectedNonce) throw OPE("unexpected ID Token \"nonce\" claim value", JWT_CLAIM_COMPARISON, {
|
|
2279
|
+
expected: expectedNonce,
|
|
2280
|
+
claims,
|
|
2281
|
+
claim: "nonce"
|
|
2282
|
+
});
|
|
2283
|
+
return result;
|
|
2284
|
+
}
|
|
2285
|
+
async function processAuthorizationCodeOAuth2Response(as, client, response, decryptFn, recognizedTokenTypes) {
|
|
2286
|
+
const result = await processGenericAccessTokenResponse(as, client, response, void 0, decryptFn, recognizedTokenTypes);
|
|
2287
|
+
const claims = getValidatedIdTokenClaims(result);
|
|
2288
|
+
if (claims) {
|
|
2289
|
+
if (client.default_max_age !== void 0) {
|
|
2290
|
+
assertNumber(client.default_max_age, true, "\"client.default_max_age\"");
|
|
2291
|
+
const now = epochTime() + getClockSkew(client);
|
|
2292
|
+
const tolerance = getClockTolerance(client);
|
|
2293
|
+
if (claims.auth_time + client.default_max_age < now - tolerance) throw OPE("too much time has elapsed since the last End-User authentication", JWT_TIMESTAMP_CHECK, {
|
|
2294
|
+
claims,
|
|
2295
|
+
now,
|
|
2296
|
+
tolerance,
|
|
2297
|
+
claim: "auth_time"
|
|
2298
|
+
});
|
|
2299
|
+
}
|
|
2300
|
+
if (claims.nonce !== void 0) throw OPE("unexpected ID Token \"nonce\" claim value", JWT_CLAIM_COMPARISON, {
|
|
2301
|
+
expected: void 0,
|
|
2302
|
+
claims,
|
|
2303
|
+
claim: "nonce"
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
return result;
|
|
2307
|
+
}
|
|
2308
|
+
const WWW_AUTHENTICATE_CHALLENGE = "OAUTH_WWW_AUTHENTICATE_CHALLENGE";
|
|
2309
|
+
const RESPONSE_BODY_ERROR = "OAUTH_RESPONSE_BODY_ERROR";
|
|
2310
|
+
const UNSUPPORTED_OPERATION = "OAUTH_UNSUPPORTED_OPERATION";
|
|
2311
|
+
const AUTHORIZATION_RESPONSE_ERROR = "OAUTH_AUTHORIZATION_RESPONSE_ERROR";
|
|
2312
|
+
const PARSE_ERROR = "OAUTH_PARSE_ERROR";
|
|
2313
|
+
const INVALID_RESPONSE = "OAUTH_INVALID_RESPONSE";
|
|
2314
|
+
const RESPONSE_IS_NOT_JSON = "OAUTH_RESPONSE_IS_NOT_JSON";
|
|
2315
|
+
const RESPONSE_IS_NOT_CONFORM = "OAUTH_RESPONSE_IS_NOT_CONFORM";
|
|
2316
|
+
const HTTP_REQUEST_FORBIDDEN = "OAUTH_HTTP_REQUEST_FORBIDDEN";
|
|
2317
|
+
const REQUEST_PROTOCOL_FORBIDDEN = "OAUTH_REQUEST_PROTOCOL_FORBIDDEN";
|
|
2318
|
+
const JWT_TIMESTAMP_CHECK = "OAUTH_JWT_TIMESTAMP_CHECK_FAILED";
|
|
2319
|
+
const JWT_CLAIM_COMPARISON = "OAUTH_JWT_CLAIM_COMPARISON_FAILED";
|
|
2320
|
+
const JSON_ATTRIBUTE_COMPARISON = "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";
|
|
2321
|
+
const MISSING_SERVER_METADATA = "OAUTH_MISSING_SERVER_METADATA";
|
|
2322
|
+
const INVALID_SERVER_METADATA = "OAUTH_INVALID_SERVER_METADATA";
|
|
2323
|
+
function assertReadableResponse(response) {
|
|
2324
|
+
if (response.bodyUsed) throw CodedTypeError$1("\"response\" body has been used already", ERR_INVALID_ARG_VALUE$1);
|
|
2325
|
+
}
|
|
2326
|
+
async function validateJwt(jws, checkAlg, clockSkew$2, clockTolerance$2, decryptJwt) {
|
|
2327
|
+
let { 0: protectedHeader, 1: payload, length } = jws.split(".");
|
|
2328
|
+
if (length === 5) if (decryptJwt !== void 0) {
|
|
2329
|
+
jws = await decryptJwt(jws);
|
|
2330
|
+
({0: protectedHeader, 1: payload, length} = jws.split("."));
|
|
2331
|
+
} else throw new UnsupportedOperationError("JWE decryption is not configured", { cause: jws });
|
|
2332
|
+
if (length !== 3) throw OPE("Invalid JWT", INVALID_RESPONSE, jws);
|
|
2333
|
+
let header;
|
|
2334
|
+
try {
|
|
2335
|
+
header = JSON.parse(buf(b64u(protectedHeader)));
|
|
2336
|
+
} catch (cause) {
|
|
2337
|
+
throw OPE("failed to parse JWT Header body as base64url encoded JSON", PARSE_ERROR, cause);
|
|
2338
|
+
}
|
|
2339
|
+
if (!isJsonObject(header)) throw OPE("JWT Header must be a top level object", INVALID_RESPONSE, jws);
|
|
2340
|
+
checkAlg(header);
|
|
2341
|
+
if (header.crit !== void 0) throw new UnsupportedOperationError("no JWT \"crit\" header parameter extensions are supported", { cause: { header } });
|
|
2342
|
+
let claims;
|
|
2343
|
+
try {
|
|
2344
|
+
claims = JSON.parse(buf(b64u(payload)));
|
|
2345
|
+
} catch (cause) {
|
|
2346
|
+
throw OPE("failed to parse JWT Payload body as base64url encoded JSON", PARSE_ERROR, cause);
|
|
2347
|
+
}
|
|
2348
|
+
if (!isJsonObject(claims)) throw OPE("JWT Payload must be a top level object", INVALID_RESPONSE, jws);
|
|
2349
|
+
const now = epochTime() + clockSkew$2;
|
|
2350
|
+
if (claims.exp !== void 0) {
|
|
2351
|
+
if (typeof claims.exp !== "number") throw OPE("unexpected JWT \"exp\" (expiration time) claim type", INVALID_RESPONSE, { claims });
|
|
2352
|
+
if (claims.exp <= now - clockTolerance$2) throw OPE("unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp", JWT_TIMESTAMP_CHECK, {
|
|
2353
|
+
claims,
|
|
2354
|
+
now,
|
|
2355
|
+
tolerance: clockTolerance$2,
|
|
2356
|
+
claim: "exp"
|
|
2357
|
+
});
|
|
2358
|
+
}
|
|
2359
|
+
if (claims.iat !== void 0) {
|
|
2360
|
+
if (typeof claims.iat !== "number") throw OPE("unexpected JWT \"iat\" (issued at) claim type", INVALID_RESPONSE, { claims });
|
|
2361
|
+
}
|
|
2362
|
+
if (claims.iss !== void 0) {
|
|
2363
|
+
if (typeof claims.iss !== "string") throw OPE("unexpected JWT \"iss\" (issuer) claim type", INVALID_RESPONSE, { claims });
|
|
2364
|
+
}
|
|
2365
|
+
if (claims.nbf !== void 0) {
|
|
2366
|
+
if (typeof claims.nbf !== "number") throw OPE("unexpected JWT \"nbf\" (not before) claim type", INVALID_RESPONSE, { claims });
|
|
2367
|
+
if (claims.nbf > now + clockTolerance$2) throw OPE("unexpected JWT \"nbf\" (not before) claim value", JWT_TIMESTAMP_CHECK, {
|
|
2368
|
+
claims,
|
|
2369
|
+
now,
|
|
2370
|
+
tolerance: clockTolerance$2,
|
|
2371
|
+
claim: "nbf"
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
if (claims.aud !== void 0) {
|
|
2375
|
+
if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) throw OPE("unexpected JWT \"aud\" (audience) claim type", INVALID_RESPONSE, { claims });
|
|
2376
|
+
}
|
|
2377
|
+
return {
|
|
2378
|
+
header,
|
|
2379
|
+
claims,
|
|
2380
|
+
jwt: jws
|
|
2381
|
+
};
|
|
2382
|
+
}
|
|
2383
|
+
async function consumeStream(request) {
|
|
2384
|
+
if (request.bodyUsed) throw CodedTypeError$1("form_post Request instances must contain a readable body", ERR_INVALID_ARG_VALUE$1, { cause: request });
|
|
2385
|
+
return request.text();
|
|
2386
|
+
}
|
|
2387
|
+
async function formPostResponse(request) {
|
|
2388
|
+
if (request.method !== "POST") throw CodedTypeError$1("form_post responses are expected to use the POST method", ERR_INVALID_ARG_VALUE$1, { cause: request });
|
|
2389
|
+
if (getContentType(request) !== "application/x-www-form-urlencoded") throw CodedTypeError$1("form_post responses are expected to use the application/x-www-form-urlencoded content-type", ERR_INVALID_ARG_VALUE$1, { cause: request });
|
|
2390
|
+
return consumeStream(request);
|
|
2391
|
+
}
|
|
2392
|
+
function checkSigningAlgorithm(client, issuer, fallback, header) {
|
|
2393
|
+
if (client !== void 0) {
|
|
2394
|
+
if (typeof client === "string" ? header.alg !== client : !client.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
2395
|
+
header,
|
|
2396
|
+
expected: client,
|
|
2397
|
+
reason: "client configuration"
|
|
2398
|
+
});
|
|
2399
|
+
return;
|
|
2400
|
+
}
|
|
2401
|
+
if (Array.isArray(issuer)) {
|
|
2402
|
+
if (!issuer.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
2403
|
+
header,
|
|
2404
|
+
expected: issuer,
|
|
2405
|
+
reason: "authorization server metadata"
|
|
2406
|
+
});
|
|
2407
|
+
return;
|
|
2408
|
+
}
|
|
2409
|
+
if (fallback !== void 0) {
|
|
2410
|
+
if (typeof fallback === "string" ? header.alg !== fallback : typeof fallback === "function" ? !fallback(header.alg) : !fallback.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
2411
|
+
header,
|
|
2412
|
+
expected: fallback,
|
|
2413
|
+
reason: "default value"
|
|
2414
|
+
});
|
|
2415
|
+
return;
|
|
2416
|
+
}
|
|
2417
|
+
throw OPE("missing client or server configuration to verify used JWT \"alg\" header parameter", void 0, {
|
|
2418
|
+
client,
|
|
2419
|
+
issuer,
|
|
2420
|
+
fallback
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
function getURLSearchParameter(parameters, name) {
|
|
2424
|
+
const { 0: value, length } = parameters.getAll(name);
|
|
2425
|
+
if (length > 1) throw OPE(`"${name}" parameter must be provided only once`, INVALID_RESPONSE);
|
|
2426
|
+
return value;
|
|
2427
|
+
}
|
|
2428
|
+
const skipStateCheck$1 = Symbol();
|
|
2429
|
+
const expectNoState = Symbol();
|
|
2430
|
+
function validateAuthResponse(as, client, parameters, expectedState) {
|
|
2431
|
+
assertAs(as);
|
|
2432
|
+
assertClient(client);
|
|
2433
|
+
if (parameters instanceof URL) parameters = parameters.searchParams;
|
|
2434
|
+
if (!(parameters instanceof URLSearchParams)) throw CodedTypeError$1("\"parameters\" must be an instance of URLSearchParams, or URL", ERR_INVALID_ARG_TYPE$1);
|
|
2435
|
+
if (getURLSearchParameter(parameters, "response")) throw OPE("\"parameters\" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()", INVALID_RESPONSE, { parameters });
|
|
2436
|
+
const iss = getURLSearchParameter(parameters, "iss");
|
|
2437
|
+
const state = getURLSearchParameter(parameters, "state");
|
|
2438
|
+
if (!iss && as.authorization_response_iss_parameter_supported) throw OPE("response parameter \"iss\" (issuer) missing", INVALID_RESPONSE, { parameters });
|
|
2439
|
+
if (iss && iss !== as.issuer) throw OPE("unexpected \"iss\" (issuer) response parameter value", INVALID_RESPONSE, {
|
|
2440
|
+
expected: as.issuer,
|
|
2441
|
+
parameters
|
|
2442
|
+
});
|
|
2443
|
+
switch (expectedState) {
|
|
2444
|
+
case void 0:
|
|
2445
|
+
case expectNoState:
|
|
2446
|
+
if (state !== void 0) throw OPE("unexpected \"state\" response parameter encountered", INVALID_RESPONSE, {
|
|
2447
|
+
expected: void 0,
|
|
2448
|
+
parameters
|
|
2449
|
+
});
|
|
2450
|
+
break;
|
|
2451
|
+
case skipStateCheck$1: break;
|
|
2452
|
+
default:
|
|
2453
|
+
assertString$1(expectedState, "\"expectedState\" argument");
|
|
2454
|
+
if (state !== expectedState) throw OPE(state === void 0 ? "response parameter \"state\" missing" : "unexpected \"state\" response parameter value", INVALID_RESPONSE, {
|
|
2455
|
+
expected: expectedState,
|
|
2456
|
+
parameters
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
if (getURLSearchParameter(parameters, "error")) throw new AuthorizationResponseError("authorization response from the server is an error", { cause: parameters });
|
|
2460
|
+
const id_token = getURLSearchParameter(parameters, "id_token");
|
|
2461
|
+
const token = getURLSearchParameter(parameters, "token");
|
|
2462
|
+
if (id_token !== void 0 || token !== void 0) throw new UnsupportedOperationError("implicit and hybrid flows are not supported");
|
|
2463
|
+
return brand(new URLSearchParams(parameters));
|
|
2464
|
+
}
|
|
2465
|
+
async function getResponseJsonBody(response, check = assertApplicationJson) {
|
|
2466
|
+
let json;
|
|
2467
|
+
try {
|
|
2468
|
+
json = await response.json();
|
|
2469
|
+
} catch (cause) {
|
|
2470
|
+
check(response);
|
|
2471
|
+
throw OPE("failed to parse \"response\" body as JSON", PARSE_ERROR, cause);
|
|
2472
|
+
}
|
|
2473
|
+
if (!isJsonObject(json)) throw OPE("\"response\" body must be a top level object", INVALID_RESPONSE, { body: json });
|
|
2474
|
+
return json;
|
|
2475
|
+
}
|
|
2476
|
+
const _nodiscoverycheck = Symbol();
|
|
2477
|
+
const _expectedIssuer = Symbol();
|
|
2478
|
+
|
|
2479
|
+
//#endregion
|
|
2480
|
+
//#region ../../node_modules/openid-client/build/index.js
|
|
2481
|
+
let headers;
|
|
2482
|
+
let USER_AGENT;
|
|
2483
|
+
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
|
|
2484
|
+
USER_AGENT = `openid-client/v6.8.1`;
|
|
2485
|
+
headers = { "user-agent": USER_AGENT };
|
|
2486
|
+
}
|
|
2487
|
+
const int = (config) => {
|
|
2488
|
+
return props.get(config);
|
|
2489
|
+
};
|
|
2490
|
+
let props;
|
|
2491
|
+
let tbi;
|
|
2492
|
+
function ClientSecretPost(clientSecret) {
|
|
2493
|
+
if (clientSecret !== void 0) return ClientSecretPost$1(clientSecret);
|
|
2494
|
+
tbi ||= /* @__PURE__ */ new WeakMap();
|
|
2495
|
+
return (as, client, body, headers$1) => {
|
|
2496
|
+
let auth;
|
|
2497
|
+
if (!(auth = tbi.get(client))) {
|
|
2498
|
+
assertString(client.client_secret, "\"metadata.client_secret\"");
|
|
2499
|
+
auth = ClientSecretPost$1(client.client_secret);
|
|
2500
|
+
tbi.set(client, auth);
|
|
2501
|
+
}
|
|
2502
|
+
return auth(as, client, body, headers$1);
|
|
2503
|
+
};
|
|
2504
|
+
}
|
|
2505
|
+
function assertString(input, it) {
|
|
2506
|
+
if (typeof input !== "string") throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);
|
|
2507
|
+
if (input.length === 0) throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);
|
|
2508
|
+
}
|
|
2509
|
+
function None() {
|
|
2510
|
+
return None$1();
|
|
2511
|
+
}
|
|
2512
|
+
const skipStateCheck = skipStateCheck$1;
|
|
2513
|
+
const skipSubjectCheck = skipSubjectCheck$1;
|
|
2514
|
+
const customFetch = customFetch$1;
|
|
2515
|
+
const modifyAssertion = modifyAssertion$1;
|
|
2516
|
+
const clockSkew = clockSkew$1;
|
|
2517
|
+
const clockTolerance = clockTolerance$1;
|
|
2518
|
+
const ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
|
|
2519
|
+
const ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
|
|
2520
|
+
function CodedTypeError(message, code, cause) {
|
|
2521
|
+
const err = new TypeError(message, { cause });
|
|
2522
|
+
Object.assign(err, { code });
|
|
2523
|
+
return err;
|
|
2524
|
+
}
|
|
2525
|
+
function calculatePKCECodeChallenge(codeVerifier) {
|
|
2526
|
+
return calculatePKCECodeChallenge$1(codeVerifier);
|
|
2527
|
+
}
|
|
2528
|
+
function randomPKCECodeVerifier() {
|
|
2529
|
+
return generateRandomCodeVerifier();
|
|
2530
|
+
}
|
|
2531
|
+
function randomState() {
|
|
2532
|
+
return generateRandomState();
|
|
2533
|
+
}
|
|
2534
|
+
var ClientError = class extends Error {
|
|
2535
|
+
code;
|
|
2536
|
+
constructor(message, options) {
|
|
2537
|
+
super(message, options);
|
|
2538
|
+
this.name = this.constructor.name;
|
|
2539
|
+
this.code = options?.code;
|
|
2540
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
2541
|
+
}
|
|
2542
|
+
};
|
|
2543
|
+
const decoder = new TextDecoder();
|
|
2544
|
+
function e(msg, cause, code) {
|
|
2545
|
+
return new ClientError(msg, {
|
|
2546
|
+
cause,
|
|
2547
|
+
code
|
|
2548
|
+
});
|
|
2549
|
+
}
|
|
2550
|
+
function errorHandler(err) {
|
|
2551
|
+
if (err instanceof TypeError || err instanceof ClientError || err instanceof ResponseBodyError || err instanceof AuthorizationResponseError || err instanceof WWWAuthenticateChallengeError) throw err;
|
|
2552
|
+
if (err instanceof OperationProcessingError) switch (err.code) {
|
|
2553
|
+
case HTTP_REQUEST_FORBIDDEN: throw e("only requests to HTTPS are allowed", err, err.code);
|
|
2554
|
+
case REQUEST_PROTOCOL_FORBIDDEN: throw e("only requests to HTTP or HTTPS are allowed", err, err.code);
|
|
2555
|
+
case RESPONSE_IS_NOT_CONFORM: throw e("unexpected HTTP response status code", err.cause, err.code);
|
|
2556
|
+
case RESPONSE_IS_NOT_JSON: throw e("unexpected response content-type", err.cause, err.code);
|
|
2557
|
+
case PARSE_ERROR: throw e("parsing error occured", err, err.code);
|
|
2558
|
+
case INVALID_RESPONSE: throw e("invalid response encountered", err, err.code);
|
|
2559
|
+
case JWT_CLAIM_COMPARISON: throw e("unexpected JWT claim value encountered", err, err.code);
|
|
2560
|
+
case JSON_ATTRIBUTE_COMPARISON: throw e("unexpected JSON attribute value encountered", err, err.code);
|
|
2561
|
+
case JWT_TIMESTAMP_CHECK: throw e("JWT timestamp claim value failed validation", err, err.code);
|
|
2562
|
+
default: throw e(err.message, err, err.code);
|
|
2563
|
+
}
|
|
2564
|
+
if (err instanceof UnsupportedOperationError) throw e("unsupported operation", err, err.code);
|
|
2565
|
+
if (err instanceof DOMException) switch (err.name) {
|
|
2566
|
+
case "OperationError": throw e("runtime operation error", err, UNSUPPORTED_OPERATION);
|
|
2567
|
+
case "NotSupportedError": throw e("runtime unsupported operation", err, UNSUPPORTED_OPERATION);
|
|
2568
|
+
case "TimeoutError": throw e("operation timed out", err, "OAUTH_TIMEOUT");
|
|
2569
|
+
case "AbortError": throw e("operation aborted", err, "OAUTH_ABORT");
|
|
2570
|
+
}
|
|
2571
|
+
throw new ClientError("something went wrong", { cause: err });
|
|
2572
|
+
}
|
|
2573
|
+
function handleEntraId(server, as, options) {
|
|
2574
|
+
if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
|
|
2575
|
+
as[kEntraId] = true;
|
|
2576
|
+
return true;
|
|
2577
|
+
}
|
|
2578
|
+
return false;
|
|
2579
|
+
}
|
|
2580
|
+
function handleB2Clogin(server, options) {
|
|
2581
|
+
if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) return true;
|
|
2582
|
+
return false;
|
|
2583
|
+
}
|
|
2584
|
+
async function discovery(server, clientId, metadata, clientAuthentication, options) {
|
|
2585
|
+
const instance = new Configuration(await performDiscovery(server, options), clientId, metadata, clientAuthentication);
|
|
2586
|
+
let internals = int(instance);
|
|
2587
|
+
if (options?.[customFetch]) internals.fetch = options[customFetch];
|
|
2588
|
+
if (options?.timeout) internals.timeout = options.timeout;
|
|
2589
|
+
if (options?.execute) for (const extension of options.execute) extension(instance);
|
|
2590
|
+
return instance;
|
|
2591
|
+
}
|
|
2592
|
+
async function performDiscovery(server, options) {
|
|
2593
|
+
if (!(server instanceof URL)) throw CodedTypeError("\"server\" must be an instance of URL", ERR_INVALID_ARG_TYPE);
|
|
2594
|
+
const resolve = !server.href.includes("/.well-known/");
|
|
2595
|
+
const timeout = options?.timeout ?? 30;
|
|
2596
|
+
const signal$2 = AbortSignal.timeout(timeout * 1e3);
|
|
2597
|
+
const as = await (resolve ? discoveryRequest(server, {
|
|
2598
|
+
algorithm: options?.algorithm,
|
|
2599
|
+
[customFetch$1]: options?.[customFetch],
|
|
2600
|
+
[allowInsecureRequests$1]: options?.execute?.includes(allowInsecureRequests),
|
|
2601
|
+
signal: signal$2,
|
|
2602
|
+
headers: new Headers(headers)
|
|
2603
|
+
}) : (options?.[customFetch] || fetch)((() => {
|
|
2604
|
+
checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);
|
|
2605
|
+
return server.href;
|
|
2606
|
+
})(), {
|
|
2607
|
+
headers: Object.fromEntries(new Headers({
|
|
2608
|
+
accept: "application/json",
|
|
2609
|
+
...headers
|
|
2610
|
+
}).entries()),
|
|
2611
|
+
body: void 0,
|
|
2612
|
+
method: "GET",
|
|
2613
|
+
redirect: "manual",
|
|
2614
|
+
signal: signal$2
|
|
2615
|
+
})).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
|
|
2616
|
+
if (resolve && new URL(as.issuer).href !== server.href) handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
|
|
2617
|
+
throw new ClientError("discovered metadata issuer does not match the expected issuer", {
|
|
2618
|
+
code: JSON_ATTRIBUTE_COMPARISON,
|
|
2619
|
+
cause: {
|
|
2620
|
+
expected: server.href,
|
|
2621
|
+
body: as,
|
|
2622
|
+
attribute: "issuer"
|
|
2623
|
+
}
|
|
2624
|
+
});
|
|
2625
|
+
})();
|
|
2626
|
+
return as;
|
|
2627
|
+
}
|
|
2628
|
+
function getServerHelpers(metadata) {
|
|
2629
|
+
return { supportsPKCE: {
|
|
2630
|
+
__proto__: null,
|
|
2631
|
+
value(method = "S256") {
|
|
2632
|
+
return metadata.code_challenge_methods_supported?.includes(method) === true;
|
|
2633
|
+
}
|
|
2634
|
+
} };
|
|
2635
|
+
}
|
|
2636
|
+
function addServerHelpers(metadata) {
|
|
2637
|
+
Object.defineProperties(metadata, getServerHelpers(metadata));
|
|
2638
|
+
}
|
|
2639
|
+
const kEntraId = Symbol();
|
|
2640
|
+
var Configuration = class {
|
|
2641
|
+
constructor(server, clientId, metadata, clientAuthentication) {
|
|
2642
|
+
if (typeof clientId !== "string" || !clientId.length) throw CodedTypeError("\"clientId\" must be a non-empty string", ERR_INVALID_ARG_TYPE);
|
|
2643
|
+
if (typeof metadata === "string") metadata = { client_secret: metadata };
|
|
2644
|
+
if (metadata?.client_id !== void 0 && clientId !== metadata.client_id) throw CodedTypeError("\"clientId\" and \"metadata.client_id\" must be the same", ERR_INVALID_ARG_VALUE);
|
|
2645
|
+
const client = {
|
|
2646
|
+
...structuredClone(metadata),
|
|
2647
|
+
client_id: clientId
|
|
2648
|
+
};
|
|
2649
|
+
client[clockSkew$1] = metadata?.[clockSkew$1] ?? 0;
|
|
2650
|
+
client[clockTolerance$1] = metadata?.[clockTolerance$1] ?? 30;
|
|
2651
|
+
let auth;
|
|
2652
|
+
if (clientAuthentication) auth = clientAuthentication;
|
|
2653
|
+
else if (typeof client.client_secret === "string" && client.client_secret.length) auth = ClientSecretPost(client.client_secret);
|
|
2654
|
+
else auth = None();
|
|
2655
|
+
let c = Object.freeze(client);
|
|
2656
|
+
const clone = structuredClone(server);
|
|
2657
|
+
if (kEntraId in server) clone[_expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace("{tenantid}", tid);
|
|
2658
|
+
let as = Object.freeze(clone);
|
|
2659
|
+
props ||= /* @__PURE__ */ new WeakMap();
|
|
2660
|
+
props.set(this, {
|
|
2661
|
+
__proto__: null,
|
|
2662
|
+
as,
|
|
2663
|
+
c,
|
|
2664
|
+
auth,
|
|
2665
|
+
tlsOnly: true,
|
|
2666
|
+
jwksCache: {}
|
|
2667
|
+
});
|
|
2668
|
+
}
|
|
2669
|
+
serverMetadata() {
|
|
2670
|
+
const metadata = structuredClone(int(this).as);
|
|
2671
|
+
addServerHelpers(metadata);
|
|
2672
|
+
return metadata;
|
|
2673
|
+
}
|
|
2674
|
+
clientMetadata() {
|
|
2675
|
+
return structuredClone(int(this).c);
|
|
2676
|
+
}
|
|
2677
|
+
get timeout() {
|
|
2678
|
+
return int(this).timeout;
|
|
2679
|
+
}
|
|
2680
|
+
set timeout(value) {
|
|
2681
|
+
int(this).timeout = value;
|
|
2682
|
+
}
|
|
2683
|
+
get [customFetch]() {
|
|
2684
|
+
return int(this).fetch;
|
|
2685
|
+
}
|
|
2686
|
+
set [customFetch](value) {
|
|
2687
|
+
int(this).fetch = value;
|
|
2688
|
+
}
|
|
2689
|
+
};
|
|
2690
|
+
Object.freeze(Configuration.prototype);
|
|
2691
|
+
function getHelpers(response) {
|
|
2692
|
+
let exp = void 0;
|
|
2693
|
+
if (response.expires_in !== void 0) {
|
|
2694
|
+
const now = /* @__PURE__ */ new Date();
|
|
2695
|
+
now.setSeconds(now.getSeconds() + response.expires_in);
|
|
2696
|
+
exp = now.getTime();
|
|
2697
|
+
}
|
|
2698
|
+
return {
|
|
2699
|
+
expiresIn: {
|
|
2700
|
+
__proto__: null,
|
|
2701
|
+
value() {
|
|
2702
|
+
if (exp) {
|
|
2703
|
+
const now = Date.now();
|
|
2704
|
+
if (exp > now) return Math.floor((exp - now) / 1e3);
|
|
2705
|
+
return 0;
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
},
|
|
2709
|
+
claims: {
|
|
2710
|
+
__proto__: null,
|
|
2711
|
+
value() {
|
|
2712
|
+
try {
|
|
2713
|
+
return getValidatedIdTokenClaims(this);
|
|
2714
|
+
} catch {
|
|
2715
|
+
return;
|
|
2716
|
+
}
|
|
2717
|
+
}
|
|
2718
|
+
}
|
|
2719
|
+
};
|
|
2720
|
+
}
|
|
2721
|
+
function addHelpers(response) {
|
|
2722
|
+
Object.defineProperties(response, getHelpers(response));
|
|
2723
|
+
}
|
|
2724
|
+
function allowInsecureRequests(config) {
|
|
2725
|
+
int(config).tlsOnly = false;
|
|
2726
|
+
}
|
|
2727
|
+
function stripParams(url) {
|
|
2728
|
+
url = new URL(url);
|
|
2729
|
+
url.search = "";
|
|
2730
|
+
url.hash = "";
|
|
2731
|
+
return url.href;
|
|
2732
|
+
}
|
|
2733
|
+
function webInstanceOf(input, toStringTag) {
|
|
2734
|
+
try {
|
|
2735
|
+
return Object.getPrototypeOf(input)[Symbol.toStringTag] === toStringTag;
|
|
2736
|
+
} catch {
|
|
2737
|
+
return false;
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
async function authorizationCodeGrant(config, currentUrl, checks, tokenEndpointParameters, options) {
|
|
2741
|
+
checkConfig(config);
|
|
2742
|
+
if (options?.flag !== retry && !(currentUrl instanceof URL) && !webInstanceOf(currentUrl, "Request")) throw CodedTypeError("\"currentUrl\" must be an instance of URL, or Request", ERR_INVALID_ARG_TYPE);
|
|
2743
|
+
let authResponse;
|
|
2744
|
+
let redirectUri;
|
|
2745
|
+
const { as, c, auth, fetch: fetch$1, tlsOnly, jarm, hybrid, nonRepudiation, timeout, decrypt, implicit } = int(config);
|
|
2746
|
+
if (options?.flag === retry) {
|
|
2747
|
+
authResponse = options.authResponse;
|
|
2748
|
+
redirectUri = options.redirectUri;
|
|
2749
|
+
} else {
|
|
2750
|
+
if (!(currentUrl instanceof URL)) {
|
|
2751
|
+
const request = currentUrl;
|
|
2752
|
+
currentUrl = new URL(currentUrl.url);
|
|
2753
|
+
switch (request.method) {
|
|
2754
|
+
case "GET": break;
|
|
2755
|
+
case "POST":
|
|
2756
|
+
const params = new URLSearchParams(await formPostResponse(request));
|
|
2757
|
+
if (hybrid) currentUrl.hash = params.toString();
|
|
2758
|
+
else for (const [k, v] of params.entries()) currentUrl.searchParams.append(k, v);
|
|
2759
|
+
break;
|
|
2760
|
+
default: throw CodedTypeError("unexpected Request HTTP method", ERR_INVALID_ARG_VALUE);
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
redirectUri = stripParams(currentUrl);
|
|
2764
|
+
switch (true) {
|
|
2765
|
+
case !!jarm:
|
|
2766
|
+
authResponse = await jarm(currentUrl, checks?.expectedState);
|
|
2767
|
+
break;
|
|
2768
|
+
case !!hybrid:
|
|
2769
|
+
authResponse = await hybrid(currentUrl, checks?.expectedNonce, checks?.expectedState, checks?.maxAge);
|
|
2770
|
+
break;
|
|
2771
|
+
case !!implicit: throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");
|
|
2772
|
+
default: try {
|
|
2773
|
+
authResponse = validateAuthResponse(as, c, currentUrl.searchParams, checks?.expectedState);
|
|
2774
|
+
} catch (err) {
|
|
2775
|
+
errorHandler(err);
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
const response = await authorizationCodeGrantRequest(as, c, auth, authResponse, redirectUri, checks?.pkceCodeVerifier || nopkce, {
|
|
2780
|
+
additionalParameters: tokenEndpointParameters,
|
|
2781
|
+
[customFetch$1]: fetch$1,
|
|
2782
|
+
[allowInsecureRequests$1]: !tlsOnly,
|
|
2783
|
+
DPoP: options?.DPoP,
|
|
2784
|
+
headers: new Headers(headers),
|
|
2785
|
+
signal: signal(timeout)
|
|
2786
|
+
}).catch(errorHandler);
|
|
2787
|
+
if (typeof checks?.expectedNonce === "string" || typeof checks?.maxAge === "number") checks.idTokenExpected = true;
|
|
2788
|
+
const p = processAuthorizationCodeResponse(as, c, response, {
|
|
2789
|
+
expectedNonce: checks?.expectedNonce,
|
|
2790
|
+
maxAge: checks?.maxAge,
|
|
2791
|
+
requireIdToken: checks?.idTokenExpected,
|
|
2792
|
+
[jweDecrypt]: decrypt
|
|
2793
|
+
});
|
|
2794
|
+
let result;
|
|
2795
|
+
try {
|
|
2796
|
+
result = await p;
|
|
2797
|
+
} catch (err) {
|
|
2798
|
+
if (retryable(err, options)) return authorizationCodeGrant(config, void 0, checks, tokenEndpointParameters, {
|
|
2799
|
+
...options,
|
|
2800
|
+
flag: retry,
|
|
2801
|
+
authResponse,
|
|
2802
|
+
redirectUri
|
|
2803
|
+
});
|
|
2804
|
+
errorHandler(err);
|
|
2805
|
+
}
|
|
2806
|
+
result.id_token && await nonRepudiation?.(response);
|
|
2807
|
+
addHelpers(result);
|
|
2808
|
+
return result;
|
|
2809
|
+
}
|
|
2810
|
+
async function refreshTokenGrant(config, refreshToken, parameters, options) {
|
|
2811
|
+
checkConfig(config);
|
|
2812
|
+
parameters = new URLSearchParams(parameters);
|
|
2813
|
+
const { as, c, auth, fetch: fetch$1, tlsOnly, nonRepudiation, timeout, decrypt } = int(config);
|
|
2814
|
+
const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
|
|
2815
|
+
[customFetch$1]: fetch$1,
|
|
2816
|
+
[allowInsecureRequests$1]: !tlsOnly,
|
|
2817
|
+
additionalParameters: parameters,
|
|
2818
|
+
DPoP: options?.DPoP,
|
|
2819
|
+
headers: new Headers(headers),
|
|
2820
|
+
signal: signal(timeout)
|
|
2821
|
+
}).catch(errorHandler);
|
|
2822
|
+
const p = processRefreshTokenResponse(as, c, response, { [jweDecrypt]: decrypt });
|
|
2823
|
+
let result;
|
|
2824
|
+
try {
|
|
2825
|
+
result = await p;
|
|
2826
|
+
} catch (err) {
|
|
2827
|
+
if (retryable(err, options)) return refreshTokenGrant(config, refreshToken, parameters, {
|
|
2828
|
+
...options,
|
|
2829
|
+
flag: retry
|
|
2830
|
+
});
|
|
2831
|
+
errorHandler(err);
|
|
2832
|
+
}
|
|
2833
|
+
result.id_token && await nonRepudiation?.(response);
|
|
2834
|
+
addHelpers(result);
|
|
2835
|
+
return result;
|
|
2836
|
+
}
|
|
2837
|
+
function buildAuthorizationUrl(config, parameters) {
|
|
2838
|
+
checkConfig(config);
|
|
2839
|
+
const { as, c, tlsOnly, hybrid, jarm, implicit } = int(config);
|
|
2840
|
+
const authorizationEndpoint = resolveEndpoint(as, "authorization_endpoint", false, tlsOnly);
|
|
2841
|
+
parameters = new URLSearchParams(parameters);
|
|
2842
|
+
if (!parameters.has("client_id")) parameters.set("client_id", c.client_id);
|
|
2843
|
+
if (!parameters.has("request_uri") && !parameters.has("request")) {
|
|
2844
|
+
if (!parameters.has("response_type")) parameters.set("response_type", hybrid ? "code id_token" : implicit ? "id_token" : "code");
|
|
2845
|
+
if (implicit && !parameters.has("nonce")) throw CodedTypeError("response_type=id_token clients must provide a nonce parameter in their authorization request parameters", ERR_INVALID_ARG_VALUE);
|
|
2846
|
+
if (jarm) parameters.set("response_mode", "jwt");
|
|
2847
|
+
}
|
|
2848
|
+
for (const [k, v] of parameters.entries()) authorizationEndpoint.searchParams.append(k, v);
|
|
2849
|
+
return authorizationEndpoint;
|
|
2850
|
+
}
|
|
2851
|
+
function buildEndSessionUrl(config, parameters) {
|
|
2852
|
+
checkConfig(config);
|
|
2853
|
+
const { as, c, tlsOnly } = int(config);
|
|
2854
|
+
const endSessionEndpoint = resolveEndpoint(as, "end_session_endpoint", false, tlsOnly);
|
|
2855
|
+
parameters = new URLSearchParams(parameters);
|
|
2856
|
+
if (!parameters.has("client_id")) parameters.set("client_id", c.client_id);
|
|
2857
|
+
for (const [k, v] of parameters.entries()) endSessionEndpoint.searchParams.append(k, v);
|
|
2858
|
+
return endSessionEndpoint;
|
|
2859
|
+
}
|
|
2860
|
+
function checkConfig(input) {
|
|
2861
|
+
if (!(input instanceof Configuration)) throw CodedTypeError("\"config\" must be an instance of Configuration", ERR_INVALID_ARG_TYPE);
|
|
2862
|
+
if (Object.getPrototypeOf(input) !== Configuration.prototype) throw CodedTypeError("subclassing Configuration is not allowed", ERR_INVALID_ARG_VALUE);
|
|
2863
|
+
}
|
|
2864
|
+
function signal(timeout) {
|
|
2865
|
+
return timeout ? AbortSignal.timeout(timeout * 1e3) : void 0;
|
|
2866
|
+
}
|
|
2867
|
+
function retryable(err, options) {
|
|
2868
|
+
if (options?.DPoP && options.flag !== retry) return isDPoPNonceError(err);
|
|
2869
|
+
return false;
|
|
2870
|
+
}
|
|
2871
|
+
const retry = Symbol();
|
|
2872
|
+
|
|
2873
|
+
//#endregion
|
|
2874
|
+
//#region src/auth/descriptors/$auth.ts
|
|
2875
|
+
/**
|
|
2876
|
+
* Creates an authentication provider descriptor for handling user login flows.
|
|
2877
|
+
*
|
|
2878
|
+
* Supports multiple authentication strategies: credentials (username/password), OAuth2,
|
|
2879
|
+
* and OIDC (OpenID Connect). Handles token management, user profile retrieval, and
|
|
2880
|
+
* integration with both external identity providers (Auth0, Keycloak) and internal realms.
|
|
2881
|
+
*
|
|
2882
|
+
* **Authentication Types**: Credentials, OAuth2 (Google, GitHub), OIDC, External providers
|
|
2883
|
+
*
|
|
2884
|
+
* @example
|
|
2885
|
+
* ```ts
|
|
2886
|
+
* class AuthProviders {
|
|
2887
|
+
* // Internal credentials-based auth
|
|
2888
|
+
* credentials = $auth({
|
|
2889
|
+
* realm: this.userRealm,
|
|
2890
|
+
* credentials: {
|
|
2891
|
+
* account: async ({ username, password }) => {
|
|
2892
|
+
* return await this.validateUser(username, password);
|
|
2893
|
+
* }
|
|
2894
|
+
* }
|
|
2895
|
+
* });
|
|
2896
|
+
*
|
|
2897
|
+
* // External OIDC provider
|
|
2898
|
+
* keycloak = $auth({
|
|
2899
|
+
* oidc: {
|
|
2900
|
+
* issuer: "https://auth.example.com",
|
|
2901
|
+
* clientId: "my-app",
|
|
2902
|
+
* clientSecret: "secret",
|
|
2903
|
+
* redirectUri: "/auth/callback"
|
|
2904
|
+
* }
|
|
2905
|
+
* });
|
|
2906
|
+
* }
|
|
2907
|
+
* ```
|
|
2908
|
+
*/
|
|
2909
|
+
const $auth = (options) => {
|
|
2910
|
+
return createDescriptor(AuthDescriptor, options);
|
|
2911
|
+
};
|
|
2912
|
+
var AuthDescriptor = class extends Descriptor {
|
|
2913
|
+
securityProvider = $inject(SecurityProvider);
|
|
2914
|
+
dateTimeProvider = $inject(DateTimeProvider);
|
|
2915
|
+
oauth;
|
|
2916
|
+
get name() {
|
|
2917
|
+
return this.options.name ?? this.config.propertyKey;
|
|
2918
|
+
}
|
|
2919
|
+
get jwks_uri() {
|
|
2920
|
+
const jwks = this.oauth?.serverMetadata().jwks_uri;
|
|
2921
|
+
if (!jwks) throw new AlephaError("No JWKS URI available for the auth provider");
|
|
2922
|
+
return jwks;
|
|
2923
|
+
}
|
|
2924
|
+
get scope() {
|
|
2925
|
+
if ("oauth" in this.options) return this.options.oauth.scope;
|
|
2926
|
+
if ("oidc" in this.options) return this.options.oidc.scope || "openid profile email";
|
|
2927
|
+
throw new AlephaError("No OAuth2 or OIDC configuration available for the auth provider");
|
|
2928
|
+
}
|
|
2929
|
+
get redirect_uri() {
|
|
2930
|
+
if ("oauth" in this.options) return this.options.oauth.redirectUri;
|
|
2931
|
+
if ("oidc" in this.options) return this.options.oidc.redirectUri;
|
|
2932
|
+
throw new AlephaError("No OAuth2 or OIDC configuration available for the auth provider");
|
|
2933
|
+
}
|
|
2934
|
+
/**
|
|
2935
|
+
* Refreshes the access token using the refresh token.
|
|
2936
|
+
* Can be used on oauth2, oidc or credentials auth providers.
|
|
2937
|
+
*/
|
|
2938
|
+
async refresh(refreshToken, accessToken) {
|
|
2939
|
+
if ("realm" in this.options) return this.options.realm.refreshToken(refreshToken, accessToken).then((it) => it.tokens).catch((error) => {
|
|
2940
|
+
throw new SecurityError("Failed to refresh access token using the refresh token (realm)", { cause: error });
|
|
2941
|
+
});
|
|
2942
|
+
else if (this.oauth) try {
|
|
2943
|
+
return {
|
|
2944
|
+
...await refreshTokenGrant(this.oauth, refreshToken),
|
|
2945
|
+
issued_at: this.dateTimeProvider.now().unix()
|
|
2946
|
+
};
|
|
2947
|
+
} catch (error) {
|
|
2948
|
+
throw new SecurityError("Failed to refresh access token using the refresh token (oauth2)", { cause: error });
|
|
2949
|
+
}
|
|
2950
|
+
throw new AlephaError("No realm or OAuth2 configuration available for refreshing the access token");
|
|
2951
|
+
}
|
|
2952
|
+
/**
|
|
2953
|
+
* Extracts user information from the access token.
|
|
2954
|
+
* This is used to create a user account from the access token.
|
|
2955
|
+
*/
|
|
2956
|
+
async user(tokens) {
|
|
2957
|
+
try {
|
|
2958
|
+
if ("oauth" in this.options) {
|
|
2959
|
+
const profile = await this.options.oauth.userinfo(tokens);
|
|
2960
|
+
if (this.options.oauth.account) return this.options.oauth.account({
|
|
2961
|
+
...tokens,
|
|
2962
|
+
user: profile
|
|
2963
|
+
});
|
|
2964
|
+
return this.securityProvider.createUserFromPayload(profile);
|
|
2965
|
+
}
|
|
2966
|
+
if ("oidc" in this.options) {
|
|
2967
|
+
const payload = this.getUserFromIdToken(tokens.id_token || "");
|
|
2968
|
+
if (this.options.oidc.account) return this.options.oidc.account({
|
|
2969
|
+
...tokens,
|
|
2970
|
+
user: payload
|
|
2971
|
+
});
|
|
2972
|
+
return this.securityProvider.createUserFromPayload(payload);
|
|
2973
|
+
}
|
|
2974
|
+
} catch (error) {
|
|
2975
|
+
throw new SecurityError("Failed to extract user from identity provider tokens", { cause: error });
|
|
2976
|
+
}
|
|
2977
|
+
throw new AlephaError("This authentication does not support user extraction from tokens");
|
|
2978
|
+
}
|
|
2979
|
+
getUserFromIdToken(idToken) {
|
|
2980
|
+
try {
|
|
2981
|
+
return JSON.parse(Buffer.from(idToken.split(".")[1], "base64").toString("utf8"));
|
|
2982
|
+
} catch (error) {
|
|
2983
|
+
throw new AlephaError("Failed to parse ID Token payload", { cause: error });
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
async prepare() {
|
|
2987
|
+
const addons = [];
|
|
2988
|
+
addons.push(allowInsecureRequests);
|
|
2989
|
+
if ("oidc" in this.options) {
|
|
2990
|
+
const { oidc } = this.options;
|
|
2991
|
+
this.oauth = await discovery(new URL(oidc.issuer), oidc.clientId, { client_secret: oidc.clientSecret }, void 0, { execute: addons });
|
|
2992
|
+
}
|
|
2993
|
+
if ("oauth" in this.options) {
|
|
2994
|
+
const { oauth } = this.options;
|
|
2995
|
+
this.oauth = new Configuration({
|
|
2996
|
+
authorization_endpoint: oauth.authorization,
|
|
2997
|
+
token_endpoint: oauth.token,
|
|
2998
|
+
issuer: oauth.authorization,
|
|
2999
|
+
jwks_uri: void 0,
|
|
3000
|
+
end_session_endpoint: void 0
|
|
3001
|
+
}, oauth.clientId, { client_secret: oauth.clientSecret });
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
};
|
|
3005
|
+
$auth[KIND] = AuthDescriptor;
|
|
3006
|
+
|
|
3007
|
+
//#endregion
|
|
3008
|
+
//#region src/auth/schemas/tokensSchema.ts
|
|
3009
|
+
const tokensSchema = t.object({
|
|
3010
|
+
provider: t.text(),
|
|
3011
|
+
access_token: t.text({ size: "rich" }),
|
|
3012
|
+
issued_at: t.number(),
|
|
3013
|
+
expires_in: t.optional(t.number()),
|
|
3014
|
+
refresh_token: t.optional(t.text({ size: "rich" })),
|
|
3015
|
+
refresh_token_expires_in: t.optional(t.number()),
|
|
3016
|
+
refresh_expires_in: t.optional(t.number({ description: "Alias of `refresh_token_expires_in` for compatibility with some providers." })),
|
|
3017
|
+
id_token: t.optional(t.text({ size: "rich" })),
|
|
3018
|
+
scope: t.optional(t.text())
|
|
3019
|
+
});
|
|
3020
|
+
|
|
3021
|
+
//#endregion
|
|
3022
|
+
//#region src/auth/schemas/tokenResponseSchema.ts
|
|
3023
|
+
const tokenResponseSchema = t.extend(tokensSchema, {
|
|
3024
|
+
user: userAccountInfoSchema,
|
|
3025
|
+
api: apiLinksResponseSchema
|
|
3026
|
+
});
|
|
3027
|
+
|
|
3028
|
+
//#endregion
|
|
3029
|
+
//#region src/auth/schemas/userinfoResponseSchema.ts
|
|
3030
|
+
const userinfoResponseSchema = t.object({
|
|
3031
|
+
user: t.optional(userAccountInfoSchema),
|
|
3032
|
+
api: apiLinksResponseSchema
|
|
3033
|
+
});
|
|
3034
|
+
|
|
3035
|
+
//#endregion
|
|
3036
|
+
//#region src/auth/services/ReactAuth.ts
|
|
3037
|
+
/**
|
|
3038
|
+
* Browser, SSR friendly, service to handle authentication.
|
|
3039
|
+
*/
|
|
3040
|
+
var ReactAuth = class ReactAuth {
|
|
3041
|
+
log = $logger();
|
|
3042
|
+
alepha = $inject(Alepha);
|
|
3043
|
+
httpClient = $inject(HttpClient);
|
|
3044
|
+
static path = {
|
|
3045
|
+
login: "/oauth/login",
|
|
3046
|
+
callback: "/oauth/callback",
|
|
3047
|
+
logout: "/oauth/logout",
|
|
3048
|
+
token: "/_auth/token",
|
|
3049
|
+
refresh: "/_auth/refresh",
|
|
3050
|
+
userinfo: "/_auth/userinfo"
|
|
3051
|
+
};
|
|
3052
|
+
onBeginTransition = $hook({
|
|
3053
|
+
on: "react:transition:begin",
|
|
3054
|
+
handler: async (event) => {
|
|
3055
|
+
if (this.alepha.isBrowser()) Object.defineProperty(event.state, "user", { get: () => this.user });
|
|
3056
|
+
}
|
|
3057
|
+
});
|
|
3058
|
+
onFetchRequest = $hook({
|
|
3059
|
+
on: "client:onRequest",
|
|
3060
|
+
handler: async ({ request }) => {
|
|
3061
|
+
if (this.alepha.isBrowser() && this.user) request.credentials ??= "include";
|
|
3062
|
+
}
|
|
3063
|
+
});
|
|
3064
|
+
/**
|
|
3065
|
+
* Get the current authenticated user.
|
|
3066
|
+
*
|
|
3067
|
+
* Alias for `alepha.state.get("user")`
|
|
3068
|
+
*/
|
|
3069
|
+
get user() {
|
|
3070
|
+
return this.alepha.state.get("alepha.server.request.user");
|
|
3071
|
+
}
|
|
3072
|
+
async ping() {
|
|
3073
|
+
const { data } = await this.httpClient.fetch(ReactAuth.path.userinfo, { schema: { response: userinfoResponseSchema } });
|
|
3074
|
+
this.alepha.state.set("alepha.server.request.apiLinks", data.api);
|
|
3075
|
+
this.alepha.state.set("alepha.server.request.user", data.user);
|
|
3076
|
+
return data.user;
|
|
3077
|
+
}
|
|
3078
|
+
async login(provider, options) {
|
|
3079
|
+
if (options.username || options.password) {
|
|
3080
|
+
const { data } = await this.httpClient.fetch(`${options.hostname || ""}${ReactAuth.path.token}?provider=${provider}`, {
|
|
3081
|
+
method: "POST",
|
|
3082
|
+
body: JSON.stringify({
|
|
3083
|
+
username: options.username,
|
|
3084
|
+
password: options.password,
|
|
3085
|
+
...options
|
|
3086
|
+
}),
|
|
3087
|
+
schema: { response: tokenResponseSchema }
|
|
3088
|
+
});
|
|
3089
|
+
this.alepha.state.set("alepha.server.request.apiLinks", data.api);
|
|
3090
|
+
this.alepha.state.set("alepha.server.request.user", data.user);
|
|
3091
|
+
return data;
|
|
3092
|
+
}
|
|
3093
|
+
if (this.alepha.isBrowser()) {
|
|
3094
|
+
const browser = this.alepha.inject(ReactBrowserProvider);
|
|
3095
|
+
const redirect = options.redirect || (browser.transitioning ? window.location.origin + browser.transitioning.to : window.location.href);
|
|
3096
|
+
const href = `${window.location.origin}${ReactAuth.path.login}?provider=${provider}&redirect_uri=${encodeURIComponent(redirect)}`;
|
|
3097
|
+
if (browser.transitioning) throw new Redirection(href);
|
|
3098
|
+
else {
|
|
3099
|
+
window.location.href = href;
|
|
3100
|
+
return {};
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
throw new Redirection(`${ReactAuth.path.login}?provider=${provider}&redirect_uri=${options.redirect || "/"}`);
|
|
3104
|
+
}
|
|
3105
|
+
logout() {
|
|
3106
|
+
window.location.href = `${ReactAuth.path.logout}?post_logout_redirect_uri=${encodeURIComponent(window.location.origin)}`;
|
|
3107
|
+
}
|
|
3108
|
+
};
|
|
3109
|
+
|
|
3110
|
+
//#endregion
|
|
3111
|
+
//#region src/auth/providers/ReactAuthProvider.ts
|
|
3112
|
+
var ReactAuthProvider = class {
|
|
3113
|
+
log = $logger();
|
|
3114
|
+
alepha = $inject(Alepha);
|
|
3115
|
+
serverCookiesProvider = $inject(ServerCookiesProvider);
|
|
3116
|
+
dateTimeProvider = $inject(DateTimeProvider);
|
|
3117
|
+
serverLinksProvider = $inject(ServerLinksProvider);
|
|
3118
|
+
reactAuth = $inject(ReactAuth);
|
|
3119
|
+
authorizationCode = $cookie({
|
|
3120
|
+
name: "authorizationCode",
|
|
3121
|
+
ttl: [15, "minutes"],
|
|
3122
|
+
httpOnly: true,
|
|
3123
|
+
schema: t.object({
|
|
3124
|
+
provider: t.text(),
|
|
3125
|
+
codeVerifier: t.optional(t.text({ size: "long" })),
|
|
3126
|
+
redirectUri: t.optional(t.text({ size: "long" })),
|
|
3127
|
+
state: t.optional(t.text()),
|
|
3128
|
+
nonce: t.optional(t.text())
|
|
3129
|
+
})
|
|
3130
|
+
});
|
|
3131
|
+
tokens = $cookie({
|
|
3132
|
+
name: "tokens",
|
|
3133
|
+
ttl: [30, "days"],
|
|
3134
|
+
httpOnly: true,
|
|
3135
|
+
compress: true,
|
|
3136
|
+
encrypt: true,
|
|
3137
|
+
schema: tokensSchema
|
|
3138
|
+
});
|
|
3139
|
+
onRender = $hook({
|
|
3140
|
+
on: "react:server:render:begin",
|
|
3141
|
+
handler: async ({ request, state }) => {
|
|
3142
|
+
if (request?.user) {
|
|
3143
|
+
const { token, realm, ...user } = request.user;
|
|
3144
|
+
this.alepha.state.set("alepha.server.request.user", user);
|
|
3145
|
+
state.user = user;
|
|
3146
|
+
}
|
|
3147
|
+
}
|
|
3148
|
+
});
|
|
3149
|
+
get identities() {
|
|
3150
|
+
return this.alepha.descriptors($auth).filter((auth) => !auth.options.disabled);
|
|
3151
|
+
}
|
|
3152
|
+
configure = $hook({
|
|
3153
|
+
on: "configure",
|
|
3154
|
+
handler: async () => {
|
|
3155
|
+
for (const identity of this.identities) await identity.prepare();
|
|
3156
|
+
}
|
|
3157
|
+
});
|
|
3158
|
+
getAccessTokens(tokens) {
|
|
3159
|
+
const idp = this.provider(tokens.provider);
|
|
3160
|
+
if ("oidc" in idp.options && !("realm" in idp.options) && idp.options.oidc?.useIdToken) return tokens.id_token;
|
|
3161
|
+
return tokens.access_token;
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* Fill request headers with access token from cookies or fallback to provider's fallback function.
|
|
3165
|
+
*/
|
|
3166
|
+
onRequest = $hook({
|
|
3167
|
+
on: "server:onRequest",
|
|
3168
|
+
after: this.serverCookiesProvider,
|
|
3169
|
+
handler: async ({ request }) => {
|
|
3170
|
+
const cookies = request.cookies;
|
|
3171
|
+
if (cookies) {
|
|
3172
|
+
const tokens = await this.cookiesToTokens(cookies);
|
|
3173
|
+
if (tokens) {
|
|
3174
|
+
request.headers.authorization = `Bearer ${this.getAccessTokens(tokens)}`;
|
|
3175
|
+
this.log.trace("Access token set in request headers", { provider: tokens.provider });
|
|
3176
|
+
}
|
|
3177
|
+
}
|
|
3178
|
+
if (!request.headers.authorization) {
|
|
3179
|
+
for (const provider of this.identities) if (!("realm" in provider.options) && !!provider.options.fallback) {
|
|
3180
|
+
const token = await provider.options.fallback();
|
|
3181
|
+
if (token) {
|
|
3182
|
+
request.headers.authorization = `Bearer ${token}`;
|
|
3183
|
+
break;
|
|
3184
|
+
}
|
|
3185
|
+
}
|
|
3186
|
+
}
|
|
3187
|
+
}
|
|
3188
|
+
});
|
|
3189
|
+
/**
|
|
3190
|
+
* Convert cookies to tokens.
|
|
3191
|
+
* If the tokens are expired, try to refresh them using the refresh token.
|
|
3192
|
+
*/
|
|
3193
|
+
async cookiesToTokens(cookies) {
|
|
3194
|
+
const tokens = this.tokens.get({ cookies });
|
|
3195
|
+
if (!tokens) {
|
|
3196
|
+
this.log.trace("No tokens found in cookies");
|
|
3197
|
+
return;
|
|
3198
|
+
}
|
|
3199
|
+
this.log.trace("Tokens found in cookies", {
|
|
3200
|
+
expires_in: tokens.expires_in,
|
|
3201
|
+
issued_at: tokens.issued_at
|
|
3202
|
+
});
|
|
3203
|
+
const refreshedTokens = await this.refreshTokens(tokens);
|
|
3204
|
+
if (!refreshedTokens) {
|
|
3205
|
+
this.tokens.del({ cookies });
|
|
3206
|
+
return;
|
|
3207
|
+
}
|
|
3208
|
+
if (refreshedTokens.access_token !== tokens.access_token) this.setTokens(refreshedTokens, cookies);
|
|
3209
|
+
return refreshedTokens;
|
|
3210
|
+
}
|
|
3211
|
+
async refreshTokens(tokens) {
|
|
3212
|
+
if (tokens.expires_in && tokens.issued_at) {
|
|
3213
|
+
if (tokens.issued_at + (tokens.expires_in - 10) < this.dateTimeProvider.now().unix()) {
|
|
3214
|
+
this.log.trace("Tokens are expired");
|
|
3215
|
+
if (tokens.refresh_token) {
|
|
3216
|
+
this.log.trace("Trying to refresh tokens using refresh token");
|
|
3217
|
+
try {
|
|
3218
|
+
const newTokens = {
|
|
3219
|
+
...await this.provider(tokens).refresh(tokens.refresh_token, tokens.access_token),
|
|
3220
|
+
provider: tokens.provider,
|
|
3221
|
+
issued_at: this.dateTimeProvider.now().unix()
|
|
3222
|
+
};
|
|
3223
|
+
this.log.debug("Tokens refreshed successfully");
|
|
3224
|
+
return newTokens;
|
|
3225
|
+
} catch (e$1) {
|
|
3226
|
+
this.log.warn("Failed to refresh token", e$1);
|
|
3227
|
+
}
|
|
3228
|
+
}
|
|
3229
|
+
return;
|
|
3230
|
+
}
|
|
3231
|
+
}
|
|
3232
|
+
if (!tokens.issued_at && tokens.access_token) return;
|
|
3233
|
+
return tokens;
|
|
3234
|
+
}
|
|
3235
|
+
/**
|
|
3236
|
+
* Get user information.
|
|
3237
|
+
*/
|
|
3238
|
+
userinfo = $route({
|
|
3239
|
+
path: ReactAuth.path.userinfo,
|
|
3240
|
+
schema: { response: userinfoResponseSchema },
|
|
3241
|
+
handler: async ({ user, headers: headers$1, cookies }) => {
|
|
3242
|
+
const tokens = this.tokens.get({ cookies });
|
|
3243
|
+
if (tokens) {
|
|
3244
|
+
const provider = this.provider(tokens);
|
|
3245
|
+
if (!("realm" in provider.options)) {
|
|
3246
|
+
const user$1 = await provider.user(tokens);
|
|
3247
|
+
return {
|
|
3248
|
+
api: await this.serverLinksProvider.getUserApiLinks({
|
|
3249
|
+
authorization: headers$1.authorization,
|
|
3250
|
+
user: user$1
|
|
3251
|
+
}),
|
|
3252
|
+
user: user$1
|
|
3253
|
+
};
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
return {
|
|
3257
|
+
api: await this.serverLinksProvider.getUserApiLinks({
|
|
3258
|
+
authorization: headers$1.authorization,
|
|
3259
|
+
user
|
|
3260
|
+
}),
|
|
3261
|
+
user
|
|
3262
|
+
};
|
|
3263
|
+
}
|
|
3264
|
+
});
|
|
3265
|
+
/**
|
|
3266
|
+
* Refresh a token for internal providers.
|
|
3267
|
+
*/
|
|
3268
|
+
refresh = $route({
|
|
3269
|
+
path: ReactAuth.path.refresh,
|
|
3270
|
+
method: "POST",
|
|
3271
|
+
schema: {
|
|
3272
|
+
query: t.object({ provider: t.text() }),
|
|
3273
|
+
body: t.object({
|
|
3274
|
+
refresh_token: t.text({ size: "rich" }),
|
|
3275
|
+
access_token: t.optional(t.text({
|
|
3276
|
+
size: "rich",
|
|
3277
|
+
description: "Required if provider has stateless refresh token on credentials mode"
|
|
3278
|
+
}))
|
|
3279
|
+
}),
|
|
3280
|
+
response: tokensSchema
|
|
3281
|
+
},
|
|
3282
|
+
handler: async ({ query, body, cookies }) => {
|
|
3283
|
+
const provider = this.provider(query);
|
|
3284
|
+
const tokens = {
|
|
3285
|
+
provider: query.provider,
|
|
3286
|
+
...await provider.refresh(body.refresh_token, body.access_token)
|
|
3287
|
+
};
|
|
3288
|
+
this.setTokens(tokens, cookies);
|
|
3289
|
+
return tokens;
|
|
3290
|
+
}
|
|
3291
|
+
});
|
|
3292
|
+
/**
|
|
3293
|
+
* Login for local password-based authentication.
|
|
3294
|
+
*/
|
|
3295
|
+
token = $route({
|
|
3296
|
+
path: ReactAuth.path.token,
|
|
3297
|
+
method: "POST",
|
|
3298
|
+
schema: {
|
|
3299
|
+
query: t.object({ provider: t.text() }),
|
|
3300
|
+
body: t.object({
|
|
3301
|
+
username: t.text(),
|
|
3302
|
+
password: t.text()
|
|
3303
|
+
}),
|
|
3304
|
+
response: tokenResponseSchema
|
|
3305
|
+
},
|
|
3306
|
+
handler: async ({ query, body, cookies }) => {
|
|
3307
|
+
const provider = this.provider(query);
|
|
3308
|
+
const realm = "realm" in provider.options && provider.options.realm;
|
|
3309
|
+
if (!realm) throw new SecurityError(`Auth provider '${query.provider}' does not support password grant`);
|
|
3310
|
+
const credentials = "credentials" in provider.options && provider.options.credentials;
|
|
3311
|
+
if (!credentials) throw new SecurityError(`Auth provider '${query.provider}' does not support password grant`);
|
|
3312
|
+
let user;
|
|
3313
|
+
try {
|
|
3314
|
+
user = await credentials.account(body);
|
|
3315
|
+
} catch (e$1) {
|
|
3316
|
+
throw new UnauthorizedError(`Failed to authenticate user`, { cause: e$1 });
|
|
3317
|
+
}
|
|
3318
|
+
const tokens = {
|
|
3319
|
+
provider: query.provider,
|
|
3320
|
+
...await realm.createToken(user)
|
|
3321
|
+
};
|
|
3322
|
+
this.setTokens(tokens, cookies);
|
|
3323
|
+
const api = await this.serverLinksProvider.getUserApiLinks({ user });
|
|
3324
|
+
return {
|
|
3325
|
+
...tokens,
|
|
3326
|
+
user,
|
|
3327
|
+
api
|
|
3328
|
+
};
|
|
3329
|
+
}
|
|
3330
|
+
});
|
|
3331
|
+
/**
|
|
3332
|
+
* Oauth2/OIDC login route.
|
|
3333
|
+
*/
|
|
3334
|
+
login = $route({
|
|
3335
|
+
path: ReactAuth.path.login,
|
|
3336
|
+
schema: { query: t.object({
|
|
3337
|
+
provider: t.text(),
|
|
3338
|
+
redirect_uri: t.optional(t.text({ size: "rich" }))
|
|
3339
|
+
}) },
|
|
3340
|
+
handler: async ({ query, url, reply }) => {
|
|
3341
|
+
const provider = this.provider(query);
|
|
3342
|
+
const oauth = provider.oauth;
|
|
3343
|
+
if (!oauth) throw new SecurityError(`Auth provider '${query.provider}' does not support OAuth2`);
|
|
3344
|
+
const scope = provider.scope;
|
|
3345
|
+
let redirect_uri = provider.redirect_uri || ReactAuth.path.callback;
|
|
3346
|
+
if (redirect_uri.startsWith("/")) redirect_uri = `${url.protocol}//${url.host}${redirect_uri}`;
|
|
3347
|
+
const oidc = "oidc" in provider.options && provider.options.oidc;
|
|
3348
|
+
if (!oauth.serverMetadata().supportsPKCE()) {
|
|
3349
|
+
const state = randomState();
|
|
3350
|
+
const parameters$1 = {
|
|
3351
|
+
redirect_uri,
|
|
3352
|
+
state
|
|
3353
|
+
};
|
|
3354
|
+
if (oidc) parameters$1.nonce = randomState();
|
|
3355
|
+
if (scope) parameters$1.scope = scope;
|
|
3356
|
+
this.authorizationCode.set({
|
|
3357
|
+
state,
|
|
3358
|
+
nonce: parameters$1.nonce,
|
|
3359
|
+
redirectUri: query.redirect_uri ?? "/",
|
|
3360
|
+
provider: query.provider
|
|
3361
|
+
});
|
|
3362
|
+
reply.redirect(buildAuthorizationUrl(oauth, parameters$1).toString());
|
|
3363
|
+
return;
|
|
3364
|
+
}
|
|
3365
|
+
const codeVerifier = randomPKCECodeVerifier();
|
|
3366
|
+
const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
|
|
3367
|
+
const parameters = {
|
|
3368
|
+
redirect_uri,
|
|
3369
|
+
code_challenge: codeChallenge,
|
|
3370
|
+
code_challenge_method: "S256"
|
|
3371
|
+
};
|
|
3372
|
+
if (scope) parameters.scope = scope;
|
|
3373
|
+
this.authorizationCode.set({
|
|
3374
|
+
codeVerifier,
|
|
3375
|
+
redirectUri: query.redirect_uri ?? "/",
|
|
3376
|
+
provider: query.provider
|
|
3377
|
+
});
|
|
3378
|
+
reply.redirect(buildAuthorizationUrl(oauth, parameters).toString());
|
|
3379
|
+
}
|
|
3380
|
+
});
|
|
3381
|
+
/**
|
|
3382
|
+
* Callback for OAuth2/OIDC providers.
|
|
3383
|
+
* It handles the authorization code flow and retrieves the access token.
|
|
3384
|
+
*/
|
|
3385
|
+
callback = $route({
|
|
3386
|
+
path: ReactAuth.path.callback,
|
|
3387
|
+
handler: async ({ url, reply, cookies }) => {
|
|
3388
|
+
const authorizationCode = this.authorizationCode.get({ cookies });
|
|
3389
|
+
if (!authorizationCode) throw new BadRequestError("Missing code verifier");
|
|
3390
|
+
const provider = this.provider(authorizationCode);
|
|
3391
|
+
const oauth = provider.oauth;
|
|
3392
|
+
if (!oauth) throw new SecurityError(`Auth provider '${provider.name}' does not support OAuth2`);
|
|
3393
|
+
const redirectUri = authorizationCode.redirectUri ?? "/";
|
|
3394
|
+
const externalTokens = await authorizationCodeGrant(oauth, url, {
|
|
3395
|
+
pkceCodeVerifier: authorizationCode.codeVerifier,
|
|
3396
|
+
expectedState: authorizationCode.state,
|
|
3397
|
+
expectedNonce: authorizationCode.nonce
|
|
3398
|
+
}).then((tokens$1) => ({
|
|
3399
|
+
issued_at: this.dateTimeProvider.now().unix(),
|
|
3400
|
+
provider: provider.name,
|
|
3401
|
+
...tokens$1
|
|
3402
|
+
})).catch((e$1) => {
|
|
3403
|
+
this.log.error("Failed to get access token", e$1);
|
|
3404
|
+
throw new SecurityError("Failed to get access token", { cause: e$1 });
|
|
3405
|
+
});
|
|
3406
|
+
this.authorizationCode.del({ cookies });
|
|
3407
|
+
const realm = "realm" in provider.options && provider.options.realm;
|
|
3408
|
+
if (!realm) {
|
|
3409
|
+
this.setTokens(externalTokens, cookies);
|
|
3410
|
+
reply.redirect(redirectUri);
|
|
3411
|
+
return;
|
|
3412
|
+
}
|
|
3413
|
+
const user = await provider.user(externalTokens);
|
|
3414
|
+
const tokens = await realm.createToken(user);
|
|
3415
|
+
this.setTokens({
|
|
3416
|
+
...tokens,
|
|
3417
|
+
issued_at: this.dateTimeProvider.now().unix(),
|
|
3418
|
+
provider: provider.name
|
|
3419
|
+
}, cookies);
|
|
3420
|
+
reply.redirect(redirectUri);
|
|
3421
|
+
}
|
|
3422
|
+
});
|
|
3423
|
+
/**
|
|
3424
|
+
* Logout route for OAuth2/OIDC providers.
|
|
3425
|
+
*/
|
|
3426
|
+
logout = $route({
|
|
3427
|
+
path: ReactAuth.path.logout,
|
|
3428
|
+
method: "GET",
|
|
3429
|
+
schema: { query: t.object({ post_logout_redirect_uri: t.optional(t.text()) }) },
|
|
3430
|
+
handler: async ({ query, reply, cookies }) => {
|
|
3431
|
+
const redirect = query.post_logout_redirect_uri ?? "/";
|
|
3432
|
+
const tokens = this.tokens.get({ cookies });
|
|
3433
|
+
if (!tokens) {
|
|
3434
|
+
reply.redirect(redirect);
|
|
3435
|
+
return;
|
|
3436
|
+
}
|
|
3437
|
+
const provider = this.provider(tokens.provider);
|
|
3438
|
+
this.tokens.del({ cookies });
|
|
3439
|
+
if ("realm" in provider.options && tokens.refresh_token) {
|
|
3440
|
+
const onDeleteSession = provider.options.realm.options.settings?.onDeleteSession;
|
|
3441
|
+
if (onDeleteSession) try {
|
|
3442
|
+
await onDeleteSession(tokens.refresh_token);
|
|
3443
|
+
} catch (e$1) {
|
|
3444
|
+
this.log.error("Failed to delete session", e$1);
|
|
3445
|
+
}
|
|
3446
|
+
}
|
|
3447
|
+
const oauth = provider.oauth;
|
|
3448
|
+
if (!oauth) {
|
|
3449
|
+
reply.redirect(redirect);
|
|
3450
|
+
return;
|
|
3451
|
+
}
|
|
3452
|
+
const params = new URLSearchParams();
|
|
3453
|
+
const idToken = tokens?.id_token;
|
|
3454
|
+
params.set("post_logout_redirect_uri", redirect);
|
|
3455
|
+
if (idToken) params.set("id_token_hint", idToken);
|
|
3456
|
+
const customLogoutUri = "oidc" in provider.options ? provider.options.oidc?.logoutUri : void 0;
|
|
3457
|
+
if (customLogoutUri) {
|
|
3458
|
+
reply.redirect(`${customLogoutUri}?${params}`);
|
|
3459
|
+
return;
|
|
3460
|
+
}
|
|
3461
|
+
if (!oauth.serverMetadata().end_session_endpoint) {
|
|
3462
|
+
reply.redirect(redirect);
|
|
3463
|
+
return;
|
|
3464
|
+
}
|
|
3465
|
+
reply.redirect(buildEndSessionUrl(oauth, params).toString());
|
|
3466
|
+
}
|
|
3467
|
+
});
|
|
3468
|
+
provider(opts) {
|
|
3469
|
+
const name = typeof opts === "string" ? opts : opts.provider;
|
|
3470
|
+
const identity = this.identities.find((identity$1) => identity$1.name === name);
|
|
3471
|
+
if (!identity) throw new SecurityError(`Auth provider '${name}' not found`);
|
|
3472
|
+
return identity;
|
|
3473
|
+
}
|
|
3474
|
+
setTokens(tokens, cookies) {
|
|
3475
|
+
const exp = tokens.refresh_token_expires_in || tokens.refresh_expires_in || tokens.expires_in;
|
|
3476
|
+
const ttl = exp ? this.dateTimeProvider.duration(exp, "seconds") : void 0;
|
|
3477
|
+
this.tokens.set(tokens, {
|
|
3478
|
+
cookies,
|
|
3479
|
+
ttl
|
|
3480
|
+
});
|
|
3481
|
+
}
|
|
3482
|
+
};
|
|
3483
|
+
|
|
3484
|
+
//#endregion
|
|
3485
|
+
//#region src/auth/descriptors/$authGithub.ts
|
|
3486
|
+
/**
|
|
3487
|
+
* Already configured GitHub authentication descriptor.
|
|
3488
|
+
*
|
|
3489
|
+
* Uses OAuth2 to authenticate users via their GitHub accounts.
|
|
3490
|
+
* Upon successful authentication, it links the GitHub account to a user session.
|
|
3491
|
+
*
|
|
3492
|
+
* Environment Variables:
|
|
3493
|
+
* - `GITHUB_CLIENT_ID`: The client ID obtained from the GitHub Developer Settings.
|
|
3494
|
+
* - `GITHUB_CLIENT_SECRET`: The client secret obtained from the GitHub Developer Settings.
|
|
3495
|
+
*/
|
|
3496
|
+
const $authGithub = (realm, options) => {
|
|
3497
|
+
const { alepha } = $context();
|
|
3498
|
+
const env = alepha.parseEnv(t.object({
|
|
3499
|
+
GITHUB_CLIENT_ID: t.string(),
|
|
3500
|
+
GITHUB_CLIENT_SECRET: t.string()
|
|
3501
|
+
}));
|
|
3502
|
+
return $auth({
|
|
3503
|
+
realm,
|
|
3504
|
+
name: "github",
|
|
3505
|
+
oauth: {
|
|
3506
|
+
clientId: env.GITHUB_CLIENT_ID,
|
|
3507
|
+
clientSecret: env.GITHUB_CLIENT_SECRET,
|
|
3508
|
+
authorization: "https://github.com/login/oauth/authorize",
|
|
3509
|
+
token: "https://github.com/login/oauth/access_token",
|
|
3510
|
+
scope: "read:user user:email",
|
|
3511
|
+
userinfo: async (tokens) => {
|
|
3512
|
+
const BASE_URL = "https://api.github.com";
|
|
3513
|
+
const res = await fetch(`${BASE_URL}/user`, { headers: {
|
|
3514
|
+
Authorization: `Bearer ${tokens.access_token}`,
|
|
3515
|
+
"User-Agent": "Alepha"
|
|
3516
|
+
} }).then((res$1) => res$1.json());
|
|
3517
|
+
const user = { sub: res.id.toString() };
|
|
3518
|
+
if (res.email) user.email = res.email;
|
|
3519
|
+
if (res.name) user.name = res.name.trim();
|
|
3520
|
+
if (res.avatar_url) user.picture = res.avatar_url;
|
|
3521
|
+
if (!user.email) {
|
|
3522
|
+
const res$1 = await fetch(`${BASE_URL}/user/emails`, { headers: {
|
|
3523
|
+
Authorization: `Bearer ${tokens.access_token}`,
|
|
3524
|
+
"User-Agent": "Alepha"
|
|
3525
|
+
} });
|
|
3526
|
+
if (res$1.ok) {
|
|
3527
|
+
const emails = await res$1.json();
|
|
3528
|
+
user.email = (emails.find((e$1) => e$1.primary) ?? emails[0]).email;
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
return user;
|
|
3532
|
+
},
|
|
3533
|
+
...options
|
|
3534
|
+
}
|
|
3535
|
+
});
|
|
3536
|
+
};
|
|
3537
|
+
|
|
3538
|
+
//#endregion
|
|
3539
|
+
//#region src/auth/descriptors/$authGoogle.ts
|
|
3540
|
+
/**
|
|
3541
|
+
* Already configured Google authentication descriptor.
|
|
3542
|
+
*
|
|
3543
|
+
* Uses OpenID Connect (OIDC) to authenticate users via their Google accounts.
|
|
3544
|
+
* Upon successful authentication, it links the Google account to a user session.
|
|
3545
|
+
*
|
|
3546
|
+
* Environment Variables:
|
|
3547
|
+
* - `GOOGLE_CLIENT_ID`: The client ID obtained from the Google Developer Console.
|
|
3548
|
+
* - `GOOGLE_CLIENT_SECRET`: The client secret obtained from the Google Developer Console.
|
|
3549
|
+
*/
|
|
3550
|
+
const $authGoogle = (realm, options) => {
|
|
3551
|
+
const { alepha } = $context();
|
|
3552
|
+
const env = alepha.parseEnv(t.object({
|
|
3553
|
+
GOOGLE_CLIENT_ID: t.string(),
|
|
3554
|
+
GOOGLE_CLIENT_SECRET: t.string()
|
|
3555
|
+
}));
|
|
3556
|
+
return $auth({
|
|
3557
|
+
realm,
|
|
3558
|
+
name: "google",
|
|
3559
|
+
oidc: {
|
|
3560
|
+
issuer: "https://accounts.google.com",
|
|
3561
|
+
clientId: env.GOOGLE_CLIENT_ID,
|
|
3562
|
+
clientSecret: env.GOOGLE_CLIENT_SECRET,
|
|
3563
|
+
...options
|
|
3564
|
+
}
|
|
3565
|
+
});
|
|
3566
|
+
};
|
|
3567
|
+
|
|
3568
|
+
//#endregion
|
|
3569
|
+
//#region src/auth/errors/SessionExpiredError.ts
|
|
3570
|
+
var SessionExpiredError = class extends AlephaError {
|
|
3571
|
+
name = "SessionExpiredError";
|
|
3572
|
+
status = 401;
|
|
3573
|
+
};
|
|
3574
|
+
|
|
3575
|
+
//#endregion
|
|
3576
|
+
//#region src/auth/hooks/useAuth.ts
|
|
3577
|
+
const useAuth = () => {
|
|
3578
|
+
const alepha = useAlepha();
|
|
3579
|
+
const [user] = useStore("alepha.server.request.user");
|
|
3580
|
+
return {
|
|
3581
|
+
user,
|
|
3582
|
+
logout: () => {
|
|
3583
|
+
alepha.inject(ReactAuth).logout();
|
|
3584
|
+
},
|
|
3585
|
+
login: async (provider, options = {}) => {
|
|
3586
|
+
await alepha.inject(ReactAuth).login(provider, options);
|
|
3587
|
+
},
|
|
3588
|
+
can: (name) => {
|
|
3589
|
+
return alepha.inject(LinkProvider).can(name);
|
|
3590
|
+
}
|
|
3591
|
+
};
|
|
3592
|
+
};
|
|
3593
|
+
|
|
3594
|
+
//#endregion
|
|
3595
|
+
//#region src/auth/index.ts
|
|
3596
|
+
/**
|
|
3597
|
+
* The ReactAuthModule provides authentication services for React applications.
|
|
3598
|
+
*
|
|
3599
|
+
* @see {@link ReactAuthProvider}
|
|
3600
|
+
* @module alepha.react.auth
|
|
3601
|
+
*/
|
|
3602
|
+
const AlephaReactAuth = $module({
|
|
3603
|
+
name: "alepha.react.auth",
|
|
3604
|
+
descriptors: [$auth],
|
|
3605
|
+
services: [
|
|
3606
|
+
AlephaReact,
|
|
3607
|
+
AlephaServerCookies,
|
|
3608
|
+
ReactAuthProvider,
|
|
3609
|
+
ReactAuth
|
|
3610
|
+
]
|
|
3611
|
+
});
|
|
3612
|
+
|
|
3613
|
+
//#endregion
|
|
3614
|
+
export { $auth, $authGithub, $authGoogle, AlephaReactAuth, AuthDescriptor, ReactAuth, ReactAuthProvider, SessionExpiredError, useAuth };
|
|
3615
|
+
//# sourceMappingURL=index.js.map
|