@alepha/react 0.5.0 → 0.5.2

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/dist/index.js ADDED
@@ -0,0 +1,476 @@
1
+ import { t, $logger, $inject, Alepha, $hook, autoInject } from '@alepha/core';
2
+ import { ServerProvider, $route, BadRequestError, ServerModule, ServerLinksProvider } from '@alepha/server';
3
+ import { R as Router, $ as $page, P as PageDescriptorProvider } from './useRouterState-CvFCmaq7.js';
4
+ export { N as NestedView, k as ReactBrowserProvider, j as RedirectException, a as RouterContext, f as RouterHookApi, b as RouterLayerContext, p as pageDescriptorKey, u as useActive, c as useClient, d as useInject, e as useQueryParams, g as useRouter, h as useRouterEvents, i as useRouterState } from './useRouterState-CvFCmaq7.js';
5
+ import { existsSync } from 'node:fs';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { join } from 'node:path';
8
+ import { renderToString } from 'react-dom/server';
9
+ import crypto from 'node:crypto';
10
+ import { $cache } from '@alepha/cache';
11
+ import { SecurityProvider } from '@alepha/security';
12
+ import { discovery, allowInsecureRequests, refreshTokenGrant, randomPKCECodeVerifier, calculatePKCECodeChallenge, buildAuthorizationUrl, authorizationCodeGrant, buildEndSessionUrl } from 'openid-client';
13
+ import 'react';
14
+ import 'react-dom/client';
15
+ import 'path-to-regexp';
16
+
17
+ const envSchema$1 = t.object({
18
+ REACT_SERVER_DIST: t.string({ default: "client" }),
19
+ REACT_SERVER_PREFIX: t.string({ default: "" }),
20
+ REACT_SSR_ENABLED: t.boolean({ default: false }),
21
+ REACT_SSR_OUTLET: t.string({ default: "<!--ssr-outlet-->" })
22
+ });
23
+ class ReactServerProvider {
24
+ log = $logger();
25
+ alepha = $inject(Alepha);
26
+ router = $inject(Router);
27
+ server = $inject(ServerProvider);
28
+ env = $inject(envSchema$1);
29
+ configure = $hook({
30
+ name: "configure",
31
+ handler: async () => {
32
+ await this.configureRoutes();
33
+ }
34
+ });
35
+ async configureRoutes() {
36
+ if (this.alepha.isTest()) {
37
+ this.processDescriptors();
38
+ }
39
+ if (this.router.empty()) {
40
+ return;
41
+ }
42
+ if (process.env.VITE_ALEPHA_DEV === "true") {
43
+ this.log.info("SSR starting in development mode");
44
+ const templateUrl = `${this.server.hostname}/index.html`;
45
+ this.log.debug(`Fetch template from ${templateUrl}`);
46
+ const route2 = this.createHandler(
47
+ () => fetch(templateUrl).then((it) => it.text()).catch(() => void 0)
48
+ );
49
+ await this.server.route(route2);
50
+ await this.server.route({
51
+ url: "*",
52
+ handler: route2.handler
53
+ });
54
+ return;
55
+ }
56
+ const maybe = [
57
+ join(process.cwd(), this.env.REACT_SERVER_DIST),
58
+ join(process.cwd(), "..", this.env.REACT_SERVER_DIST),
59
+ join(process.cwd(), "dist", this.env.REACT_SERVER_DIST)
60
+ ];
61
+ let root = "";
62
+ for (const it of maybe) {
63
+ if (existsSync(it)) {
64
+ root = it;
65
+ break;
66
+ }
67
+ }
68
+ if (!root) {
69
+ this.log.warn("Missing static files, SSR will be disabled");
70
+ return;
71
+ }
72
+ await this.server.serve(this.createStaticHandler(root));
73
+ const template = await readFile(join(root, "index.html"), "utf-8");
74
+ const route = this.createHandler(async () => template);
75
+ await this.server.route(route);
76
+ await this.server.route({
77
+ url: "/*",
78
+ // alias for "not found handler"
79
+ handler: route.handler
80
+ });
81
+ }
82
+ /**
83
+ *
84
+ * @param root
85
+ * @protected
86
+ */
87
+ createStaticHandler(root) {
88
+ return {
89
+ root,
90
+ prefix: this.env.REACT_SERVER_PREFIX,
91
+ logLevel: "warn",
92
+ cacheControl: true,
93
+ immutable: true,
94
+ preCompressed: true,
95
+ maxAge: "30d",
96
+ index: false
97
+ };
98
+ }
99
+ /**
100
+ *
101
+ * @param templateLoader
102
+ * @protected
103
+ */
104
+ createHandler(templateLoader) {
105
+ return {
106
+ url: "/",
107
+ handler: async ({ url, user }) => {
108
+ const template = await templateLoader();
109
+ if (!template) {
110
+ return new Response("Not found", { status: 404 });
111
+ }
112
+ const response = this.notFoundHandler(url);
113
+ if (response) {
114
+ return response;
115
+ }
116
+ return await this.ssr(url, template, user);
117
+ }
118
+ };
119
+ }
120
+ processDescriptors() {
121
+ const pages = this.alepha.getDescriptorValues($page);
122
+ for (const { key, instance, value } of pages) {
123
+ instance[key].render = async (options = {}) => {
124
+ const name = value.options.name ?? key;
125
+ const page = this.router.page(name);
126
+ const layers = await this.router.createLayers(
127
+ "",
128
+ page,
129
+ options.params ?? {},
130
+ options.query ?? {},
131
+ []
132
+ );
133
+ return renderToString(
134
+ this.router.root({
135
+ layers,
136
+ pathname: "",
137
+ search: ""
138
+ })
139
+ );
140
+ };
141
+ }
142
+ }
143
+ /**
144
+ *
145
+ * @param url
146
+ * @protected
147
+ */
148
+ notFoundHandler(url) {
149
+ if (url.match(/\.\w+$/)) {
150
+ return new Response("Not found", { status: 404 });
151
+ }
152
+ }
153
+ /**
154
+ *
155
+ * @param url
156
+ * @param template
157
+ * @param user
158
+ */
159
+ async ssr(url, template = this.env.REACT_SSR_OUTLET, user) {
160
+ const { element, layers, redirect } = await this.router.render(url, {
161
+ user
162
+ });
163
+ if (redirect) {
164
+ return new Response("", {
165
+ status: 302,
166
+ headers: {
167
+ Location: redirect
168
+ }
169
+ });
170
+ }
171
+ const appHtml = renderToString(element);
172
+ const script = `<script>window.__ssr=${JSON.stringify({
173
+ layers: layers.map((it) => ({
174
+ ...it,
175
+ index: void 0,
176
+ path: void 0,
177
+ element: void 0
178
+ })),
179
+ session: {
180
+ user: user ? {
181
+ id: user.id,
182
+ name: user.name
183
+ } : void 0
184
+ }
185
+ })}<\/script>`;
186
+ const index = template.indexOf("</body>");
187
+ if (index !== -1) {
188
+ template = template.slice(0, index) + script + template.slice(index);
189
+ }
190
+ return new Response(template.replace(this.env.REACT_SSR_OUTLET, appHtml), {
191
+ headers: { "Content-Type": "text/html" }
192
+ });
193
+ }
194
+ }
195
+
196
+ const sessionUserSchema = t.object({
197
+ id: t.string(),
198
+ name: t.optional(t.string())
199
+ });
200
+ const sessionSchema = t.object({
201
+ user: t.optional(sessionUserSchema)
202
+ });
203
+ const envSchema = t.object({
204
+ REACT_OIDC_ISSUER: t.optional(t.string()),
205
+ REACT_OIDC_CLIENT_ID: t.optional(t.string()),
206
+ REACT_OIDC_CLIENT_SECRET: t.optional(t.string()),
207
+ REACT_OIDC_REDIRECT_URI: t.optional(t.string())
208
+ });
209
+ class ReactSessionProvider {
210
+ SSID = "ssid";
211
+ log = $logger();
212
+ env = $inject(envSchema);
213
+ serverProvider = $inject(ServerProvider);
214
+ securityProvider = $inject(SecurityProvider);
215
+ sessions = $cache();
216
+ clients = [];
217
+ get redirectUri() {
218
+ return this.env.REACT_OIDC_REDIRECT_URI ?? `${this.serverProvider.hostname}/api/callback`;
219
+ }
220
+ configure = $hook({
221
+ name: "configure",
222
+ priority: 100,
223
+ handler: async () => {
224
+ const issuer = this.env.REACT_OIDC_ISSUER;
225
+ const clientId = this.env.REACT_OIDC_CLIENT_ID;
226
+ if (!issuer || !clientId) {
227
+ return;
228
+ }
229
+ const client = await discovery(
230
+ new URL(issuer),
231
+ clientId,
232
+ {
233
+ client_secret: this.env.REACT_OIDC_CLIENT_SECRET
234
+ },
235
+ void 0,
236
+ {
237
+ execute: [allowInsecureRequests]
238
+ }
239
+ );
240
+ this.clients = [client];
241
+ }
242
+ });
243
+ /**
244
+ *
245
+ * @param sessionId
246
+ * @param session
247
+ * @protected
248
+ */
249
+ async setSession(sessionId, session) {
250
+ await this.sessions.set(sessionId, session, {
251
+ days: 1
252
+ });
253
+ }
254
+ /**
255
+ *
256
+ * @param sessionId
257
+ * @protected
258
+ */
259
+ async getSession(sessionId) {
260
+ const session = await this.sessions.get(sessionId);
261
+ if (!session) {
262
+ return;
263
+ }
264
+ const now = Date.now();
265
+ if (session.expires_in && session.issued_at) {
266
+ const expiresAt = session.issued_at + (session.expires_in - 10) * 1e3;
267
+ if (expiresAt < now) {
268
+ if (session.refresh_token) {
269
+ try {
270
+ const newTokens = await refreshTokenGrant(
271
+ this.clients[0],
272
+ session.refresh_token
273
+ );
274
+ await this.setSession(sessionId, {
275
+ ...newTokens,
276
+ issued_at: Date.now()
277
+ });
278
+ return newTokens;
279
+ } catch (e) {
280
+ this.log.error(e, "Failed to refresh token");
281
+ }
282
+ }
283
+ await this.sessions.invalidate(sessionId);
284
+ return;
285
+ }
286
+ }
287
+ if (!session.issued_at && session.access_token) {
288
+ await this.sessions.invalidate(sessionId);
289
+ return;
290
+ }
291
+ return session;
292
+ }
293
+ /**
294
+ *
295
+ * @protected
296
+ */
297
+ beforeRequest = $hook({
298
+ name: "configure:fastify",
299
+ priority: 100,
300
+ handler: async (app) => {
301
+ app.decorateRequest("session");
302
+ app.addHook("onRequest", async (req) => {
303
+ const sessionId = req.cookies[this.SSID];
304
+ if (sessionId && !isViteFile(req.url)) {
305
+ const session = await this.getSession(sessionId);
306
+ if (session) {
307
+ req.session = session;
308
+ if (session.access_token) {
309
+ req.headers.authorization = `Bearer ${session.access_token}`;
310
+ }
311
+ }
312
+ }
313
+ });
314
+ }
315
+ });
316
+ /**
317
+ *
318
+ */
319
+ login = $route({
320
+ security: false,
321
+ url: "/login",
322
+ method: "GET",
323
+ schema: {
324
+ query: t.object({
325
+ redirect: t.optional(t.string())
326
+ })
327
+ },
328
+ handler: async ({ query }) => {
329
+ const client = this.clients[0];
330
+ const codeVerifier = randomPKCECodeVerifier();
331
+ const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
332
+ const scope = "openid profile email";
333
+ const parameters = {
334
+ redirect_uri: this.redirectUri,
335
+ scope,
336
+ code_challenge: codeChallenge,
337
+ code_challenge_method: "S256"
338
+ };
339
+ const sessionId = crypto.randomUUID();
340
+ await this.setSession(sessionId, {
341
+ authorizationCodeGrant: {
342
+ codeVerifier,
343
+ redirectUri: query.redirect ?? "/"
344
+ // TODO: add nonce, max_age, state
345
+ }
346
+ });
347
+ return new Response("", {
348
+ status: 302,
349
+ headers: {
350
+ "Set-Cookie": `${this.SSID}=${sessionId}; HttpOnly; Path=/; SameSite=Lax;`,
351
+ Location: buildAuthorizationUrl(client, parameters).toString()
352
+ }
353
+ });
354
+ }
355
+ });
356
+ /**
357
+ *
358
+ */
359
+ callback = $route({
360
+ security: false,
361
+ url: "/callback",
362
+ method: "GET",
363
+ schema: {
364
+ headers: t.record(t.string(), t.string()),
365
+ cookies: t.object({
366
+ ssid: t.string()
367
+ })
368
+ },
369
+ handler: async ({ cookies, url }) => {
370
+ const sessionId = cookies.ssid;
371
+ const session = await this.getSession(sessionId);
372
+ if (!session) {
373
+ throw new BadRequestError("Missing session");
374
+ }
375
+ if (!session.authorizationCodeGrant) {
376
+ throw new BadRequestError("Invalid session - missing code verifier");
377
+ }
378
+ const [, search] = url.split("?");
379
+ const tokens = await authorizationCodeGrant(
380
+ this.clients[0],
381
+ new URL(`${this.redirectUri}?${search}`),
382
+ {
383
+ pkceCodeVerifier: session.authorizationCodeGrant.codeVerifier,
384
+ expectedNonce: session.authorizationCodeGrant.nonce,
385
+ expectedState: session.authorizationCodeGrant.state,
386
+ maxAge: session.authorizationCodeGrant.max_age
387
+ }
388
+ );
389
+ await this.setSession(sessionId, {
390
+ ...tokens,
391
+ issued_at: Date.now()
392
+ });
393
+ return new Response("", {
394
+ status: 302,
395
+ headers: {
396
+ Location: session.authorizationCodeGrant.redirectUri ?? "/"
397
+ }
398
+ });
399
+ }
400
+ });
401
+ logout = $route({
402
+ security: false,
403
+ url: "/logout",
404
+ method: "GET",
405
+ schema: {
406
+ query: t.object({
407
+ redirect: t.optional(t.string())
408
+ }),
409
+ cookies: t.object({
410
+ ssid: t.string()
411
+ })
412
+ },
413
+ handler: async ({ query, cookies }, { fastify }) => {
414
+ const session = fastify?.req.session;
415
+ await this.sessions.invalidate(cookies.ssid);
416
+ const redirect = query.redirect ?? "/";
417
+ const params = new URLSearchParams();
418
+ params.set("post_logout_redirect_uri", redirect);
419
+ if (session?.id_token) {
420
+ params.set("id_token_hint", session.id_token);
421
+ }
422
+ return new Response("", {
423
+ status: 302,
424
+ headers: {
425
+ "Set-Cookie": `${this.SSID}=; HttpOnly; Path=/; SameSite=Lax;`,
426
+ Location: buildEndSessionUrl(this.clients[0], params).toString()
427
+ }
428
+ });
429
+ }
430
+ });
431
+ session = $route({
432
+ security: false,
433
+ url: "/_session",
434
+ method: "GET",
435
+ schema: {
436
+ headers: t.object({
437
+ authorization: t.string()
438
+ }),
439
+ response: sessionSchema
440
+ },
441
+ handler: async ({ headers }) => {
442
+ try {
443
+ return {
444
+ user: await this.securityProvider.createUserFromToken(
445
+ headers.authorization
446
+ )
447
+ };
448
+ } catch (e) {
449
+ return {};
450
+ }
451
+ }
452
+ });
453
+ }
454
+ const isViteFile = (file) => {
455
+ const [pathname] = file.split("?");
456
+ if (pathname.startsWith("/docs")) {
457
+ return false;
458
+ }
459
+ if (pathname.match(/\.\w{2,5}$/)) {
460
+ return true;
461
+ }
462
+ if (pathname.startsWith("/@")) {
463
+ return true;
464
+ }
465
+ return false;
466
+ };
467
+
468
+ class ReactModule {
469
+ alepha = $inject(Alepha);
470
+ constructor() {
471
+ this.alepha.with(ServerModule).with(ServerLinksProvider).with(ReactServerProvider).with(ReactSessionProvider).with(PageDescriptorProvider);
472
+ }
473
+ }
474
+ autoInject($page, ReactModule);
475
+
476
+ export { $page, PageDescriptorProvider, ReactModule, ReactServerProvider, ReactSessionProvider, Router, envSchema$1 as envSchema, sessionSchema, sessionUserSchema };