@lowdefy/server-dev 0.0.0-experimental-20260716044341 → 0.0.0-experimental-20260716132211

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 (36) hide show
  1. package/lib/client/auth/Auth.jsx +3 -5
  2. package/lib/client/auth/AuthConfigured.jsx +116 -35
  3. package/lib/client/auth/AuthNotConfigured.js +22 -2
  4. package/lib/client/utils/usePageConfig.js +7 -0
  5. package/lib/docs/createDocsMcpServer.test.mjs +4 -1
  6. package/lib/docs/docs.test.mjs +7 -1
  7. package/lib/docs/findConfig.js +15 -3
  8. package/lib/server/auth/createSystemContext.js +70 -0
  9. package/lib/server/auth/getAuth.js +46 -0
  10. package/lib/server/auth/getHeadlessUser.js +7 -8
  11. package/lib/server/auth/getMockUser.js +11 -7
  12. package/lib/server/auth/{getAuthConfig.js → getStrategies.js} +12 -10
  13. package/lib/server/auth/headlessUser.js +3 -2
  14. package/lib/server/createLowdefyContext.js +56 -41
  15. package/lib/server/loadDynamicJsMap.js +47 -0
  16. package/lib/server/log/logRequest.js +1 -3
  17. package/manager/processes/startServer.mjs +0 -2
  18. package/manager/utils/createCustomPluginTypesMap.mjs +1 -2
  19. package/manager/watchers/serverArtifactWatcher.mjs +0 -2
  20. package/package.json +36 -34
  21. package/package.original.json +36 -34
  22. package/src/app.js +27 -14
  23. package/src/middleware/errorHandler.js +12 -1
  24. package/src/routes/auth.js +15 -21
  25. package/src/routes/detached.js +10 -6
  26. package/src/routes/docs/runRequest.js +2 -4
  27. package/src/routes/endpoints.js +14 -9
  28. package/src/routes/jitPage.js +21 -2
  29. package/src/routes/user.js +27 -0
  30. package/lib/server/auth/getDevSession.js +0 -70
  31. package/lib/server/auth/getDevSession.test.mjs +0 -138
  32. package/lib/server/auth/session.js +0 -39
  33. package/manager/processes/warnAuthUrlPortMismatch.mjs +0 -47
  34. package/manager/processes/warnAuthUrlPortMismatch.test.mjs +0 -93
  35. package/src/routes/apiPage.js +0 -37
  36. package/src/routes/auth.test.mjs +0 -84
@@ -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,15 +23,15 @@ 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
  );
@@ -14,17 +14,17 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- /* eslint-disable react/jsx-props-no-spreading */
18
-
19
17
  import React, { useEffect, useRef } 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
+ genericOAuthClient,
22
+ magicLinkClient,
23
+ organizationClient,
24
+ phoneNumberClient,
25
+ twoFactorClient,
26
+ } from 'better-auth/client/plugins';
27
+ import { passkeyClient } from '@better-auth/passkey/client';
28
28
 
29
29
  import { serializer } from '@lowdefy/helpers';
30
30
 
@@ -32,42 +32,123 @@ import rawLowdefyConfig from '../../../build/config.json';
32
32
 
33
33
  const lowdefyConfig = serializer.deserialize(rawLowdefyConfig);
34
34
 
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
- }
35
+ const authClient = createAuthClient({
36
+ baseURL: `${window.location.origin}${lowdefyConfig.basePath ?? ''}/api/auth`,
37
+ plugins: [
38
+ adminClient(),
39
+ genericOAuthClient(),
40
+ magicLinkClient(),
41
+ organizationClient(),
42
+ passkeyClient(),
43
+ phoneNumberClient(),
44
+ twoFactorClient(),
45
+ ],
46
+ });
40
47
 
