@lowdefy/server-dev 0.0.0-experimental-20260914131506 → 0.0.0-experimental-20260925210809

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/client/App.jsx +1 -1
  2. package/client/Page.jsx +13 -0
  3. package/client/clientBuildImports.test.mjs +61 -0
  4. package/lib/client/RedirectingPage.jsx +56 -0
  5. package/lib/client/auth/Auth.jsx +6 -8
  6. package/lib/client/auth/AuthConfigured.jsx +203 -39
  7. package/lib/client/auth/AuthNotConfigured.js +41 -8
  8. package/lib/client/auth/authNotConfiguredParity.test.mjs +61 -0
  9. package/lib/client/auth/authTemplateSync.test.mjs +40 -0
  10. package/lib/client/auth/betterAuthSessionContract.test.mjs +181 -0
  11. package/lib/client/utils/usePageConfig.js +15 -0
  12. package/lib/docs/createDocsMcpServer.js +157 -484
  13. package/lib/docs/createDocsMcpServer.test.mjs +10 -0
  14. package/lib/docs/devToolDefinitions.js +361 -0
  15. package/lib/docs/docs.test.mjs +1 -0
  16. package/lib/docs/getBrowser.test.mjs +0 -2
  17. package/lib/docs/getOverview.js +18 -3
  18. package/lib/docs/getOverviewBasePath.test.mjs +36 -0
  19. package/lib/docs/isPageReady.js +5 -0
  20. package/lib/docs/isPageReady.test.mjs +21 -0
  21. package/lib/docs/runCheck.js +75 -0
  22. package/lib/docs/runCheck.test.mjs +91 -0
  23. package/lib/docs/runCheckChild.js +47 -0
  24. package/lib/docs/runEndpoint.test.mjs +1 -1
  25. package/lib/docs/runRequest.test.mjs +4 -3
  26. package/lib/docs/searchIcons.js +93 -0
  27. package/lib/docs/searchIcons.test.mjs +81 -0
  28. package/lib/docs/waitForBuild.js +47 -0
  29. package/lib/docs/waitForBuild.test.mjs +71 -0
  30. package/lib/server/auth/createSystemContext.js +73 -0
  31. package/lib/server/auth/getAuth.js +46 -0
  32. package/lib/server/auth/getHeadlessUser.js +7 -8
  33. package/lib/server/auth/getMockUser.js +10 -6
  34. package/lib/server/auth/{getAuthConfig.js → getStrategies.js} +12 -10
  35. package/lib/server/auth/headlessUser.js +3 -2
  36. package/lib/server/auth/resolveHeadlessUser.test.mjs +0 -4
  37. package/lib/server/createLowdefyContext.js +93 -49
  38. package/lib/server/createLowdefyContext.test.mjs +147 -0
  39. package/lib/server/getPageJitEnrichment.test.mjs +21 -0
  40. package/lib/server/jitPageBuilder.js +14 -8
  41. package/lib/server/loadDynamicJsMap.js +47 -0
  42. package/lib/server/log/createLogger.test.mjs +62 -0
  43. package/lib/server/log/logRequest.js +1 -3
  44. package/lib/server/scrubSecrets.js +23 -0
  45. package/lib/vite/createDevServerExclude.js +40 -0
  46. package/lib/vite/createDevServerExclude.test.mjs +79 -0
  47. package/manager/getContext.mjs +5 -0
  48. package/manager/processes/startServer.mjs +10 -2
  49. package/manager/run.mjs +40 -24
  50. package/manager/utils/BatchChanges.mjs +21 -5
  51. package/manager/utils/BatchChanges.test.mjs +77 -0
  52. package/manager/utils/acquireDevInstance.mjs +94 -0
  53. package/manager/utils/acquireDevInstance.test.mjs +103 -0
  54. package/manager/utils/createCustomPluginTypesMap.mjs +2 -2
  55. package/manager/utils/readBasePath.mjs +27 -0
  56. package/manager/utils/readBasePath.test.mjs +43 -0
  57. package/manager/utils/resolvePorts.mjs +49 -0
  58. package/manager/utils/setupWatcher.mjs +2 -1
  59. package/manager/utils/waitForServer.mjs +38 -0
  60. package/manager/watchers/lowdefyBuildWatcher.mjs +2 -2
  61. package/manager/watchers/moduleBuildWatcher.mjs +1 -0
  62. package/manager/watchers/serverArtifactWatcher.mjs +0 -2
  63. package/package.json +44 -40
  64. package/package.original.json +44 -40
  65. package/src/app.js +49 -16
  66. package/src/html/renderDevPage.js +5 -14
  67. package/src/middleware/errorHandler.js +24 -11
  68. package/src/middleware/errorHandler.test.mjs +95 -29
  69. package/src/middleware/localDevToolsOnly.js +38 -0
  70. package/src/middleware/localDevToolsOnly.test.mjs +61 -0
  71. package/src/routes/auth.js +18 -26
  72. package/src/routes/cronForward.js +4 -2
  73. package/src/routes/detached.js +16 -8
  74. package/src/routes/docs/buildStatus.js +6 -1
  75. package/src/routes/docs/icons.js +30 -0
  76. package/src/routes/docs/runEndpoint.js +2 -3
  77. package/src/routes/docs/runRequest.js +2 -4
  78. package/src/routes/endpoints.js +14 -9
  79. package/src/routes/jitPage.js +42 -2
  80. package/src/routes/jitPage.test.mjs +107 -0
  81. package/src/routes/mcp.js +71 -5
  82. package/src/routes/mcp.test.mjs +199 -0
  83. package/src/routes/mcpProtectedResourceMetadata.js +34 -0
  84. package/src/routes/mcpProtectedResourceMetadata.test.mjs +65 -0
  85. package/src/routes/mountOauthDiscovery.js +44 -0
  86. package/src/routes/mountOauthDiscovery.test.mjs +79 -0
  87. package/src/routes/normalizeMcpProtocolVersionHeader.js +46 -0
  88. package/src/routes/normalizeMcpProtocolVersionHeader.test.mjs +62 -0
  89. package/src/routes/user.js +27 -0
  90. package/vite.config.js +3 -10
  91. package/lib/server/auth/getDevSession.js +0 -70
  92. package/lib/server/auth/getDevSession.test.mjs +0 -138
  93. package/lib/server/auth/getDevSessionAuthDevOnly.test.mjs +0 -73
  94. package/lib/server/auth/session.js +0 -39
  95. package/manager/processes/warnAuthUrlPortMismatch.mjs +0 -47
  96. package/manager/processes/warnAuthUrlPortMismatch.test.mjs +0 -93
  97. package/manager/utils/acquireManagerLock.mjs +0 -63
  98. package/manager/utils/acquireManagerLock.test.mjs +0 -79
  99. package/src/routes/apiPage.js +0 -37
  100. package/src/routes/auth.test.mjs +0 -84
