@lowdefy/server-dev 0.0.0-experimental-20260804101357 → 0.0.0-experimental-20260805140807

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.
@@ -98,27 +98,23 @@ function Session({ children, reloadSuppressedRef, serverUser }) {
98
98
  return children({ roles: [], ...session.user }, resolvedUserRef);
99
99
  }
100
100
  if (resolved.id !== session.user.id) {
101
- // The ref has not caught up with a changed session user (an impersonation
102
- // switch between the session refetch and the /api/user result). Render
103
- // the last resolved caller rather than a caller with no roles - blocks
104
- // re-evaluate operators on render, so a role-guarded page would act on
105
- // roles: []. UpdateSession closes the window when it lands the new
106
- // caller; a flow that swaps the session user without chaining it leaves
107
- // the previous caller rendered until the next page load.
101
+ // The ref has not caught up with a changed session user - a sign-in as a
102
+ // different person lands between the session refetch and the /api/user
103
+ // result. Render the last resolved caller whole rather than mixing the new
104
+ // session user with the previous person's resolved fields, or falling back
105
+ // to a caller with no roles - blocks re-evaluate operators on render, so a
106
+ // role-guarded page would act on an empty role list. UpdateSession closes
107
+ // the window when it lands the new caller; a flow that changes the session
108
+ // user without chaining it leaves the previous caller rendered until the
109
+ // next page load.
108
110
  return children(resolved, resolvedUserRef);
109
111
  }
110
- // The resolved caller contributes every field the session user lacks: roles
111
- // (the active member row), attributes (the merged bag), and
112
- // activeOrganizationId / impersonatedBy (session row, not session user).
113
- // impersonatedBy is carried only when present, matching the server, which
114
- // omits it rather than setting it to undefined.
115
- const user = {
116
- ...session.user,
117
- roles: resolved.roles,
118
- attributes: resolved.attributes,
119
- activeOrganizationId: resolved.activeOrganizationId,
120
- ...('impersonatedBy' in resolved ? { impersonatedBy: resolved.impersonatedBy } : {}),
121
- };
112
+ // _user is one object with one meaning on both sides: the resolved caller is
113
+ // spread whole, so every field resolveAuthentication emits is readable in app
114
+ // config without this file naming it. session.user is the floor - the client
115
+ // store may hold a fresher one than the ref, and the resolved object wins
116
+ // wherever both carry a key.
117
+ const user = { ...session.user, ...resolved };
122
118
  return children(user, resolvedUserRef);
123
119
  }
124
120
 