41
- function Session({ children }) {
42
- const wasAuthenticated = useRef(false);
43
- const { data: session, status } = useSession();
44
- wasAuthenticated.current = wasAuthenticated.current || status === 'authenticated';
48
+ // The server resolves the caller per request and embeds it in the page
49
+ // config, so the first render never flashes unauthenticated. The BetterAuth
50
+ // client store takes over once its session fetch settles.
51
+ //
52
+ // Roles and merged attributes resolve server-side from the active member row
53
+ // - the base session carries neither. The last server-resolved caller is
54
+ // kept in a ref: while the session user is unchanged its roles and
55
+ // attributes stay authoritative, and UpdateSession refreshes the ref from
56
+ // /api/user after a change (e.g. SetActiveOrganization).
57
+ function Session({ children, reloadSuppressedRef, serverUser }) {
58
+ const { data: session, isPending } = authClient.useSession();
59
+ const resolvedUserRef = useRef(serverUser);
60
+ const wasAuthenticated = useRef(Boolean(serverUser));
45
61
 
46
62
  useEffect(() => {
47
- if (wasAuthenticated.current && status === 'unauthenticated') {
63
+ if (session) {
64
+ wasAuthenticated.current = true;
65
+ }
66
+ // Reload after sign-out (or session revocation) so the server can apply
67
+ // the page auth fork - a protected page redirects to the login page.
68
+ // A logout with a callbackUrl suppresses the reload - its own navigation
69
+ // would otherwise race this one.
70
+ if (wasAuthenticated.current && !isPending && !session && !reloadSuppressedRef.current) {
48
71
  window.location.reload();
49
72
  }
50
- }, [status]);
73
+ }, [session, isPending]);
51
74
 
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 '';
75
+ if (isPending) {
76
+ return children(resolvedUserRef.current, resolvedUserRef);
77
+ }
78
+ if (!session?.user) {
79
+ return children(null, resolvedUserRef);
56
80
  }
57
- return children(session);
81
+ const resolved = resolvedUserRef.current;
82
+ const user =
83
+ resolved && resolved.id === session.user.id
84
+ ? { ...session.user, roles: resolved.roles, attributes: resolved.attributes }
85
+ : { roles: [], ...session.user };
86
+ return children(user, resolvedUserRef);
58
87
  }
59
88
 