package/client/App.jsx CHANGED
@@ -144,7 +144,7 @@ function App({ config, router }) {
144
144
  />
145
145
  }
146
146
  >
147
- <Auth session={config.devSession}>
147
+ <Auth user={config?.user}>
148
148
  {(auth) => {
149
149
  return <Routing auth={auth} lowdefy={lowdefyRef.current} router={router} />;
150
150
  }}
package/client/Page.jsx CHANGED
@@ -20,6 +20,7 @@ import Client from '@lowdefy/client';
20
20
 
21
21
  import BuildErrorPage from '../lib/client/BuildErrorPage.jsx';
22
22
  import InstallingPluginsPage from '../lib/client/InstallingPluginsPage.jsx';
23
+ import RedirectingPage from '../lib/client/RedirectingPage.jsx';
23
24
  import usePageConfig from '../lib/client/utils/usePageConfig.js';
24
25
 
25
26
  const Page = ({
@@ -46,10 +47,22 @@ const Page = ({
46
47
  }
47
48
  }, [pageConfig?._warnings, lowdefy]);
48
49
 
50
+ // Full load to the sign-in page so it can return here after sign-in — an
51
+ // effect, not a fetcher side effect, so the redirect re-fires if the same
52
+ // cached result renders again.
53
+ useEffect(() => {
54
+ if (pageConfig?.authRedirect) {
55
+ window.location.assign(pageConfig.authRedirect);
56
+ }
57
+ }, [pageConfig?.authRedirect]);
58
+
49
59
  if (!pageConfig) {
50
60
  router.replace({ pathname: '/404' });
51
61
  return '';
52
62
  }
63
+ if (pageConfig.authRedirect) {
64
+ return <RedirectingPage redirect={pageConfig.authRedirect} />;
65
+ }
53
66
  if (pageConfig.buildError) {
54
67
  return (
55
68
  <BuildErrorPage
@@ -0,0 +1,61 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ // Everything the client imports from build/ ships in the browser bundle. build/config.json is
22
+ // server-only: it carries every deployment environment's settings (other environments' urls,
23
+ // secret names, email filters). The client learns only the current environment's name and
24
+ // switched-off features, through appMeta. This allowlist fails the build of any new client import
25
+ // of a build artifact until it has been checked for what it exposes.
26
+ const allowed = new Set([
27
+ 'auth.json',
28
+ 'appMeta.json',
29
+ 'logger.json',
30
+ 'i18n/antdLocales.js',
31
+ 'i18n/antdXLocales.js',
32
+ 'i18n/dayjsLocales.js',
33
+ 'plugins/actions.js',
34
+ 'plugins/blockMetas.json',
35
+ 'plugins/blocks.js',
36
+ 'plugins/icons.js',
37
+ 'plugins/operators/client.js',
38
+ 'plugins/operators/clientJsMap.js',
39
+ ]);
40
+
41
+ const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
42
+
43
+ function listSourceFiles(dir) {
44
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
45
+ const full = path.join(dir, entry.name);
46
+ if (entry.isDirectory()) return listSourceFiles(full);
47
+ return /\.(js|jsx|mjs)$/.test(entry.name) && !entry.name.includes('.test.') ? [full] : [];
48
+ });
49
+ }
50
+
51
+ test('client code imports only client-safe build artifacts', () => {
52
+ const imported = ['client', 'lib/client'].flatMap((dir) =>
53
+ listSourceFiles(path.join(root, dir)).flatMap((file) =>
54
+ [...fs.readFileSync(file, 'utf8').matchAll(/from '[^']*\/build\/([^']+)'/g)].map(
55
+ (match) => ({ file: path.relative(root, file), artifact: match[1] })
56
+ )
57
+ )
58
+ );
59
+ expect(imported.length).toBeGreaterThan(0);
60
+ expect(imported.filter(({ artifact }) => !allowed.has(artifact))).toEqual([]);
61
+ });
@@ -0,0 +1,56 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import React from 'react';
18
+
19
+ // Shown while the 401 sign-in redirect navigates. The link is the escape
20
+ // hatch for a dropped navigation - the tab must never depend on a single
21
+ // window.location.assign to leave this screen.
22
+ const RedirectingPage = ({ redirect }) => {
23
+ return (
24
+ <div
25
+ style={{
26
+ height: '100vh',
27
+ textAlign: 'center',
28
+ display: 'flex',
29
+ flexDirection: 'column',
30
+ alignItems: 'center',
31
+ justifyContent: 'center',
32
+ backgroundColor: 'var(--ant-color-bg-layout)',
33
+ color: 'var(--ant-color-text)',
34
+ fontFamily:
35
+ "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
36
+ }}
37
+ >
38
+ <div
39
+ style={{
40
+ verticalAlign: 'middle',
41
+ display: 'inline-block',
42
+ }}
43
+ >
44
+ <h3>Redirecting to sign-in...</h3>
45
+ <p>
46
+ <a href={redirect} style={{ color: 'var(--ant-color-primary)' }}>
47
+ Continue to sign-in
48
+ </a>{' '}
49
+ if you are not redirected automatically.
50
+ </p>
51
+ </div>
52
+ </div>
53
+ );
54
+ };
55
+
56
+ export default RedirectingPage;
@@ -14,8 +14,6 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- /* eslint-disable react/jsx-props-no-spreading */
18
-
19
17
  import React from 'react';
20
18
  import AuthConfigured from './AuthConfigured.jsx';
21
19
  import AuthNotConfigured from './AuthNotConfigured.js';
@@ -25,24 +23,24 @@ import { serializer } from '@lowdefy/helpers';
25
23
  // Client code imports the build JSON directly — Vite handles JSON imports;
26
24
  // the lib/build/*.js wrappers are server-only (they read from disk).
27
25
  // Deserialize to restore arrays from their ~arr build markers (providers
28
- // must be a real array for single-provider inference in createAuthMethods).
26
+ // must be a real array for provider lookups in createAuthMethods).
29
27
  import rawAuthConfig from '../../../build/auth.json';
30
28
 
31
29
  const authConfig = serializer.deserialize(rawAuthConfig);
32
30
 
33
- function Auth({ children, session }) {
31
+ function Auth({ children, user }) {
34
32
  if (authConfig.configured === true) {
35
33
  return (
36
- <AuthConfigured serverSession={session} authConfig={authConfig}>
34
+ <AuthConfigured serverUser={user} authConfig={authConfig}>
37
35
  {(auth) => children(auth)}
38
36
  </AuthConfigured>
39
37
  );
40
38
  }
41
39
  // An app whose only auth key is auth.dev has no auth stack, but the dev
42
- // server still resolves a session for auth.dev.mockUser - pass it through
43
- // so _user reads the same identity in the browser as on the server.
40
+ // server still resolves a caller for auth.dev.mockUser - pass it through so
41
+ // _user reads the same identity in the browser as on the server.
44
42
  return (
45
- <AuthNotConfigured authConfig={authConfig} session={session}>
43
+ <AuthNotConfigured authConfig={authConfig} user={user}>
46
44
  {(auth) => children(auth)}
47
45
  </AuthNotConfigured>
48
46
  );
@@ -14,60 +14,224 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- /* eslint-disable react/jsx-props-no-spreading */
18
-
19
- import React, { useEffect, useRef } from 'react';
17
+ import React, { useEffect, useRef, useState } from 'react';
18
+ import { createAuthClient } from 'better-auth/react';
20
19
  import {
21
- authConfigManager,
22
- getSession,
23
- SessionProvider,
24
- signIn,
25
- signOut,
26
- useSession,
27
- } from '@hono/auth-js/react';
20
+ adminClient,
21
+ emailOTPClient,
22
+ magicLinkClient,
23
+ organizationClient,
24
+ phoneNumberClient,
25
+ twoFactorClient,
26
+ } from 'better-auth/client/plugins';
27
+ import { oauthProviderClient } from '@better-auth/oauth-provider/client';
28
+ import { passkeyClient } from '@better-auth/passkey/client';
28
29
 
29
- import { serializer } from '@lowdefy/helpers';
30
+ import { normalizeCaller } from '@lowdefy/helpers';
30
31
 
31
- import rawLowdefyConfig from '../../../build/config.json';
32
+ // The app basePath, from Vite's BASE_URL (`${config.basePath}/`, set in
33
+ // vite.config.js). build/config.json is server-only - it carries every
34
+ // deployment environment's settings - so it is never imported into the client.
35
+ const basePath = import.meta.env.BASE_URL.replace(/\/$/, '');
32
36
 
33
- const lowdefyConfig = serializer.deserialize(rawLowdefyConfig);
37
+ // GenericOAuth providers have no client plugin here. BetterAuth 1.7.0 dropped
38
+ // genericOAuthClient from better-auth/client/plugins, and nothing replaces it:
39
+ // through 1.6.x it was a marker plugin carrying only an id, a version, an empty
40
+ // $InferServerPlugin for TypeScript inference, and the generic-oauth error
41
+ // codes - no actions, atoms, fetch plugins or path methods. signIn.oauth2 is
42
+ // resolved by the client's dynamic path proxy from the call itself
43
+ // (signIn.oauth2 -> POST /sign-in/oauth2, POST because providerId is always
44
+ // sent), so the sign-in a Lowdefy GenericOAuth provider makes is unaffected.
45
+ const authClient = createAuthClient({
46
+ baseURL: `${window.location.origin}${basePath}/api/auth`,
47
+ plugins: [
48
+ adminClient(),
49
+ emailOTPClient(),
50
+ magicLinkClient(),
51
+ oauthProviderClient(),
52
+ organizationClient(),
53
+ passkeyClient(),
54
+ phoneNumberClient(),
55
+ twoFactorClient(),
56
+ ],
57
+ });
34
58
 
35
- // @hono/auth-js/react configures its fetch paths through a module-level
36
- // manager instead of SessionProvider props.
37
- if (lowdefyConfig.basePath) {
38
- authConfigManager.setConfig({ basePath: `${lowdefyConfig.basePath}/api/auth` });
39
- }
59
+ // UpdateSession owns session freshness - suppress BetterAuth's own
60
+ // signal-driven refetch on the calls that would otherwise fire one, so
61
+ // nothing competes with (and aborts) the refetch UpdateSession awaits.
62
+ // Only calls that mutate an existing session are suppressed - calls that
63
+ // can establish one (the sign-ins, and the two-factor, phone-number,
64
+ // email-otp and passkey verifies) keep their signal: its refetch is what makes the store
65
+ // notice a login when no navigation follows.
66
+ // disableSignal silences all atomListeners for the call, including the
67
+ // organization plugin's org atoms - none are exposed to app config, so a
68
+ // future design exposing one must refresh it through its own action.
69
+ const sessionScoped = (params) => ({
70
+ ...params,
71
+ fetchOptions: { ...params?.fetchOptions, disableSignal: true },
72
+ });
40
73
 
41
- function Session({ children }) {
42
- const wasAuthenticated = useRef(false);
43
- const { data: session, status } = useSession();
44
- wasAuthenticated.current = wasAuthenticated.current || status === 'authenticated';
74
+ // The server resolves the caller per request and embeds it in the page
75
+ // config, so the first render never flashes unauthenticated. The BetterAuth
76
+ // client store takes over once its session fetch settles.
77
+ //
78
+ // Roles and merged attributes resolve server-side from the active member row
79
+ // - the base session carries neither. The last server-resolved caller is
80
+ // held in state: while the session user is unchanged it stays authoritative
81
+ // for the fields the session does not carry, and UpdateSession refreshes it
82
+ // from /api/user after a change (e.g. SetActiveOrganization). Holding it in
83
+ // state, not a ref, re-renders Session when it changes so _user recomputes -
84
+ // the same reactive footing the session half already stands on.
85
+ //
86
+ // Only the session half is passed through normalizeCaller. BetterAuth's store
87
+ // returns camelCase keys whatever the columns are named, so untransformed it
88
+ // would sit emailVerified beside the resolved caller's email_verified on one
89
+ // object; anything arriving from the server is already snake_case.
90
+ function Session({ children, reloadSuppressedRef, serverUser }) {
91
+ const { data: session, isPending } = authClient.useSession();
92
+ const [resolvedUser, setResolvedUser] = useState(serverUser);
93
+ const wasAuthenticated = useRef(Boolean(serverUser));
45
94
 
46
95
  useEffect(() => {
47
- if (wasAuthenticated.current && status === 'unauthenticated') {
96
+ if (session) {
97
+ wasAuthenticated.current = true;
98
+ }
99
+ // Reload after sign-out (or session revocation) so the server can apply
100
+ // the page auth fork - a protected page redirects to the login page.
101
+ // A logout with a callbackUrl suppresses the reload - its own navigation
102
+ // would otherwise race this one.
103
+ if (wasAuthenticated.current && !isPending && !session && !reloadSuppressedRef.current) {
48
104
  window.location.reload();
49
105
  }
50
- }, [status]);
106
+ }, [session, isPending]);
51
107
 
52
- // If session is passed to SessionProvider from the server-rendered config
53
- // we won't have a loading state here, but unauthenticated first loads do.
54
- if (status === 'loading') {
55
- return '';
108
+ if (isPending) {
109
+ return children(resolvedUser, setResolvedUser);
110
+ }
111
+ if (!session?.user) {
112
+ return children(null, setResolvedUser);
113
+ }
114
+ const resolved = resolvedUser;
115
+ if (!resolved) {
116
+ return children({ roles: [], ...normalizeCaller(session.user) }, setResolvedUser);
117
+ }
118
+ if (resolved.id !== session.user.id) {
119
+ // The ref has not caught up with a changed session user - a sign-in as a
120
+ // different person lands between the session refetch and the /api/user
121
+ // result. Render the last resolved caller whole rather than mixing the new
122
+ // session user with the previous person's resolved fields, or falling back
123
+ // to a caller with no roles - blocks re-evaluate operators on render, so a
124
+ // role-guarded page would act on an empty role list. UpdateSession closes
125
+ // the window when it lands the new caller; a flow that changes the session
126
+ // user without chaining it leaves the previous caller rendered until the
127
+ // next page load.
128
+ return children(resolved, setResolvedUser);
56
129
  }
57
- return children(session);
130
+ // _user is one object with one meaning on both sides: the resolved caller is
131
+ // spread whole, so every field resolveAuthentication emits is readable in app
132
+ // config without this file naming it. session.user is the floor - the client
133
+ // store may hold a fresher one than the resolved state, and the resolved
134
+ // object wins wherever both carry a key.
135
+ const user = { ...normalizeCaller(session.user), ...resolved };
136
+ return children(user, setResolvedUser);
58
137
  }
59
138
 
60
- function AuthConfigured({ authConfig, children, serverSession }) {
61
- const auth = { authConfig, getSession, signIn, signOut };
139
+ function AuthConfigured({ authConfig, children, serverUser }) {
140
+ const reloadSuppressedRef = useRef(false);
141
+ const auth = {
142
+ authConfig,
143
+ getSession: ({ disableCookieCache } = {}) =>
144
+ authClient.getSession(disableCookieCache ? { query: { disableCookieCache: true } } : {}),
145
+ // Refetches the session through the session atom - the store's only
146
+ // writer - and resolves only after the store is written. fetchSession
147
+ // returns undefined and never rejects (failures are written into the
148
+ // atom), so the atom's own { data, error } is read back and returned,
149
+ // keeping unwrap working and surfacing a failed refresh to the action.
150
+ refreshSession: async ({ disableCookieCache } = {}) => {
151
+ const sessionAtom = authClient.$store.atoms.session;
152
+ await sessionAtom
153
+ .get()
154
+ .refetch(disableCookieCache ? { query: { disableCookieCache: true } } : undefined);
155
+ const { data, error } = sessionAtom.get();
156
+ return { data, error };
157
+ },
158
+ // The server-resolved caller - roles from the active member row and the
159
+ // merged attributes bag - for re-syncing after session changes.
160
+ getResolvedUser: async () => {
161
+ const response = await fetch(`${basePath}/api/user`, {
162
+ credentials: 'same-origin',
163
+ });
164
+ if (!response.ok) {
165
+ // /api/user itself always answers 200 { user } - user: null when no
166
+ // caller is admitted, which updateSession branches on. A non-OK
167
+ // response is a transport failure (gateway error page, 5xx) with no
168
+ // parsable body.
169
+ throw new Error(`Failed to fetch the resolved user (HTTP ${response.status}).`);
170
+ }
171
+ return response.json();
172
+ },
173
+ suppressSignOutReload: () => {
174
+ reloadSuppressedRef.current = true;
175
+ },
176
+ acceptInvitation: (params) => authClient.organization.acceptInvitation(sessionScoped(params)),
177
+ // addPasskey runs the WebAuthn browser ceremony itself - options fetch,
178
+ // authenticator prompt, verification.
179
+ addPasskey: (params) => authClient.passkey.addPasskey(params),
180
+ changePassword: (params) => authClient.changePassword(sessionScoped(params)),
181
+ deletePasskey: (params) => authClient.passkey.deletePasskey(params),
182
+ updatePasskey: (params) => authClient.passkey.updatePasskey(params),
183
+ leaveOrganization: (params) => authClient.organization.leave(sessionScoped(params)),
184
+ // The caller's memberships from the org plugin, keyed on the session
185
+ // alone - not the active organization. sessionScoped so the list read
186
+ // does not also fire the org-list atom's own refetch of the same route.
187
+ listOrganizations: () => authClient.organization.list(sessionScoped()),
188
+ // POST /oauth2/consent. The signed authorization query is not passed
189
+ // here - the oauthProviderClient fetch plugin stamps it onto the body as
190
+ // oauth_query from window.location.search, so the call must run while
191
+ // the page still holds the query the oauth-provider redirect arrived
192
+ // with.
193
+ oauth2Consent: (params) => authClient.oauth2.consent(params),
194
+ // POST /oauth2/continue - resumes the authorization after the post-login
195
+ // organization choice (the page runs SetActiveOrganization first). Same
196
+ // oauth_query contract as oauth2Consent: the signed query rides from
197
+ // window.location.search, so the call must run before any navigation.
198
+ oauth2Continue: (params) => authClient.oauth2.continue(params),
199
+ // The one-time email code: send, then sign in with it.
200
+ emailOtpSend: (params) => authClient.emailOtp.sendVerificationOtp(params),
201
+ emailOtpVerify: (params) => authClient.signIn.emailOtp(params),
202
+ phoneNumberRequestPasswordReset: (params) =>
203
+ authClient.phoneNumber.requestPasswordReset(params),
204
+ phoneNumberResetPassword: (params) => authClient.phoneNumber.resetPassword(params),
205
+ phoneNumberSendOtp: (params) => authClient.phoneNumber.sendOtp(params),
206
+ phoneNumberVerify: (params) => authClient.phoneNumber.verify(params),
207
+ requestPasswordReset: (params) => authClient.requestPasswordReset(params),
208
+ resetPassword: (params) => authClient.resetPassword(params),
209
+ revokeOtherSessions: () => authClient.revokeOtherSessions(sessionScoped()),
210
+ sendVerificationEmail: (params) => authClient.sendVerificationEmail(params),
211
+ setActiveOrganization: (params) => authClient.organization.setActive(sessionScoped(params)),
212
+ signInEmail: (params) => authClient.signIn.email(params),
213
+ signInMagicLink: (params) => authClient.signIn.magicLink(params),
214
+ signInOauth2: (params) => authClient.signIn.oauth2(params),
215
+ signInPasskey: (params) => authClient.signIn.passkey(params),
216
+ signInPhoneNumber: (params) => authClient.signIn.phoneNumber(params),
217
+ signInSocial: (params) => authClient.signIn.social(params),
218
+ signOut: () => authClient.signOut(),
219
+ signUpEmail: (params) => authClient.signUp.email(params),
220
+ twoFactorDisable: (params) => authClient.twoFactor.disable(sessionScoped(params)),
221
+ twoFactorEnable: (params) => authClient.twoFactor.enable(sessionScoped(params)),
222
+ twoFactorGenerateBackupCodes: (params) =>
223
+ authClient.twoFactor.generateBackupCodes(sessionScoped(params)),
224
+ twoFactorVerifyBackupCode: (params) => authClient.twoFactor.verifyBackupCode(params),
225
+ twoFactorVerifyTotp: (params) => authClient.twoFactor.verifyTotp(params),
226
+ };
62
227
  return (
63
- <SessionProvider session={serverSession}>
64
- <Session>
65
- {(session) => {
66
- auth.session = session;
67
- return children(auth);
68
- }}
69
- </Session>
70
- </SessionProvider>
228
+ <Session reloadSuppressedRef={reloadSuppressedRef} serverUser={serverUser}>
229
+ {(user, setResolvedUser) => {
230
+ auth.user = user;
231
+ auth.updateResolvedUser = (resolved) => setResolvedUser(resolved);
232
+ return children(auth);
233
+ }}
234
+ </Session>
71
235
  );
72
236
  }
73
237
 
@@ -13,7 +13,6 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */
16
- /* eslint-disable react/jsx-props-no-spreading */
17
16
 
18
17
  import { ConfigError } from '@lowdefy/errors';
19
18
 
@@ -23,17 +22,51 @@ function authNotConfigured() {
23
22
  );
24
23
  }
25
24
 
26
- // A dev mock user reaches the browser through this component: an app whose
27
- // only auth key is auth.dev has no auth stack, but the dev server still
28
- // resolves a session for it, so _user reads the same identity in the browser
29
- // as on the server.
30
- function AuthNotConfigured({ authConfig, children, session = null }) {
25
+ // Every key AuthConfigured exposes must be present here, or an auth action in an
26
+ // app without an auth section fails with "auth.x is not a function" instead of
27
+ // the ConfigError that names the missing config.
28
+ function AuthNotConfigured({ authConfig, children, user = null }) {
31
29
  const auth = {
32
30
  authConfig,
33
- session,
31
+ user,
32
+ acceptInvitation: authNotConfigured,
33
+ addPasskey: authNotConfigured,
34
+ changePassword: authNotConfigured,
35
+ deletePasskey: authNotConfigured,
36
+ getResolvedUser: authNotConfigured,
34
37
  getSession: authNotConfigured,
35
- signIn: authNotConfigured,
38
+ leaveOrganization: authNotConfigured,
39
+ listOrganizations: authNotConfigured,
40
+ oauth2Consent: authNotConfigured,
41
+ oauth2Continue: authNotConfigured,
42
+ emailOtpSend: authNotConfigured,
43
+ emailOtpVerify: authNotConfigured,
44
+ phoneNumberRequestPasswordReset: authNotConfigured,
45
+ phoneNumberResetPassword: authNotConfigured,
46
+ phoneNumberSendOtp: authNotConfigured,
47
+ phoneNumberVerify: authNotConfigured,
48
+ refreshSession: authNotConfigured,
49
+ requestPasswordReset: authNotConfigured,
50
+ resetPassword: authNotConfigured,
51
+ revokeOtherSessions: authNotConfigured,
52
+ sendVerificationEmail: authNotConfigured,
53
+ setActiveOrganization: authNotConfigured,
54
+ signInEmail: authNotConfigured,
55
+ signInMagicLink: authNotConfigured,
56
+ signInOauth2: authNotConfigured,
57
+ signInPasskey: authNotConfigured,
58
+ signInPhoneNumber: authNotConfigured,
59
+ signInSocial: authNotConfigured,
36
60
  signOut: authNotConfigured,
61
+ signUpEmail: authNotConfigured,
62
+ suppressSignOutReload: authNotConfigured,
63
+ twoFactorDisable: authNotConfigured,
64
+ twoFactorEnable: authNotConfigured,
65
+ twoFactorGenerateBackupCodes: authNotConfigured,
66
+ twoFactorVerifyBackupCode: authNotConfigured,
67
+ twoFactorVerifyTotp: authNotConfigured,
68
+ updatePasskey: authNotConfigured,
69
+ updateResolvedUser: authNotConfigured,
37
70
  };
38
71
 
39
72
  return children(auth);
@@ -0,0 +1,61 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { readFile } from 'node:fs/promises';
18
+ import path from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ import AuthNotConfigured from './AuthNotConfigured.js';
22
+
23
+ const authDir = path.dirname(fileURLToPath(import.meta.url));
24
+
25
+ // The keys of the `const auth = { ... }` literal plus the `auth.x =` assignments
26
+ // made after it - both reach the app through the same context object.
27
+ function readExposedKeys(source) {
28
+ const literal = source.slice(source.indexOf('const auth = {'), source.indexOf('\n };'));
29
+ const keys = [...literal.matchAll(/^ {4}([a-zA-Z0-9_]+)[:,]/gm)].map((match) => match[1]);
30
+ const assigned = [...source.matchAll(/^ +auth\.([a-zA-Z0-9_]+) =/gm)].map((match) => match[1]);
31
+ return [...new Set([...keys, ...assigned])].sort();
32
+ }
33
+
34
+ function callAuthNotConfigured() {
35
+ let auth;
36
+ AuthNotConfigured({ authConfig: { enabled: false }, children: (value) => (auth = value) });
37
+ return auth;
38
+ }
39
+
40
+ // An app with no auth section still renders every block and action. A method
41
+ // AuthConfigured exposes but AuthNotConfigured omits surfaces as
42
+ // "auth.x is not a function" instead of the ConfigError naming the missing config.
43
+ test('AuthNotConfigured exposes every key AuthConfigured exposes', async () => {
44
+ const source = await readFile(path.join(authDir, 'AuthConfigured.jsx'), 'utf8');
45
+ const auth = callAuthNotConfigured();
46
+ expect(Object.keys(auth).sort()).toEqual(readExposedKeys(source));
47
+ });
48
+
49
+ test('AuthNotConfigured keeps authConfig and a null user', () => {
50
+ const auth = callAuthNotConfigured();
51
+ expect(auth.authConfig).toEqual({ enabled: false });
52
+ expect(auth.user).toBeNull();
53
+ });
54
+
55
+ test('AuthNotConfigured methods throw a ConfigError naming the missing auth config', () => {
56
+ const auth = callAuthNotConfigured();
57
+ expect(() => auth.signInEmail({})).toThrow(
58
+ 'Auth is not configured. Add an "auth" section to lowdefy.yaml to use auth actions.'
59
+ );
60
+ expect(() => auth.signInEmail({})).toThrow(expect.objectContaining({ name: 'ConfigError' }));
61
+ });
@@ -0,0 +1,40 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { readdir, readFile } from 'node:fs/promises';
18
+ import path from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+
21
+ const devAuthDir = path.dirname(fileURLToPath(import.meta.url));
22
+ const prodAuthDir = path.resolve(devAuthDir, '../../../../server/lib/client/auth');
23
+
24
+ // The dev and prod server templates each carry their own copy of the auth
25
+ // components, kept in sync by hand. A change applied to one and not the
26
+ // other ships dev-only or prod-only - the app then behaves differently
27
+ // between lowdefy dev and a production build, which no unit test of either
28
+ // copy can catch.
29
+ test('the auth client templates are byte-identical between server and server-dev', async () => {
30
+ const isTemplate = (file) => !file.includes('.test.');
31
+ const devFiles = (await readdir(devAuthDir)).filter(isTemplate).sort();
32
+ const prodFiles = (await readdir(prodAuthDir)).filter(isTemplate).sort();
33
+ expect(prodFiles).toEqual(devFiles);
34
+ for (const file of devFiles) {
35
+ const dev = await readFile(path.join(devAuthDir, file), 'utf8');
36
+ const prod = await readFile(path.join(prodAuthDir, file), 'utf8');
37
+ // Compared per file so a failure names the file that diverged.
38
+ expect({ file, content: prod }).toEqual({ file, content: dev });
39
+ }
40
+ });