@@ -163,18 +159,14 @@ function AuthConfigured({ authConfig, children, serverUser }) {
163
159
  // addPasskey runs the WebAuthn browser ceremony itself - options fetch,
164
160
  // authenticator prompt, verification.
165
161
  addPasskey: (params) => authClient.passkey.addPasskey(params),
166
- cancelInvitation: (params) => authClient.organization.cancelInvitation(params),
167
162
  changePassword: (params) => authClient.changePassword(sessionScoped(params)),
168
163
  deletePasskey: (params) => authClient.passkey.deletePasskey(params),
169
- impersonateUser: (params) => authClient.admin.impersonateUser(sessionScoped(params)),
170
- inviteMember: (params) => authClient.organization.inviteMember(params),
171
164
  leaveOrganization: (params) => authClient.organization.leave(sessionScoped(params)),
172
165
  phoneNumberRequestPasswordReset: (params) =>
173
166
  authClient.phoneNumber.requestPasswordReset(params),
174
167
  phoneNumberResetPassword: (params) => authClient.phoneNumber.resetPassword(params),
175
168
  phoneNumberSendOtp: (params) => authClient.phoneNumber.sendOtp(params),
176
169
  phoneNumberVerify: (params) => authClient.phoneNumber.verify(params),
177
- removeMember: (params) => authClient.organization.removeMember(sessionScoped(params)),
178
170
  requestPasswordReset: (params) => authClient.requestPasswordReset(params),
179
171
  resetPassword: (params) => authClient.resetPassword(params),
180
172
  revokeOtherSessions: () => authClient.revokeOtherSessions(sessionScoped()),
@@ -188,13 +180,12 @@ function AuthConfigured({ authConfig, children, serverUser }) {
188
180
  signInSocial: (params) => authClient.signIn.social(params),
189
181
  signOut: () => authClient.signOut(),
190
182
  signUpEmail: (params) => authClient.signUp.email(params),
191
- stopImpersonating: () => authClient.admin.stopImpersonating(sessionScoped()),
192
183
  twoFactorDisable: (params) => authClient.twoFactor.disable(sessionScoped(params)),
193
184
  twoFactorEnable: (params) => authClient.twoFactor.enable(sessionScoped(params)),
185
+ twoFactorGenerateBackupCodes: (params) =>
186
+ authClient.twoFactor.generateBackupCodes(sessionScoped(params)),
194
187
  twoFactorVerifyBackupCode: (params) => authClient.twoFactor.verifyBackupCode(params),
195
188
  twoFactorVerifyTotp: (params) => authClient.twoFactor.verifyTotp(params),
196
- updateMemberRole: (params) => authClient.organization.updateMemberRole(params),
197
- updateOrganization: (params) => authClient.organization.update(params),
198
189
  };
199
190
  return (
200
191
  <Session reloadSuppressedRef={reloadSuppressedRef} serverUser={serverUser}>
@@ -24,15 +24,11 @@ function AuthNotConfigured({ authConfig, children }) {
24
24
  user: null,
25
25
  acceptInvitation: authNotConfigured,
26
26
  addPasskey: authNotConfigured,
27
- cancelInvitation: authNotConfigured,
28
27
  changePassword: authNotConfigured,
29
28
  deletePasskey: authNotConfigured,
30
29
  getResolvedUser: authNotConfigured,
31
30
  getSession: authNotConfigured,
32
- impersonateUser: authNotConfigured,
33
- inviteMember: authNotConfigured,
34
31
  leaveOrganization: authNotConfigured,
35
- removeMember: authNotConfigured,
36
32
  requestPasswordReset: authNotConfigured,
37
33
  resetPassword: authNotConfigured,
38
34
  revokeOtherSessions: authNotConfigured,
@@ -44,13 +40,11 @@ function AuthNotConfigured({ authConfig, children }) {
44
40
  signInSocial: authNotConfigured,
45
41
  signOut: authNotConfigured,
46
42
  signUpEmail: authNotConfigured,
47
- stopImpersonating: authNotConfigured,
48
43
  twoFactorDisable: authNotConfigured,
49
44
  twoFactorEnable: authNotConfigured,
45
+ twoFactorGenerateBackupCodes: authNotConfigured,
50
46
  twoFactorVerifyBackupCode: authNotConfigured,
51
47
  twoFactorVerifyTotp: authNotConfigured,
52
- updateMemberRole: authNotConfigured,
53
- updateOrganization: authNotConfigured,
54
48
  };
55
49
 
56
50
  return children(auth);
@@ -73,15 +73,18 @@ async function fetchPageConfig(url) {
73
73
  if (res.status === 404) {
74
74
  return null;
75
75
  }
76
- if (res.status === 401) {
77
- // Logged-out navigation to a protected page - Page renders a redirect
78
- // screen and full-loads to the login page so it can return here after
79
- // sign-in. Returning a settled value (never a parked promise) keeps the
80
- // SWR key healthy: if the navigation is dropped, the tab still recovers
81
- // on the next reload event or via the manual link on the redirect screen.
76
+ if (res.status === 401 || res.status === 403) {
77
+ // 401: logged-out navigation to a protected page. 403: authorised but second
78
+ // factor not yet enrolled. Page renders a redirect screen and full-loads to
79
+ // the destination so it can return here afterwards. Returning a settled value
80
+ // (never a parked promise) keeps the SWR key healthy: if the navigation is
81
+ // dropped, the tab still recovers on the next reload event or via the manual
82
+ // link on the redirect screen.
82
83
  const { redirect } = await res.json();
83
84
  const authRedirect = redirect ?? `${basePath}/404`;
84
- console.warn(`Lowdefy dev: "${url}" returned 401 - redirecting to "${authRedirect}".`);
85
+ console.warn(
86
+ `Lowdefy dev: "${url}" returned ${res.status} - redirecting to "${authRedirect}".`
87
+ );
85
88
  return { authRedirect };
86
89
  }
87
90
  const data = await res.json();
@@ -16,7 +16,7 @@
16
16
 
17
17
  import fs from 'fs';
18
18
  import path from 'path';
19
- import { ReservedKeyError, serializer, setKey, type } from '@lowdefy/helpers';
19
+ import { isReserved, serializer, setKey, type } from '@lowdefy/helpers';
20
20
 
21
21
  import { getConfigDirectory } from './checkpointPaths.js';
22
22
 
@@ -90,14 +90,13 @@ function readEntries({ dir, subdir }) {
90
90
  .filter((fileName) => fileName.endsWith('.json'))
91
91
  .forEach((fileName) => {
92
92
  const id = fileName.slice(0, -'.json'.length);
93
- try {
94
- setKey(entries, id, readJsonFile(path.join(entriesDir, fileName), null));
95
- } catch (error) {
96
- if (!(error instanceof ReservedKeyError)) throw error;
97
- // A checkpoint directory is on-disk state a developer can edit by hand.
98
- // A reserved file name can't round-trip through the entries map, so skip
99
- // it rather than fail the whole checkpoint load.
93
+ // A checkpoint directory is on-disk state a developer can edit by hand.
94
+ // A reserved file name can't round-trip through the entries map, so skip
95
+ // it rather than fail the whole checkpoint load.
96
+ if (isReserved(id)) {
97
+ return;
100
98
  }
99
+ setKey(entries, id, readJsonFile(path.join(entriesDir, fileName), null));
101
100
  });
102
101
  return entries;
103
102
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/server-dev",
3
- "version": "0.0.0-experimental-20260804101357",
3
+ "version": "0.0.0-experimental-20260805140807",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -44,39 +44,39 @@
44
44
  "@hono/mcp": "0.3.0",
45
45
  "@hono/node-server": "2.0.4",
46
46
  "@hono/vite-dev-server": "0.26.0",
47
- "@lowdefy/actions-core": "0.0.0-experimental-20260804101357",
48
- "@lowdefy/api": "0.0.0-experimental-20260804101357",
49
- "@lowdefy/block-utils": "0.0.0-experimental-20260804101357",
50
- "@lowdefy/blocks-aggrid": "0.0.0-experimental-20260804101357",
51
- "@lowdefy/blocks-antd": "0.0.0-experimental-20260804101357",
52
- "@lowdefy/blocks-antd-x": "0.0.0-experimental-20260804101357",
53
- "@lowdefy/blocks-basic": "0.0.0-experimental-20260804101357",
54
- "@lowdefy/blocks-captcha": "0.0.0-experimental-20260804101357",
55
- "@lowdefy/blocks-echarts": "0.0.0-experimental-20260804101357",
56
- "@lowdefy/blocks-loaders": "0.0.0-experimental-20260804101357",
57
- "@lowdefy/blocks-markdown": "0.0.0-experimental-20260804101357",
58
- "@lowdefy/blocks-tiptap": "0.0.0-experimental-20260804101357",
59
- "@lowdefy/build": "0.0.0-experimental-20260804101357",
60
- "@lowdefy/client": "0.0.0-experimental-20260804101357",
61
- "@lowdefy/connection-axios-http": "0.0.0-experimental-20260804101357",
62
- "@lowdefy/connection-mongodb": "0.0.0-experimental-20260804101357",
63
- "@lowdefy/docs-content": "0.0.0-experimental-20260804101357",
64
- "@lowdefy/engine": "0.0.0-experimental-20260804101357",
65
- "@lowdefy/errors": "0.0.0-experimental-20260804101357",
66
- "@lowdefy/helpers": "0.0.0-experimental-20260804101357",
67
- "@lowdefy/layout": "0.0.0-experimental-20260804101357",
68
- "@lowdefy/logger": "0.0.0-experimental-20260804101357",
69
- "@lowdefy/node-utils": "0.0.0-experimental-20260804101357",
70
- "@lowdefy/operators-change-case": "0.0.0-experimental-20260804101357",
71
- "@lowdefy/operators-dayjs": "0.0.0-experimental-20260804101357",
72
- "@lowdefy/operators-diff": "0.0.0-experimental-20260804101357",
73
- "@lowdefy/operators-js": "0.0.0-experimental-20260804101357",
74
- "@lowdefy/operators-mql": "0.0.0-experimental-20260804101357",
75
- "@lowdefy/operators-nunjucks": "0.0.0-experimental-20260804101357",
76
- "@lowdefy/operators-uuid": "0.0.0-experimental-20260804101357",
77
- "@lowdefy/operators-yaml": "0.0.0-experimental-20260804101357",
78
- "@lowdefy/plugin-better-auth": "0.0.0-experimental-20260804101357",
79
- "@lowdefy/websockets-core": "0.0.0-experimental-20260804101357",
47
+ "@lowdefy/actions-core": "0.0.0-experimental-20260805140807",
48
+ "@lowdefy/api": "0.0.0-experimental-20260805140807",
49
+ "@lowdefy/block-utils": "0.0.0-experimental-20260805140807",
50
+ "@lowdefy/blocks-aggrid": "0.0.0-experimental-20260805140807",
51
+ "@lowdefy/blocks-antd": "0.0.0-experimental-20260805140807",
52
+ "@lowdefy/blocks-antd-x": "0.0.0-experimental-20260805140807",
53
+ "@lowdefy/blocks-basic": "0.0.0-experimental-20260805140807",
54
+ "@lowdefy/blocks-captcha": "0.0.0-experimental-20260805140807",
55
+ "@lowdefy/blocks-echarts": "0.0.0-experimental-20260805140807",
56
+ "@lowdefy/blocks-loaders": "0.0.0-experimental-20260805140807",
57
+ "@lowdefy/blocks-markdown": "0.0.0-experimental-20260805140807",
58
+ "@lowdefy/blocks-tiptap": "0.0.0-experimental-20260805140807",
59
+ "@lowdefy/build": "0.0.0-experimental-20260805140807",
60
+ "@lowdefy/client": "0.0.0-experimental-20260805140807",
61
+ "@lowdefy/connection-axios-http": "0.0.0-experimental-20260805140807",
62
+ "@lowdefy/connection-mongodb": "0.0.0-experimental-20260805140807",
63
+ "@lowdefy/docs-content": "0.0.0-experimental-20260805140807",
64
+ "@lowdefy/engine": "0.0.0-experimental-20260805140807",
65
+ "@lowdefy/errors": "0.0.0-experimental-20260805140807",
66
+ "@lowdefy/helpers": "0.0.0-experimental-20260805140807",
67
+ "@lowdefy/layout": "0.0.0-experimental-20260805140807",
68
+ "@lowdefy/logger": "0.0.0-experimental-20260805140807",
69
+ "@lowdefy/node-utils": "0.0.0-experimental-20260805140807",
70
+ "@lowdefy/operators-change-case": "0.0.0-experimental-20260805140807",
71
+ "@lowdefy/operators-dayjs": "0.0.0-experimental-20260805140807",
72
+ "@lowdefy/operators-diff": "0.0.0-experimental-20260805140807",
73
+ "@lowdefy/operators-js": "0.0.0-experimental-20260805140807",
74
+ "@lowdefy/operators-mql": "0.0.0-experimental-20260805140807",
75
+ "@lowdefy/operators-nunjucks": "0.0.0-experimental-20260805140807",
76
+ "@lowdefy/operators-uuid": "0.0.0-experimental-20260805140807",
77
+ "@lowdefy/operators-yaml": "0.0.0-experimental-20260805140807",
78
+ "@lowdefy/plugin-better-auth": "0.0.0-experimental-20260805140807",
79
+ "@lowdefy/websockets-core": "0.0.0-experimental-20260805140807",
80
80
  "@modelcontextprotocol/sdk": "1.29.0",
81
81
  "@tailwindcss/postcss": "4.3.1",
82
82
  "@vitejs/plugin-react": "6.0.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/server-dev",
3
- "version": "0.0.0-experimental-20260804101357",
3
+ "version": "0.0.0-experimental-20260805140807",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -50,39 +50,39 @@
50
50
  "@hono/mcp": "0.3.0",
51
51
  "@hono/node-server": "2.0.4",
52
52
  "@hono/vite-dev-server": "0.26.0",
53
- "@lowdefy/actions-core": "0.0.0-experimental-20260804101357",
54
- "@lowdefy/api": "0.0.0-experimental-20260804101357",
55
- "@lowdefy/block-utils": "0.0.0-experimental-20260804101357",
56
- "@lowdefy/blocks-aggrid": "0.0.0-experimental-20260804101357",
57
- "@lowdefy/blocks-antd": "0.0.0-experimental-20260804101357",
58
- "@lowdefy/blocks-antd-x": "0.0.0-experimental-20260804101357",
59
- "@lowdefy/blocks-basic": "0.0.0-experimental-20260804101357",
60
- "@lowdefy/blocks-captcha": "0.0.0-experimental-20260804101357",
61
- "@lowdefy/blocks-echarts": "0.0.0-experimental-20260804101357",
62
- "@lowdefy/blocks-loaders": "0.0.0-experimental-20260804101357",
63
- "@lowdefy/blocks-markdown": "0.0.0-experimental-20260804101357",
64
- "@lowdefy/blocks-tiptap": "0.0.0-experimental-20260804101357",
65
- "@lowdefy/build": "0.0.0-experimental-20260804101357",
66
- "@lowdefy/client": "0.0.0-experimental-20260804101357",
67
- "@lowdefy/connection-axios-http": "0.0.0-experimental-20260804101357",
68
- "@lowdefy/connection-mongodb": "0.0.0-experimental-20260804101357",
69
- "@lowdefy/docs-content": "0.0.0-experimental-20260804101357",
70
- "@lowdefy/engine": "0.0.0-experimental-20260804101357",
71
- "@lowdefy/errors": "0.0.0-experimental-20260804101357",
72
- "@lowdefy/helpers": "0.0.0-experimental-20260804101357",
73
- "@lowdefy/layout": "0.0.0-experimental-20260804101357",
74
- "@lowdefy/logger": "0.0.0-experimental-20260804101357",
75
- "@lowdefy/node-utils": "0.0.0-experimental-20260804101357",
76
- "@lowdefy/operators-change-case": "0.0.0-experimental-20260804101357",
77
- "@lowdefy/operators-dayjs": "0.0.0-experimental-20260804101357",
78
- "@lowdefy/operators-diff": "0.0.0-experimental-20260804101357",
79
- "@lowdefy/operators-js": "0.0.0-experimental-20260804101357",
80
- "@lowdefy/operators-mql": "0.0.0-experimental-20260804101357",
81
- "@lowdefy/operators-nunjucks": "0.0.0-experimental-20260804101357",
82
- "@lowdefy/operators-uuid": "0.0.0-experimental-20260804101357",
83
- "@lowdefy/operators-yaml": "0.0.0-experimental-20260804101357",
84
- "@lowdefy/plugin-better-auth": "0.0.0-experimental-20260804101357",
85
- "@lowdefy/websockets-core": "0.0.0-experimental-20260804101357",
53
+ "@lowdefy/actions-core": "0.0.0-experimental-20260805140807",
54
+ "@lowdefy/api": "0.0.0-experimental-20260805140807",
55
+ "@lowdefy/block-utils": "0.0.0-experimental-20260805140807",
56
+ "@lowdefy/blocks-aggrid": "0.0.0-experimental-20260805140807",
57
+ "@lowdefy/blocks-antd": "0.0.0-experimental-20260805140807",
58
+ "@lowdefy/blocks-antd-x": "0.0.0-experimental-20260805140807",
59
+ "@lowdefy/blocks-basic": "0.0.0-experimental-20260805140807",
60
+ "@lowdefy/blocks-captcha": "0.0.0-experimental-20260805140807",
61
+ "@lowdefy/blocks-echarts": "0.0.0-experimental-20260805140807",
62
+ "@lowdefy/blocks-loaders": "0.0.0-experimental-20260805140807",
63
+ "@lowdefy/blocks-markdown": "0.0.0-experimental-20260805140807",
64
+ "@lowdefy/blocks-tiptap": "0.0.0-experimental-20260805140807",
65
+ "@lowdefy/build": "0.0.0-experimental-20260805140807",
66
+ "@lowdefy/client": "0.0.0-experimental-20260805140807",
67
+ "@lowdefy/connection-axios-http": "0.0.0-experimental-20260805140807",
68
+ "@lowdefy/connection-mongodb": "0.0.0-experimental-20260805140807",
69
+ "@lowdefy/docs-content": "0.0.0-experimental-20260805140807",
70
+ "@lowdefy/engine": "0.0.0-experimental-20260805140807",
71
+ "@lowdefy/errors": "0.0.0-experimental-20260805140807",
72
+ "@lowdefy/helpers": "0.0.0-experimental-20260805140807",
73
+ "@lowdefy/layout": "0.0.0-experimental-20260805140807",
74
+ "@lowdefy/logger": "0.0.0-experimental-20260805140807",
75
+ "@lowdefy/node-utils": "0.0.0-experimental-20260805140807",
76
+ "@lowdefy/operators-change-case": "0.0.0-experimental-20260805140807",
77
+ "@lowdefy/operators-dayjs": "0.0.0-experimental-20260805140807",
78
+ "@lowdefy/operators-diff": "0.0.0-experimental-20260805140807",
79
+ "@lowdefy/operators-js": "0.0.0-experimental-20260805140807",
80
+ "@lowdefy/operators-mql": "0.0.0-experimental-20260805140807",
81
+ "@lowdefy/operators-nunjucks": "0.0.0-experimental-20260805140807",
82
+ "@lowdefy/operators-uuid": "0.0.0-experimental-20260805140807",
83
+ "@lowdefy/operators-yaml": "0.0.0-experimental-20260805140807",
84
+ "@lowdefy/plugin-better-auth": "0.0.0-experimental-20260805140807",
85
+ "@lowdefy/websockets-core": "0.0.0-experimental-20260805140807",
86
86
  "@modelcontextprotocol/sdk": "1.29.0",
87
87
  "@tailwindcss/postcss": "4.3.1",
88
88
  "@vitejs/plugin-react": "6.0.2",
@@ -51,7 +51,7 @@ function renderDevPage(c, { basePath = '' }) {
51
51
  configColorMode
52
52
  )};var db=${safeScriptJson(darkBg)};var lb=${safeScriptJson(
53
53
  lightBg
54
- )};var d;if(c==="dark")d=true;else if(c==="light")d=false;else{try{var p=localStorage.getItem("lowdefy_darkMode");if(p==="dark")d=true;else if(p==="light")d=false;else d=window.matchMedia("(prefers-color-scheme:dark)").matches}catch(e){d=window.matchMedia("(prefers-color-scheme:dark)").matches}}var bg=d?db:lb;if(bg)document.documentElement.style.backgroundColor=bg})();`;
54
+ )};var d;if(c==="dark")d=true;else if(c==="light")d=false;else{try{var p=localStorage.getItem("lowdefy_darkMode");if(p==="dark")d=true;else if(p==="light")d=false;else d=window.matchMedia("(prefers-color-scheme:dark)").matches}catch(e){d=window.matchMedia("(prefers-color-scheme:dark)").matches}}var bg=d?db:lb;document.documentElement.style.colorScheme=d?"dark":"light";if(bg)document.documentElement.style.backgroundColor=bg})();`;
55
55
 
56
56
  const html = `<!DOCTYPE html>
57
57
  <html class="lowdefy">
@@ -33,6 +33,18 @@ function createErrorHandler({ basePath = '', logger }) {
33
33
  }
34
34
  return c.text('Unauthorized', 401);
35
35
  }
36
+ // An authorized caller who has not enrolled a second factor under
37
+ // auth.twoFactor.required. 403, not 401 - a 401 reads to the client as a dead
38
+ // session and bounces the user to sign-in, which is the loop the gate exists to
39
+ // avoid. Expected traffic under required: true, so one warning line and no
40
+ // Sentry capture, exactly as for AuthenticationError.
41
+ if (error.name === 'TwoFactorEnrolmentRequiredError') {
42
+ logger.warn(`Two-factor enrolment required: ${c.req.method} ${c.req.path}`);
43
+ if (path.startsWith('/api/')) {
44
+ return c.json({ name: error.name, message: error.message }, 403);
45
+ }
46
+ return c.text('Two-factor enrolment required', 403);
47
+ }
36
48
  const context = c.get('lowdefyContext');
37
49
  if (context) {
38
50
  await context.handleError(error);
@@ -55,6 +55,13 @@ function createAuthenticationError(message) {
55
55
  return error;
56
56
  }
57
57
 
58
+ function createTwoFactorEnrolmentRequiredError(message) {
59
+ const error = new Error(message);
60
+ error.name = 'TwoFactorEnrolmentRequiredError';
61
+ error.received = SECRET;
62
+ return error;
63
+ }
64
+
58
65
  // Two Error levels, each with a stack (every Error has one) and a recognisable
59
66
  // `received`, plus a configKey the policy keeps.
60
67
  function createErrorWithCause() {
@@ -105,6 +112,51 @@ test('errorHandler returns text Unauthorized at 401 for an AuthenticationError o
105
112
  expect(logger.warn).toHaveBeenCalledTimes(1);
106
113
  });
107
114
 
115
+ test('errorHandler returns 403 with only name and message for a TwoFactorEnrolmentRequiredError on an api path', async () => {
116
+ const logger = createLogger();
117
+ const context = { handleError: jest.fn() };
118
+ const res = await createApp({
119
+ context,
120
+ error: createTwoFactorEnrolmentRequiredError('Two-factor enrolment required.'),
121
+ logger,
122
+ }).request('/api/request/getUsers');
123
+
124
+ expect(res.status).toEqual(403);
125
+ expect(await res.json()).toEqual({
126
+ name: 'TwoFactorEnrolmentRequiredError',
127
+ message: 'Two-factor enrolment required.',
128
+ });
129
+ expect(logger.warn).toHaveBeenCalledTimes(1);
130
+ expect(logger.warn.mock.calls[0][0]).toMatch(/Two-factor enrolment required/);
131
+ expect(logger.error).not.toHaveBeenCalled();
132
+ expect(context.handleError).not.toHaveBeenCalled();
133
+ });
134
+
135
+ test('errorHandler does not send a TwoFactorEnrolmentRequiredError through the redactor', async () => {
136
+ const res = await createApp({
137
+ error: createTwoFactorEnrolmentRequiredError('Two-factor enrolment required.'),
138
+ logger: createLogger(),
139
+ }).request('/api/request/getUsers');
140
+
141
+ const body = await res.json();
142
+ expect(body['~e']).toBeUndefined();
143
+ });
144
+
145
+ test('errorHandler returns text at 403 for a TwoFactorEnrolmentRequiredError on a page path', async () => {
146
+ const logger = createLogger();
147
+ const context = { handleError: jest.fn() };
148
+ const res = await createApp({
149
+ context,
150
+ error: createTwoFactorEnrolmentRequiredError('Two-factor enrolment required.'),
151
+ logger,
152
+ }).request('/home');
153
+
154
+ expect(res.status).toEqual(403);
155
+ expect(await res.text()).toEqual('Two-factor enrolment required');
156
+ expect(logger.warn).toHaveBeenCalledTimes(1);
157
+ expect(context.handleError).not.toHaveBeenCalled();
158
+ });
159
+
108
160
  test('errorHandler returns 500 with the serialized error envelope on an api path', async () => {
109
161
  const res = await createApp({
110
162
  error: createErrorWithCause(),
@@ -28,6 +28,7 @@ const basePath = lowdefyConfig.basePath ?? '';
28
28
  // 200 { installing: true, packages } — plugin install in progress, client polls
29
29
  // 500 { buildError: true, errors, message, source } — build failed
30
30
  // 401 { redirect } — logged-out navigation to a protected page
31
+ // 403 { redirect } — authorised but second factor not yet enrolled
31
32
  // 404 'Page not found.'
32
33
  // 200 pageConfig (+ _warnings)
33
34
  async function jitPageHandler(c) {
@@ -89,6 +90,23 @@ async function jitPageHandler(c) {
89
90
  401
90
91
  );
91
92
  }
93
+ if (result.status === 'enrol_required') {
94
+ // 403, not the 401 the signed-out branch above uses: a 401 is the client's
95
+ // dead-session signal and would bounce the user to sign-in, which is the loop
96
+ // the enrolment gate exists to avoid.
97
+ const callbackUrl = `${basePath}/${pageId}`;
98
+ context.logger.debug(
99
+ `Page config request for "${pageId}" resolved enrol_required - returning a two-factor enrolment redirect.`
100
+ );
101
+ return c.json(
102
+ {
103
+ redirect: `${basePath}${authJson.authPages.twoFactorEnrol}?callbackUrl=${encodeURIComponent(
104
+ callbackUrl
105
+ )}`,
106
+ },
107
+ 403
108
+ );
109
+ }
92
110
  if (result.status !== 'ok') {
93
111
  return c.text('Page not found.', 404);
94
112
  }
@@ -0,0 +1,89 @@
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 { Hono } from 'hono';
18
+ import { jest } from '@jest/globals';
19
+
20
+ const mockGetPageConfig = jest.fn();
21
+ jest.unstable_mockModule('@lowdefy/api', () => ({
22
+ getPageConfig: mockGetPageConfig,
23
+ }));
24
+
25
+ // No JIT build work in these tests — the route's build branch is exercised
26
+ // elsewhere; here we only drive the getPageConfig status fork.
27
+ jest.unstable_mockModule('../../lib/server/jitPageBuilder.js', () => ({
28
+ default: jest.fn(async () => undefined),
29
+ }));
30
+
31
+ jest.unstable_mockModule('../../lib/build/auth.js', () => ({
32
+ default: { authPages: { signIn: '/auth/login', twoFactorEnrol: '/two-factor-enrol' } },
33
+ }));
34
+
35
+ jest.unstable_mockModule('../../lib/build/config.js', () => ({
36
+ default: { basePath: '' },
37
+ }));
38
+
39
+ const { default: jitPageHandler } = await import('./jitPage.js');
40
+
41
+ function createApp() {
42
+ const app = new Hono();
43
+ app.use('*', async (c, next) => {
44
+ c.set('lowdefyContext', {
45
+ buildDirectory: '/build',
46
+ configDirectory: '/config',
47
+ logger: { debug: jest.fn(), info: jest.fn(), error: jest.fn() },
48
+ handleError: jest.fn(),
49
+ });
50
+ await next();
51
+ });
52
+ app.all('/api/page/*', jitPageHandler);
53
+ return app;
54
+ }
55
+
56
+ afterEach(() => {
57
+ mockGetPageConfig.mockReset();
58
+ });
59
+
60
+ test('jitPageHandler redirects to the two-factor enrolment page with a 403 when enrol_required', async () => {
61
+ mockGetPageConfig.mockResolvedValue({ status: 'enrol_required' });
62
+ const res = await createApp().request('/api/page/dashboard');
63
+ expect(res.status).toEqual(403);
64
+ const body = await res.json();
65
+ expect(body).toEqual({ redirect: '/two-factor-enrol?callbackUrl=%2Fdashboard' });
66
+ });
67
+
68
+ test('jitPageHandler still returns a 401 sign-in redirect when unauthenticated', async () => {
69
+ mockGetPageConfig.mockResolvedValue({ status: 'unauthenticated' });
70
+ const res = await createApp().request('/api/page/dashboard');
71
+ expect(res.status).toEqual(401);
72
+ const body = await res.json();
73
+ expect(body).toEqual({ redirect: '/auth/login?callbackUrl=%2Fdashboard' });
74
+ });
75
+
76
+ test('jitPageHandler still returns a 404 when the page is not found', async () => {
77
+ mockGetPageConfig.mockResolvedValue({ status: 'not_found' });
78
+ const res = await createApp().request('/api/page/dashboard');
79
+ expect(res.status).toEqual(404);
80
+ expect(await res.text()).toEqual('Page not found.');
81
+ });
82
+
83
+ test('jitPageHandler returns the pageConfig when status is ok', async () => {
84
+ mockGetPageConfig.mockResolvedValue({ status: 'ok', pageConfig: { id: 'dashboard' } });
85
+ const res = await createApp().request('/api/page/dashboard');
86
+ expect(res.status).toEqual(200);
87
+ const body = await res.json();
88
+ expect(body).toEqual({ id: 'dashboard' });
89
+ });