60
- function AuthConfigured({ authConfig, children, serverSession }) {
61
- const auth = { authConfig, getSession, signIn, signOut };
89
+ function AuthConfigured({ authConfig, children, serverUser }) {
90
+ const reloadSuppressedRef = useRef(false);
91
+ const auth = {
92
+ authConfig,
93
+ getSession: ({ disableCookieCache } = {}) =>
94
+ authClient.getSession(disableCookieCache ? { query: { disableCookieCache: true } } : {}),
95
+ // The server-resolved caller - roles from the active member row and the
96
+ // merged attributes bag - for re-syncing after session changes.
97
+ getResolvedUser: async () => {
98
+ const response = await fetch(`${lowdefyConfig.basePath ?? ''}/api/user`, {
99
+ credentials: 'same-origin',
100
+ });
101
+ if (!response.ok) {
102
+ // Throw instead of parsing an error page - a silent { user: undefined }
103
+ // would read as a client-side logout in updateSession.
104
+ throw new Error(`Failed to fetch the resolved user (HTTP ${response.status}).`);
105
+ }
106
+ return response.json();
107
+ },
108
+ suppressSignOutReload: () => {
109
+ reloadSuppressedRef.current = true;
110
+ },
111
+ acceptInvitation: (params) => authClient.organization.acceptInvitation(params),
112
+ // addPasskey runs the WebAuthn browser ceremony itself - options fetch,
113
+ // authenticator prompt, verification.
114
+ addPasskey: (params) => authClient.passkey.addPasskey(params),
115
+ changePassword: (params) => authClient.changePassword(params),
116
+ deletePasskey: (params) => authClient.passkey.deletePasskey(params),
117
+ impersonateUser: (params) => authClient.admin.impersonateUser(params),
118
+ phoneNumberRequestPasswordReset: (params) =>
119
+ authClient.phoneNumber.requestPasswordReset(params),
120
+ phoneNumberResetPassword: (params) => authClient.phoneNumber.resetPassword(params),
121
+ phoneNumberSendOtp: (params) => authClient.phoneNumber.sendOtp(params),
122
+ phoneNumberVerify: (params) => authClient.phoneNumber.verify(params),
123
+ requestPasswordReset: (params) => authClient.requestPasswordReset(params),
124
+ resetPassword: (params) => authClient.resetPassword(params),
125
+ revokeOtherSessions: () => authClient.revokeOtherSessions(),
126
+ sendVerificationEmail: (params) => authClient.sendVerificationEmail(params),
127
+ setActiveOrganization: (params) => authClient.organization.setActive(params),
128
+ signInEmail: (params) => authClient.signIn.email(params),
129
+ signInMagicLink: (params) => authClient.signIn.magicLink(params),
130
+ signInOauth2: (params) => authClient.signIn.oauth2(params),
131
+ signInPasskey: (params) => authClient.signIn.passkey(params),
132
+ signInPhoneNumber: (params) => authClient.signIn.phoneNumber(params),
133
+ signInSocial: (params) => authClient.signIn.social(params),
134
+ signOut: () => authClient.signOut(),
135
+ signUpEmail: (params) => authClient.signUp.email(params),
136
+ stopImpersonating: () => authClient.admin.stopImpersonating(),
137
+ twoFactorDisable: (params) => authClient.twoFactor.disable(params),
138
+ twoFactorEnable: (params) => authClient.twoFactor.enable(params),
139
+ twoFactorVerifyBackupCode: (params) => authClient.twoFactor.verifyBackupCode(params),
140
+ twoFactorVerifyTotp: (params) => authClient.twoFactor.verifyTotp(params),
141
+ };
62
142
  return (
63
- <SessionProvider session={serverSession}>
64
- <Session>
65
- {(session) => {
66
- auth.session = session;
67
- return children(auth);
68
- }}
69
- </Session>
70
- </SessionProvider>
143
+ <Session reloadSuppressedRef={reloadSuppressedRef} serverUser={serverUser}>
144
+ {(user, resolvedUserRef) => {
145
+ auth.user = user;
146
+ auth.updateResolvedUser = (resolved) => {
147
+ resolvedUserRef.current = resolved;
148
+ };
149
+ return children(auth);
150
+ }}
151
+ </Session>
71
152
  );
72
153
  }
73
154
 
@@ -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
  function authNotConfigured() {
19
18
  throw new Error('Auth not configured.');
@@ -22,9 +21,30 @@ function authNotConfigured() {
22
21
  function AuthNotConfigured({ authConfig, children }) {
23
22
  const auth = {
24
23
  authConfig,
24
+ user: null,
25
+ acceptInvitation: authNotConfigured,
26
+ addPasskey: authNotConfigured,
27
+ changePassword: authNotConfigured,
28
+ deletePasskey: authNotConfigured,
29
+ getResolvedUser: authNotConfigured,
25
30
  getSession: authNotConfigured,
26
- signIn: authNotConfigured,
31
+ impersonateUser: authNotConfigured,
32
+ requestPasswordReset: authNotConfigured,
33
+ resetPassword: authNotConfigured,
34
+ revokeOtherSessions: authNotConfigured,
35
+ sendVerificationEmail: authNotConfigured,
36
+ setActiveOrganization: authNotConfigured,
37
+ signInEmail: authNotConfigured,
38
+ signInMagicLink: authNotConfigured,
39
+ signInOauth2: authNotConfigured,
40
+ signInSocial: authNotConfigured,
27
41
  signOut: authNotConfigured,
42
+ signUpEmail: authNotConfigured,
43
+ stopImpersonating: authNotConfigured,
44
+ twoFactorDisable: authNotConfigured,
45
+ twoFactorEnable: authNotConfigured,
46
+ twoFactorVerifyBackupCode: authNotConfigured,
47
+ twoFactorVerifyTotp: authNotConfigured,
28
48
  };
29
49
 
30
50
  return children(auth);
@@ -54,6 +54,13 @@ async function fetchPageConfig(url) {
54
54
  if (res.status === 404) {
55
55
  return null;
56
56
  }
57
+ if (res.status === 401) {
58
+ // Logged-out navigation to a protected page - full load to the login
59
+ // page so it can return here after sign-in.
60
+ const { redirect } = await res.json();
61
+ window.location.assign(redirect ?? '/404');
62
+ return new Promise(() => {});
63
+ }
57
64
  const data = await res.json();
58
65
  if (data?.buildError) {
59
66
  return data;
@@ -104,7 +104,10 @@ test('MCP tools/call lowdefy_find_config locates a block by id', async () => {
104
104
  arguments: { id: 'home' },
105
105
  });
106
106
  const parsed = JSON.parse(result.content[0].text);
107
- expect(parsed).toEqual({ kind: 'page', pageId: 'home', file: 'pages/home.yaml' });
107
+ expect(parsed.kind).toEqual('page');
108
+ expect(parsed.pageId).toEqual('home');
109
+ expect(parsed.file).toEqual('pages/home.yaml');
110
+ expect(parsed.matches[0].location.source).toContain('pages/home.yaml');
108
111
  await client.close();
109
112
  });
110
113
 
@@ -229,7 +229,13 @@ test('getPageConfig returns null for a pageId not in the page registry', async (
229
229
 
230
230
  test('findConfig resolves a known pageId to its source file', async () => {
231
231
  const result = await findConfig({ id: 'home' });
232
- expect(result).toEqual({ kind: 'page', pageId: 'home', file: 'pages/home.yaml' });
232
+ expect(result.kind).toEqual('page');
233
+ expect(result.pageId).toEqual('home');
234
+ expect(result.file).toEqual('pages/home.yaml');
235
+ // A page's root block renders with blockId === pageId — open-in-editor and
236
+ // feedback enrichment read matches[0].location.source from this result.
237
+ expect(result.matches.length).toEqual(1);
238
+ expect(result.matches[0].location.source).toContain('pages/home.yaml');
233
239
  });
234
240
 
235
241
  test('findConfig scans keyMap for a matching id when no pageId is given', async () => {
@@ -189,12 +189,24 @@ async function findConfig({ id, pageId }) {
189
189
  }
190
190
 
191
191
  const pageRegistry = readBuildArtifact({ name: 'pageRegistry.json' }) ?? {};
192
+ const configDirectory = process.env.LOWDEFY_DIRECTORY_CONFIG || process.cwd();
193
+
194
+ // A page's root block renders with blockId === pageId, so open-in-editor
195
+ // and feedback enrichment hit this branch for it — they read
196
+ // matches[0].location.source, so the page result must carry a match, not
197
+ // just the file field the docs/MCP consumers use.
192
198
  if (pageRegistry[id]) {
193
- return { kind: 'page', pageId: id, file: pageRegistry[id].refPath };
199
+ const refPath = pageRegistry[id].refPath;
200
+ const matches = [];
201
+ if (type.isString(refPath)) {
202
+ matches.push({
203
+ keyPath: `pages[${id}]`,
204
+ location: { source: path.resolve(configDirectory, refPath) },
205
+ });
206
+ }
207
+ return { kind: 'page', pageId: id, file: refPath, matches };
194
208
  }
195
209
 
196
- const configDirectory = process.env.LOWDEFY_DIRECTORY_CONFIG || process.cwd();
197
-
198
210
  if (!type.isNone(pageId)) {
199
211
  if (!pageRegistry[pageId]) {
200
212
  return {
@@ -0,0 +1,70 @@
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 path from 'node:path';
18
+ import { createSystemContext as buildSystemContext } from '@lowdefy/api';
19
+ import { getSecretsFromEnv } from '@lowdefy/node-utils';
20
+ import { v4 as uuid } from 'uuid';
21
+
22
+ import agents from '../../../build/plugins/agents.js';
23
+ import appMeta from '../../build/appMeta.js';
24
+ import config from '../../build/config.js';
25
+ import connections from '../../../build/plugins/connections.js';
26
+ import createHandleError from '../log/createHandleError.js';
27
+ import createLogger from '../log/createLogger.js';
28
+ import fileCache from '../fileCache.js';
29
+ import i18nConfig from '../../build/i18n.js';
30
+ import loadDynamicJsMap from '../loadDynamicJsMap.js';
31
+ import notifications from '../../../build/plugins/notifications.js';
32
+ import operators from '../../../build/plugins/operators/server.js';
33
+ import steps from '../../../build/plugins/steps.js';
34
+ import websockets from '../../../build/plugins/websockets.js';
35
+
36
+ const secrets = getSecretsFromEnv();
37
+
38
+ // Builds a fresh system context per auth hook fire - the trusted internal
39
+ // caller the BetterAuth engine uses to invoke hook endpoints. All fields are
40
+ // startup singletons except the per-fire rid, logger, handleError, the
41
+ // dynamic jsMap re-read (JIT rebuilds rewrite serverJsMap.js), and auth -
42
+ // auth is threaded in by the caller (createHookDispatch) rather than
43
+ // imported directly, since it comes from the same BetterAuth construction
44
+ // that this factory is a dependency of (see createHookDispatch.js).
45
+ function createSystemContext({ auth } = {}) {
46
+ const rid = uuid();
47
+ const buildDirectory = path.join(process.cwd(), 'build');
48
+ return buildSystemContext({
49
+ rid,
50
+ agents,
51
+ appMeta,
52
+ auth,
53
+ buildDirectory,
54
+ config,
55
+ configDirectory: process.env.LOWDEFY_DIRECTORY_CONFIG || process.cwd(),
56
+ connections,
57
+ createHandleError,
58
+ fileCache,
59
+ i18n: i18nConfig,
60
+ jsMap: loadDynamicJsMap(buildDirectory),
61
+ logger: createLogger({ rid }),
62
+ notifications,
63
+ operators,
64
+ secrets,
65
+ steps,
66
+ websockets,
67
+ });
68
+ }
69
+
70
+ export default createSystemContext;
@@ -0,0 +1,46 @@
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 { getBetterAuth } from '@lowdefy/api';
18
+ import { getSecretsFromEnv } from '@lowdefy/node-utils';
19
+
20
+ import adapters from '../../../build/plugins/auth/adapters.js';
21
+ import appMeta from '../../build/appMeta.js';
22
+ import authJson from '../../build/auth.js';
23
+ import createSystemContext from './createSystemContext.js';
24
+ import lowdefyConfig from '../../build/config.js';
25
+ import providers from '../../../build/plugins/auth/providers.js';
26
+
27
+ // Returns the BetterAuth instance (memoized in @lowdefy/api), or null when
28
+ // auth is not configured. dev: true relaxes cookies for plain-http localhost
29
+ // and derives a per-app cookie prefix so parallel dev apps do not collide.
30
+ function getAuth({ logger }) {
31
+ if (authJson.configured !== true) {
32
+ return null;
33
+ }
34
+ return getBetterAuth({
35
+ appMeta,
36
+ authJson,
37
+ config: lowdefyConfig,
38
+ createSystemContext,
39
+ dev: true,
40
+ logger,
41
+ plugins: { adapters, providers },
42
+ secrets: getSecretsFromEnv(),
43
+ });
44
+ }
45
+
46
+ export default getAuth;
@@ -16,24 +16,23 @@
16
16
 
17
17
  import { HEADLESS_USER_COOKIE } from './headlessUser.js';
18
18
 
19
- // Decodes the headless renderer's user cookie (set by getBrowser.js openPage
20
- // on its own browser context, base64-encoded JSON) into the raw user object.
21
- // Returns just the user; getDevSession.js turns it into a session through
22
- // the same pipeline a real sign-in uses, so headless requests carry a
23
- // prod-shaped session while the developer's real browser (no cookie) is
24
- // unaffected.
19
+ // Mirrors the e2e user-injection pattern (server-e2e/lib/server/auth/getUser.js):
20
+ // the headless renderer sets a base64-JSON user cookie on its own browser
21
+ // context, so its /api/* fetches carry a pre-resolved caller while the
22
+ // developer's real browser (no cookie) is unaffected. Returns the raw decoded
23
+ // user, or null on miss - the caller floors the shape via normalizeInjectedCaller.
25
24
  function getHeadlessUser(c) {
26
25
  const cookieHeader = c.req.header('cookie') ?? '';
27
26
  const match = cookieHeader.match(new RegExp(`${HEADLESS_USER_COOKIE}=([^;]+)`));
28
27
  if (!match) {
29
- return undefined;
28
+ return null;
30
29
  }
31
30
 
32
31
  try {
33
32
  const decoded = Buffer.from(decodeURIComponent(match[1]), 'base64').toString();
34
33
  return JSON.parse(decoded);
35
34
  } catch {
36
- return undefined;
35
+ return null;
37
36
  }
38
37
  }
39
38
 
@@ -18,10 +18,10 @@ import { serializer } from '@lowdefy/helpers';
18
18
 
19
19
  import authJson from '../../build/auth.js';
20
20
 
21
- // Resolves the raw mock user object — LOWDEFY_DEV_USER env var first (the
22
- // `lowdefy dev --mock-user` flag sets it), then auth.dev.mockUser from the
23
- // build config. Returns just the user object; getDevSession.js turns it into
24
- // a session through the same pipeline a real sign-in uses.
21
+ // dev.mockUser is a pre-resolved caller that substitutes for the whole
22
+ // resolveAuthentication step - no auth engine, no session lookup, no
23
+ // membership wall. Its roles are authoritative. LOWDEFY_DEV_USER takes
24
+ // priority over auth.dev.mockUser from lowdefy.yaml.
25
25
  function getMockUser() {
26
26
  const mockUserJson = process.env.LOWDEFY_DEV_USER;
27
27
  let mockUser;
@@ -37,9 +37,12 @@ function getMockUser() {
37
37
  }
38
38
 
39
39
  if (!mockUser) {
40
- return undefined;
40
+ return null;
41
41
  }
42
42
 
43
+ // Deserialize to restore arrays from ~arr markers and remove other build markers
44
+ mockUser = serializer.deserialize(mockUser);
45
+
43
46
  if (authJson.configured !== true) {
44
47
  throw new Error(
45
48
  'Mock user configured but auth is not configured in lowdefy.yaml. ' +
@@ -47,8 +50,9 @@ function getMockUser() {
47
50
  );
48
51
  }
49
52
 
50
- // Deserialize to restore arrays from ~arr markers and remove other build markers
51
- return serializer.deserialize(mockUser);
53
+ // The roles/attributes floor is applied at injection by
54
+ // normalizeInjectedCaller (createLowdefyContext.js) - return the raw user.
55
+ return mockUser;
52
56
  }
53
57
 
54
58
  export default getMockUser;
@@ -14,25 +14,27 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import { getAuthConfig as getApiAuthConfig } from '@lowdefy/api';
17
+ import { getAuthStrategies } from '@lowdefy/api';
18
18
  import { getSecretsFromEnv } from '@lowdefy/node-utils';
19
19
 
20
- import adapters from '../../../build/plugins/auth/adapters.js';
21
20
  import appMeta from '../../build/appMeta.js';
22
21
  import authJson from '../../build/auth.js';
23
- import callbacks from '../../../build/plugins/auth/callbacks.js';
24
- import events from '../../../build/plugins/auth/events.js';
25
- import providers from '../../../build/plugins/auth/providers.js';
22
+ import strategyTypes from '../../../build/plugins/auth/strategies.js';
26
23
 
27
- function getAuthConfig({ logger }) {
28
- return getApiAuthConfig({
24
+ // Returns the API auth strategy verifiers (memoized in @lowdefy/api), or an
25
+ // empty list when auth is not configured - resolveAuthentication tries them
26
+ // in config order when no session resolves.
27
+ function getStrategies({ logger }) {
28
+ if (authJson.configured !== true) {
29
+ return [];
30
+ }
31
+ return getAuthStrategies({
29
32
  appMeta,
30
33
  authJson,
31
- dev: true,
32
34
  logger,
33
- plugins: { adapters, callbacks, events, providers },
35
+ plugins: { strategies: strategyTypes },
34
36
  secrets: getSecretsFromEnv(),
35
37
  });
36
38
  }
37
39
 
38
- export default getAuthConfig;
40
+ export default getStrategies;
@@ -15,12 +15,13 @@
15
15
  */
16
16
 
17
17
  // Shared between the headless renderer (getBrowser.js, which sets the cookie on
18
- // its browser context) and the dev session resolution (getHeadlessUser.js, which
18
+ // its browser context) and the dev caller resolver (getHeadlessUser.js, which
19
19
  // decodes it) so the cookie name and injected user shape live in one place.
20
20
  const HEADLESS_USER_COOKIE = 'lowdefy_headless_user';
21
21
 
22
+ // BetterAuth's session user carries `id`, never `sub`. attributes is floored to
23
+ // {} by normalizeInjectedCaller at injection, so it is not spelled out here.
22
24
  const headlessUser = {
23
- sub: 'lowdefy-headless',
24
25
  id: 'lowdefy-headless',
25
26
  name: 'Lowdefy Headless',
26
27
  roles: [],