@lowdefy/server 7.1.0 → 7.2.0

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 (72) hide show
  1. package/client/clientBuildImports.test.mjs +1 -0
  2. package/client/getShownPage.test.mjs +1 -0
  3. package/client/shouldReloadForTypes.test.mjs +1 -0
  4. package/lib/build/mobileConfig.js +26 -0
  5. package/lib/client/auth/AuthConfigured.jsx +75 -48
  6. package/lib/client/auth/createFetchCheckingBuild.test.mjs +3 -3
  7. package/lib/client/auth/sessionCaller.js +56 -0
  8. package/lib/client/createLogUsage.test.mjs +2 -2
  9. package/lib/server/getClientAddress.test.mjs +6 -7
  10. package/lib/server/log/createHandleError.test.mjs +5 -5
  11. package/lib/server/log/createLogger.test.mjs +3 -3
  12. package/lib/server/log/projectErrorForLog.js +6 -4
  13. package/lib/server/log/redactUrlQuery.test.mjs +1 -0
  14. package/lib/server/log/serializeErrorForLog.test.mjs +50 -113
  15. package/lib/server/sentry/captureSentryError.test.mjs +4 -7
  16. package/lib/server/sentry/initSentry.serverless.test.mjs +6 -6
  17. package/lib/server/sentry/initSentry.test.mjs +3 -3
  18. package/lib/server/sentry/scrubEvent.test.mjs +2 -0
  19. package/lowdefy/build.mjs +4 -1
  20. package/lowdefy/build.test.mjs +11 -13
  21. package/lowdefy/createCustomPluginMessagesMap.mjs +2 -4
  22. package/lowdefy/createCustomPluginTypesMap.mjs +39 -11
  23. package/lowdefy/createCustomPluginTypesMap.test.mjs +249 -0
  24. package/package.json +31 -32
  25. package/package.original.json +31 -32
  26. package/src/app.js +19 -2
  27. package/src/app.mobile.test.mjs +351 -0
  28. package/src/app.test.mjs +31 -27
  29. package/src/html/collectPageTypesAssets.test.mjs +1 -0
  30. package/src/html/getPageAssets.test.mjs +1 -0
  31. package/src/html/renderPage.contentSecurityPolicy.test.mjs +13 -10
  32. package/src/html/renderPage.test.mjs +16 -13
  33. package/src/html/template.test.mjs +1 -0
  34. package/src/initServer.test.mjs +12 -12
  35. package/src/lib/getPathSegments.js +16 -1
  36. package/src/lib/getRequestSurface.js +25 -0
  37. package/src/middleware/apiContext.js +7 -4
  38. package/src/middleware/apiContext.test.mjs +48 -30
  39. package/src/middleware/createSameOriginGuard.test.mjs +1 -0
  40. package/src/middleware/errorHandler.js +33 -45
  41. package/src/middleware/errorHandler.test.mjs +11 -11
  42. package/src/middleware/refuseOtherBuild.test.mjs +3 -3
  43. package/src/middleware/stampBuildId.test.mjs +1 -0
  44. package/src/middleware/stampCaller.test.mjs +1 -0
  45. package/src/routes/agentBearer.test.mjs +175 -0
  46. package/src/routes/apiPage.js +12 -1
  47. package/src/routes/apiPage.test.mjs +5 -5
  48. package/src/routes/auth.test.mjs +6 -6
  49. package/src/routes/clientError.js +14 -2
  50. package/src/routes/clientError.test.mjs +106 -0
  51. package/src/routes/endpoints.js +24 -0
  52. package/src/routes/endpointsLink.test.mjs +112 -0
  53. package/src/routes/endpointsTextAnswer.test.mjs +8 -8
  54. package/src/routes/mcp.js +6 -0
  55. package/src/routes/mcp.test.mjs +23 -8
  56. package/src/routes/mcpMemberToken.test.mjs +8 -8
  57. package/src/routes/mcpProtectedResourceMetadata.test.mjs +2 -2
  58. package/src/routes/mobileRoot.js +30 -0
  59. package/src/routes/mobileSignIn.js +46 -0
  60. package/src/routes/mobileSignIn.test.mjs +58 -0
  61. package/src/routes/mobileSignInCallback.js +34 -0
  62. package/src/routes/mobileSignInCallback.test.mjs +51 -0
  63. package/src/routes/mountMobileWellKnown.js +35 -0
  64. package/src/routes/mountMobileWellKnown.test.mjs +79 -0
  65. package/src/routes/mountOauthDiscovery.test.mjs +5 -5
  66. package/src/routes/mountPageRoutes.js +9 -2
  67. package/src/routes/mountPageRoutes.test.mjs +33 -3
  68. package/src/routes/normalizeMcpProtocolVersionHeader.test.mjs +1 -0
  69. package/src/routes/requestBody.test.mjs +12 -12
  70. package/src/routes/websocket.js +4 -2
  71. package/src/routes/websocket.test.mjs +2 -2
  72. package/lib/server/log/maskCredentialKeys.js +0 -37
@@ -15,17 +15,17 @@
15
15
  */
16
16
 
17
17
  import { Hono } from 'hono';
18
- import { jest } from '@jest/globals';
18
+ import { vi, expect, test } from 'vitest';
19
19
 
20
- jest.unstable_mockModule('../../lib/build/appMeta.js', () => ({
20
+ vi.doMock('../../lib/build/appMeta.js', () => ({
21
21
  default: { buildId: 'build-abc' },
22
22
  }));
23
23
 
24
- jest.unstable_mockModule('../../lib/build/auth.js', () => ({
24
+ vi.doMock('../../lib/build/auth.js', () => ({
25
25
  default: { authPages: { signIn: '/auth/login', twoFactorEnrol: '/two-factor-enrol' } },
26
26
  }));
27
27
 
28
- jest.unstable_mockModule('../../lib/build/config.js', () => ({
28
+ vi.doMock('../../lib/build/config.js', () => ({
29
29
  default: { basePath: '' },
30
30
  }));
31
31
 
@@ -51,7 +51,7 @@ function createApp({
51
51
  c.set('lowdefyContext', {
52
52
  authEnforcement: { pagesProtectedByDefault },
53
53
  authorizeOutcome: () => outcome,
54
- logger: { debug: jest.fn(), info: jest.fn(), error: jest.fn() },
54
+ logger: { debug: vi.fn(), info: vi.fn(), error: vi.fn() },
55
55
  readConfigFile: async (file) => {
56
56
  if (file === 'routes.json') return routes;
57
57
  return pages[file.slice('pages/'.length, -'.json'.length)] ?? null;
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { serve } from '@hono/node-server';
18
18
  import { Hono } from 'hono';
19
- import { jest } from '@jest/globals';
19
+ import { vi, afterAll, beforeAll, expect, test } from 'vitest';
20
20
 
21
21
  // The auth engine is replaced by one that echoes what reached it, so the route
22
22
  // is exercised on a real @hono/node-server connection: the request the engine
@@ -29,16 +29,16 @@ const echoAuth = {
29
29
  body: await request.text(),
30
30
  }),
31
31
  };
32
- jest.unstable_mockModule('../../lib/build/auth.js', () => ({ default: { configured: true } }));
33
- jest.unstable_mockModule('../../lib/build/config.js', () => ({ default: {} }));
34
- jest.unstable_mockModule('../../lib/server/auth/getAuth.js', () => ({
35
- default: jest.fn(() => echoAuth),
32
+ vi.doMock('../../lib/build/auth.js', () => ({ default: { configured: true } }));
33
+ vi.doMock('../../lib/build/config.js', () => ({ default: {} }));
34
+ vi.doMock('../../lib/server/auth/getAuth.js', () => ({
35
+ default: vi.fn(() => echoAuth),
36
36
  }));
37
37
 
38
38
  const { default: authMiddleware } = await import('./auth.js');
39
39
  const { default: getClientAddress } = await import('../../lib/server/getClientAddress.js');
40
40
 
41
- const logger = { debug: jest.fn(), error: jest.fn(), info: jest.fn(), warn: jest.fn() };
41
+ const logger = { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
42
42
 
43
43
  let server;
44
44
  let baseUrl;
@@ -17,9 +17,13 @@
17
17
  import { logClientError, parseRequestBody } from '@lowdefy/api';
18
18
 
19
19
  import captureSentryError from '../../lib/server/sentry/captureSentryError.js';
20
+ import getRequestSurface from '../lib/getRequestSurface.js';
20
21
  import createSameOriginGuard from '../middleware/createSameOriginGuard.js';
21
22
 
22
- const guardSameOrigin = createSameOriginGuard();
23
+ // No Origin is allowed: a phone shell's fetch sends none, and refusing it lost
24
+ // every native fault. A browser on another site always sends Origin or
25
+ // Sec-Fetch-Site on a cross-site POST, so it is still refused.
26
+ const guardSameOrigin = createSameOriginGuard({ allowNoOrigin: true });
23
27
 
24
28
  async function clientErrorHandler(c) {
25
29
  if (c.req.method !== 'POST') {
@@ -39,7 +43,15 @@ async function clientErrorHandler(c) {
39
43
  if (body?.['~e']) {
40
44
  delete body['~e'].received;
41
45
  }
42
- const { error, ...response } = await logClientError(context, body);
46
+ // The log line says whether a phone shell ('mobile', with its shell version)
47
+ // or a browser ('web') reported the fault.
48
+ const surface = getRequestSurface(c);
49
+ const surfaceFields =
50
+ surface === 'mobile' ? { surface, shell: c.req.header('x-lowdefy-shell') } : { surface };
51
+ const { error, ...response } = await logClientError(
52
+ { ...context, logger: context.logger.child(surfaceFields) },
53
+ body
54
+ );
43
55
 
44
56
  // Capture client error to Sentry (no-op if Sentry not configured)
45
57
  captureSentryError({
@@ -0,0 +1,106 @@
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 { vi, beforeEach, expect, test } from 'vitest';
19
+
20
+ const mockLogClientError = vi.fn();
21
+ const mockCaptureSentryError = vi.fn();
22
+ const mockChild = vi.fn((fields) => ({ fields }));
23
+
24
+ // The same-origin rule is the real one from @lowdefy/api; only the logging is mocked.
25
+ const api = await import('@lowdefy/api');
26
+ vi.doMock('@lowdefy/api', () => ({
27
+ ...api,
28
+ logClientError: mockLogClientError,
29
+ }));
30
+ vi.doMock('../../lib/server/sentry/captureSentryError.js', () => ({
31
+ default: mockCaptureSentryError,
32
+ }));
33
+
34
+ const { default: clientErrorHandler } = await import('./clientError.js');
35
+
36
+ function post(headers) {
37
+ const app = new Hono();
38
+ app.use('*', async (c, next) => {
39
+ c.set('lowdefyContext', { logger: { child: mockChild } });
40
+ await next();
41
+ });
42
+ app.all('/api/client-error', clientErrorHandler);
43
+ return app.request('/api/client-error', {
44
+ method: 'POST',
45
+ headers: { 'content-type': 'application/json', ...headers },
46
+ body: JSON.stringify({ error: { message: 'Block failed' } }),
47
+ });
48
+ }
49
+
50
+ beforeEach(() => {
51
+ mockLogClientError.mockReset();
52
+ mockCaptureSentryError.mockReset();
53
+ mockChild.mockClear();
54
+ mockLogClientError.mockResolvedValue({
55
+ error: { name: 'BlockError', message: 'Block failed' },
56
+ source: 'pages/home.yaml:12',
57
+ });
58
+ });
59
+
60
+ test('clientError accepts an error from a phone shell, which sends no origin', async () => {
61
+ const res = await post({ host: 'app.test', 'x-lowdefy-shell': '7.1.0' });
62
+ expect(res.status).toEqual(200);
63
+ expect(mockLogClientError).toHaveBeenCalledTimes(1);
64
+ expect(mockCaptureSentryError).toHaveBeenCalledTimes(1);
65
+ });
66
+
67
+ test('clientError accepts an error from the app page itself', async () => {
68
+ const res = await post({
69
+ host: 'app.test',
70
+ origin: 'https://app.test',
71
+ 'sec-fetch-site': 'same-origin',
72
+ });
73
+ expect(res.status).toEqual(200);
74
+ });
75
+
76
+ test('clientError refuses an error a page on another site posts', async () => {
77
+ const res = await post({ host: 'app.test', origin: 'https://attacker.example' });
78
+ expect(res.status).toEqual(403);
79
+ expect(mockLogClientError).not.toHaveBeenCalled();
80
+ expect(mockCaptureSentryError).not.toHaveBeenCalled();
81
+ });
82
+
83
+ test('clientError refuses a cross-site post that sends only sec-fetch-site', async () => {
84
+ const res = await post({ host: 'app.test', 'sec-fetch-site': 'cross-site' });
85
+ expect(res.status).toEqual(403);
86
+ expect(mockLogClientError).not.toHaveBeenCalled();
87
+ });
88
+
89
+ test('clientError logs a phone shell error as mobile with its shell version', async () => {
90
+ await post({ host: 'app.test', 'x-lowdefy-shell': '7.1.0' });
91
+ expect(mockChild).toHaveBeenCalledWith({ surface: 'mobile', shell: '7.1.0' });
92
+ const [logContext] = mockLogClientError.mock.calls[0];
93
+ expect(logContext.logger).toEqual({ fields: { surface: 'mobile', shell: '7.1.0' } });
94
+ });
95
+
96
+ test('clientError logs a browser error as web', async () => {
97
+ await post({ host: 'app.test', origin: 'https://app.test' });
98
+ expect(mockChild).toHaveBeenCalledWith({ surface: 'web' });
99
+ });
100
+
101
+ test('clientError answers 405 to a request that is not a POST', async () => {
102
+ const app = new Hono();
103
+ app.all('/api/client-error', clientErrorHandler);
104
+ const res = await app.request('/api/client-error', { method: 'GET' });
105
+ expect(res.status).toEqual(405);
106
+ });
@@ -18,12 +18,36 @@ import {
18
18
  callEndpoint,
19
19
  getEndpointConfig,
20
20
  parseRequestBody,
21
+ runLinkEndpoint,
21
22
  runWebhookEndpoint,
22
23
  } from '@lowdefy/api';
24
+ import { type } from '@lowdefy/helpers';
23
25
 
24
26
  import getPathSegments from '../lib/getPathSegments.js';
25
27
 
28
+ // A GET serves a link endpoint (`link: true`): typically an <img src> or a download link, sent
29
+ // by the browser with the session cookie and no Lowdefy headers. The routine runs as that caller
30
+ // and the answer is a 302 to the URL it returns, or a status with no body. The noStore middleware
31
+ // sets Cache-Control: private, no-store on it, so a redirect to a short-lived URL is never cached.
32
+ async function linkHandler(c) {
33
+ const context = c.get('lowdefyContext');
34
+ const { status, location, body } = await runLinkEndpoint(context, {
35
+ segments: getPathSegments(c, '/api/endpoints/'),
36
+ query: c.req.query(),
37
+ });
38
+ if (status === 302) {
39
+ return c.redirect(location, 302);
40
+ }
41
+ if (type.isNone(body)) {
42
+ return c.body(null, status);
43
+ }
44
+ return c.json(body, status);
45
+ }
46
+
26
47
  async function endpointsHandler(c) {
48
+ if (c.req.method === 'GET') {
49
+ return linkHandler(c);
50
+ }
27
51
  if (c.req.method !== 'POST') {
28
52
  // A wrong-method request is client-caused: answer 405 rather than raising a
29
53
  // fault that would be logged at error level and answered with a 500.
@@ -0,0 +1,112 @@
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 { vi, beforeEach, expect, test } from 'vitest';
19
+
20
+ const mockRunLinkEndpoint = vi.fn();
21
+ const mockCallEndpoint = vi.fn();
22
+ vi.doMock('@lowdefy/api', () => ({
23
+ callEndpoint: mockCallEndpoint,
24
+ getEndpointConfig: vi.fn().mockRejectedValue(new Error('API Endpoint does not exist.')),
25
+ parseRequestBody: vi.fn(() => ({ payload: {} })),
26
+ runLinkEndpoint: mockRunLinkEndpoint,
27
+ runWebhookEndpoint: vi.fn(),
28
+ }));
29
+
30
+ const { default: endpointsHandler } = await import('./endpoints.js');
31
+ const { default: noStore } = await import('../middleware/noStore.js');
32
+ const { default: stampCaller } = await import('../middleware/stampCaller.js');
33
+ const { default: refuseOtherBuild } = await import('../middleware/refuseOtherBuild.js');
34
+
35
+ const logger = { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
36
+
37
+ // The middleware app.js puts on /api/endpoints/*, so a plain browser image GET is checked
38
+ // against what they do with no Lowdefy headers.
39
+ function createApp() {
40
+ const app = new Hono();
41
+ app.use('*', async (c, next) => {
42
+ c.set('lowdefyContext', { logger, handleError: vi.fn(), user: { id: 'user_1' } });
43
+ await next();
44
+ });
45
+ app.use('/api/endpoints/*', noStore());
46
+ app.use('/api/endpoints/*', stampCaller());
47
+ app.all('/api/endpoints/*', refuseOtherBuild({ buildId: 'build_1' }), endpointsHandler);
48
+ return app;
49
+ }
50
+
51
+ beforeEach(() => {
52
+ mockRunLinkEndpoint.mockReset();
53
+ });
54
+
55
+ test('a GET answers 302 to the link, not stored by any cache', async () => {
56
+ mockRunLinkEndpoint.mockResolvedValue({
57
+ status: 302,
58
+ location: 'https://bucket.s3.amazonaws.com/x.png?X-Amz-Signature=sig',
59
+ });
60
+ const res = await createApp().request('/api/endpoints/files/x.png', { headers: {} });
61
+ expect(res.status).toBe(302);
62
+ expect(res.headers.get('location')).toBe(
63
+ 'https://bucket.s3.amazonaws.com/x.png?X-Amz-Signature=sig'
64
+ );
65
+ expect(res.headers.get('cache-control')).toBe('private, no-store');
66
+ expect(await res.text()).toBe('');
67
+ });
68
+
69
+ test('a GET passes the decoded path segments and the query to runLinkEndpoint', async () => {
70
+ mockRunLinkEndpoint.mockResolvedValue({ status: 302, location: '/x.png' });
71
+ await createApp().request('/api/endpoints/a/b/log-events/2024/x%20y+z.png?v=2&w=a+b');
72
+ expect(mockRunLinkEndpoint).toHaveBeenCalledWith(expect.anything(), {
73
+ segments: ['a', 'b', 'log-events', '2024', 'x y+z.png'],
74
+ query: { v: '2', w: 'a b' },
75
+ });
76
+ });
77
+
78
+ test('a GET keeps an encoded slash and percent sign inside one segment', async () => {
79
+ mockRunLinkEndpoint.mockResolvedValue({ status: 302, location: '/x.png' });
80
+ await createApp().request('/api/endpoints/files/a%2Fb%25.png');
81
+ expect(mockRunLinkEndpoint).toHaveBeenCalledWith(expect.anything(), {
82
+ segments: ['files', 'a/b%.png'],
83
+ query: {},
84
+ });
85
+ });
86
+
87
+ test('a refused GET answers its status with no body', async () => {
88
+ mockRunLinkEndpoint.mockResolvedValue({ status: 401 });
89
+ const res = await createApp().request('/api/endpoints/files/x.png');
90
+ expect(res.status).toBe(401);
91
+ expect(res.headers.get('cache-control')).toBe('private, no-store');
92
+ expect(await res.text()).toBe('');
93
+ });
94
+
95
+ test('a GET that names no link endpoint answers 404 with an error body', async () => {
96
+ mockRunLinkEndpoint.mockResolvedValue({ status: 404, body: { error: 'Not found.' } });
97
+ const res = await createApp().request('/api/endpoints/unknown/x.png');
98
+ expect(res.status).toBe(404);
99
+ expect(await res.json()).toEqual({ error: 'Not found.' });
100
+ });
101
+
102
+ test('any method but GET and POST answers 405', async () => {
103
+ const res = await createApp().request('/api/endpoints/files/x.png', { method: 'PUT' });
104
+ expect(res.status).toBe(405);
105
+ expect(mockRunLinkEndpoint).not.toHaveBeenCalled();
106
+ });
107
+
108
+ test('a GET with a malformed percent escape answers 400 without running the link', async () => {
109
+ const res = await createApp().request('/api/endpoints/files/100%ZZ.png');
110
+ expect(res.status).toBe(400);
111
+ expect(mockRunLinkEndpoint).not.toHaveBeenCalled();
112
+ });
@@ -15,25 +15,25 @@
15
15
  */
16
16
 
17
17
  import { Hono } from 'hono';
18
- import { jest } from '@jest/globals';
18
+ import { vi, beforeEach, expect, test } from 'vitest';
19
19
 
20
- const mockGetEndpointConfig = jest.fn();
21
- const mockRunWebhookEndpoint = jest.fn();
22
- jest.unstable_mockModule('@lowdefy/api', () => ({
23
- callEndpoint: jest.fn(),
20
+ const mockGetEndpointConfig = vi.fn();
21
+ const mockRunWebhookEndpoint = vi.fn();
22
+ vi.doMock('@lowdefy/api', () => ({
23
+ callEndpoint: vi.fn(),
24
24
  getEndpointConfig: mockGetEndpointConfig,
25
- parseRequestBody: jest.fn(),
25
+ parseRequestBody: vi.fn(),
26
26
  runWebhookEndpoint: mockRunWebhookEndpoint,
27
27
  }));
28
28
 
29
29
  const { default: endpointsHandler } = await import('./endpoints.js');
30
30
 
31
- const logger = { debug: jest.fn(), error: jest.fn(), info: jest.fn(), warn: jest.fn() };
31
+ const logger = { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() };
32
32
 
33
33
  function createApp() {
34
34
  const app = new Hono();
35
35
  app.use('*', async (c, next) => {
36
- c.set('lowdefyContext', { logger, handleError: jest.fn() });
36
+ c.set('lowdefyContext', { logger, handleError: vi.fn() });
37
37
  await next();
38
38
  });
39
39
  app.all('/api/endpoints/*', endpointsHandler);
package/src/routes/mcp.js CHANGED
@@ -102,6 +102,12 @@ async function mcpHandler(c) {
102
102
  });
103
103
  }
104
104
  }
105
+ // The server is stateless and pushes nothing, so it offers no event stream:
106
+ // the MCP spec's answer to a GET is then 405. Opening one would hold the
107
+ // request, and on a serverless host its function, until the host's time limit.
108
+ if (c.req.method === 'GET') {
109
+ return c.json({ error: 'Method not allowed.' }, 405, { Allow: 'POST' });
110
+ }
105
111
  const server = await createMcpServer({ context });
106
112
  const transport = new StreamableHTTPTransport();
107
113
  await server.connect(transport);
@@ -15,20 +15,20 @@
15
15
  */
16
16
 
17
17
  import { Hono } from 'hono';
18
- import { jest } from '@jest/globals';
18
+ import { vi, afterAll, beforeEach, expect, test } from 'vitest';
19
19
 
20
20
  // The real URI helpers drive the challenge strings, so the header assertions
21
21
  // below exercise the actual BETTER_AUTH_URL derivation - only createMcpServer
22
22
  // is stubbed out.
23
23
  const uriHelpers = await import('@lowdefy/api/routes/mcp/getMcpUri.js');
24
24
 
25
- const mockCreateMcpServer = jest.fn();
26
- jest.unstable_mockModule('@lowdefy/api', () => ({
25
+ const mockCreateMcpServer = vi.fn();
26
+ vi.doMock('@lowdefy/api', () => ({
27
27
  ...uriHelpers,
28
28
  createMcpServer: mockCreateMcpServer,
29
29
  }));
30
30
 
31
- jest.unstable_mockModule('@hono/mcp', () => ({
31
+ vi.doMock('@hono/mcp', () => ({
32
32
  StreamableHTTPTransport: class {
33
33
  handleRequest() {
34
34
  return new Response(JSON.stringify({ served: true }), {
@@ -40,7 +40,7 @@ jest.unstable_mockModule('@hono/mcp', () => ({
40
40
  }));
41
41
 
42
42
  const mockAuthJson = { configured: true, oauthProvider: { consentPage: '/oauth/consent' } };
43
- jest.unstable_mockModule('../../lib/build/auth.js', () => ({
43
+ vi.doMock('../../lib/build/auth.js', () => ({
44
44
  default: mockAuthJson,
45
45
  }));
46
46
 
@@ -48,7 +48,7 @@ const { default: mcpHandler } = await import('./mcp.js');
48
48
 
49
49
  const originalBetterAuthUrl = process.env.BETTER_AUTH_URL;
50
50
 
51
- const mockReadConfigFile = jest.fn();
51
+ const mockReadConfigFile = vi.fn();
52
52
 
53
53
  let contextOverrides;
54
54
 
@@ -57,7 +57,7 @@ function createApp() {
57
57
  app.use('*', async (c, next) => {
58
58
  c.set('lowdefyContext', {
59
59
  config: { basePath: '' },
60
- logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
60
+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
61
61
  readConfigFile: mockReadConfigFile,
62
62
  ...contextOverrides,
63
63
  });
@@ -73,7 +73,7 @@ beforeEach(() => {
73
73
  contextOverrides = {};
74
74
  mockReadConfigFile.mockReset();
75
75
  mockCreateMcpServer.mockReset();
76
- mockCreateMcpServer.mockResolvedValue({ connect: jest.fn() });
76
+ mockCreateMcpServer.mockResolvedValue({ connect: vi.fn() });
77
77
  mockReadConfigFile.mockResolvedValue({ configured: true, hasPublicTool: true, endpoints: [] });
78
78
  });
79
79
 
@@ -213,3 +213,18 @@ test('mcpHandler serves openly with no envelope when oauthProvider is not config
213
213
  expect(res.status).toEqual(200);
214
214
  expect(await res.json()).toEqual({ served: true });
215
215
  });
216
+
217
+ test('mcpHandler answers a GET with 405, since the stateless server offers no event stream', async () => {
218
+ contextOverrides.mcpAuth = { tokenStatus: 'valid' };
219
+ const res = await createApp().request('/api/mcp', { method: 'GET' });
220
+ expect(res.status).toEqual(405);
221
+ expect(res.headers.get('Allow')).toEqual('POST');
222
+ expect(await res.json()).toEqual({ error: 'Method not allowed.' });
223
+ expect(mockCreateMcpServer).not.toHaveBeenCalled();
224
+ });
225
+
226
+ test('mcpHandler challenges a GET with an invalid token before answering 405', async () => {
227
+ contextOverrides.mcpAuth = { tokenStatus: 'invalid', parseableJwt: true };
228
+ const res = await createApp().request('/api/mcp', { method: 'GET' });
229
+ expect(res.status).toEqual(401);
230
+ });
@@ -15,20 +15,20 @@
15
15
  */
16
16
 
17
17
  import { Hono } from 'hono';
18
- import { jest } from '@jest/globals';
18
+ import { vi, afterAll, beforeEach, expect, test } from 'vitest';
19
19
 
20
20
  // The real URI helpers drive the challenge strings, so the header assertions
21
21
  // below exercise the actual BETTER_AUTH_URL derivation - only createMcpServer
22
22
  // is stubbed out.
23
23
  const uriHelpers = await import('@lowdefy/api/routes/mcp/getMcpUri.js');
24
24
 
25
- const mockCreateMcpServer = jest.fn();
26
- jest.unstable_mockModule('@lowdefy/api', () => ({
25
+ const mockCreateMcpServer = vi.fn();
26
+ vi.doMock('@lowdefy/api', () => ({
27
27
  ...uriHelpers,
28
28
  createMcpServer: mockCreateMcpServer,
29
29
  }));
30
30
 
31
- jest.unstable_mockModule('@hono/mcp', () => ({
31
+ vi.doMock('@hono/mcp', () => ({
32
32
  StreamableHTTPTransport: class {
33
33
  handleRequest() {
34
34
  return new Response(JSON.stringify({ served: true }), {
@@ -40,7 +40,7 @@ jest.unstable_mockModule('@hono/mcp', () => ({
40
40
  }));
41
41
 
42
42
  const mockAuthJson = { configured: true, oauthProvider: { consentPage: '/oauth/consent' } };
43
- jest.unstable_mockModule('../../lib/build/auth.js', () => ({
43
+ vi.doMock('../../lib/build/auth.js', () => ({
44
44
  default: mockAuthJson,
45
45
  }));
46
46
 
@@ -48,7 +48,7 @@ const { default: mcpHandler } = await import('./mcp.js');
48
48
 
49
49
  const originalBetterAuthUrl = process.env.BETTER_AUTH_URL;
50
50
 
51
- const mockReadConfigFile = jest.fn();
51
+ const mockReadConfigFile = vi.fn();
52
52
 
53
53
  let contextOverrides;
54
54
 
@@ -57,7 +57,7 @@ function createApp() {
57
57
  app.use('*', async (c, next) => {
58
58
  c.set('lowdefyContext', {
59
59
  config: { basePath: '' },
60
- logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
60
+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },
61
61
  readConfigFile: mockReadConfigFile,
62
62
  ...contextOverrides,
63
63
  });
@@ -73,7 +73,7 @@ beforeEach(() => {
73
73
  contextOverrides = {};
74
74
  mockReadConfigFile.mockReset();
75
75
  mockCreateMcpServer.mockReset();
76
- mockCreateMcpServer.mockResolvedValue({ connect: jest.fn() });
76
+ mockCreateMcpServer.mockResolvedValue({ connect: vi.fn() });
77
77
  mockReadConfigFile.mockResolvedValue({ configured: true, hasPublicTool: true, endpoints: [] });
78
78
  });
79
79
 
@@ -15,9 +15,9 @@
15
15
  */
16
16
 
17
17
  import { Hono } from 'hono';
18
- import { jest } from '@jest/globals';
18
+ import { vi, afterAll, beforeEach, expect, test } from 'vitest';
19
19
 
20
- jest.unstable_mockModule('../../lib/build/config.js', () => ({
20
+ vi.doMock('../../lib/build/config.js', () => ({
21
21
  default: { basePath: '' },
22
22
  }));
23
23
 
@@ -0,0 +1,30 @@
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 { getMobileRootConfig } from '@lowdefy/api';
18
+
19
+ // The root config a shell syncs on start (getMobileRootConfig), filtered to
20
+ // the caller. An app without a mobile key has no shell, so it answers 404.
21
+ async function mobileRootHandler(c) {
22
+ const context = c.get('lowdefyContext');
23
+ const rootConfig = await getMobileRootConfig(context);
24
+ if (rootConfig === null) {
25
+ return c.json({ name: 'NotFoundError', message: 'This app has no mobile config.' }, 404);
26
+ }
27
+ return c.json(rootConfig);
28
+ }
29
+
30
+ export default mobileRootHandler;
@@ -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 { handleMobileSignIn } from '@lowdefy/api';
18
+ import { type } from '@lowdefy/helpers';
19
+
20
+ import authJson from '../../lib/build/auth.js';
21
+ import getAuth from '../../lib/server/auth/getAuth.js';
22
+ import lowdefyConfig from '../../lib/build/config.js';
23
+ import themeConfig from '../../lib/build/theme.js';
24
+
25
+ // GET and POST /auth/mobile - the sign-in page a phone shell opens in a system
26
+ // sheet. handleMobileSignIn sends the person through the app's sign-in page,
27
+ // asks them to confirm (GET), and on Continue (POST) returns a one-time token
28
+ // for a new phone session, bound to the shell's PKCE code challenge, to the
29
+ // shell's scheme (iOS) or app link (Android). The page takes the app theme's
30
+ // primary colour. An app without a mobile section has no such page, so the
31
+ // path falls through to the app's own pages.
32
+ function mobileSignInHandler(c, next) {
33
+ if (type.isNone(authJson.mobile)) {
34
+ return next();
35
+ }
36
+ const { logger } = c.get('lowdefyContext');
37
+ return handleMobileSignIn({
38
+ auth: authJson.configured === true ? getAuth({ logger }) : null,
39
+ authJson,
40
+ basePath: lowdefyConfig.basePath ?? '',
41
+ primaryColor: themeConfig.antd?.token?.colorPrimary,
42
+ request: c.req.raw,
43
+ });
44
+ }
45
+
46
+ export default mobileSignInHandler;