@lowdefy/server 7.1.0 → 7.3.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.
- package/client/clientBuildImports.test.mjs +1 -0
- package/client/getShownPage.test.mjs +1 -0
- package/client/shouldReloadForTypes.test.mjs +1 -0
- package/lib/build/mobileConfig.js +26 -0
- package/lib/client/auth/AuthConfigured.jsx +75 -48
- package/lib/client/auth/createFetchCheckingBuild.test.mjs +3 -3
- package/lib/client/auth/sessionCaller.js +56 -0
- package/lib/client/createLogUsage.test.mjs +2 -2
- package/lib/server/getClientAddress.test.mjs +6 -7
- package/lib/server/log/createHandleError.test.mjs +5 -5
- package/lib/server/log/createLogger.test.mjs +3 -3
- package/lib/server/log/projectErrorForLog.js +6 -4
- package/lib/server/log/redactUrlQuery.test.mjs +1 -0
- package/lib/server/log/serializeErrorForLog.test.mjs +50 -113
- package/lib/server/sentry/captureSentryError.test.mjs +4 -7
- package/lib/server/sentry/initSentry.serverless.test.mjs +6 -6
- package/lib/server/sentry/initSentry.test.mjs +3 -3
- package/lib/server/sentry/scrubEvent.test.mjs +2 -0
- package/lowdefy/build.mjs +4 -1
- package/lowdefy/build.test.mjs +11 -13
- package/lowdefy/createCustomPluginMessagesMap.mjs +2 -4
- package/lowdefy/createCustomPluginTypesMap.mjs +39 -11
- package/lowdefy/createCustomPluginTypesMap.test.mjs +249 -0
- package/package.json +32 -33
- package/package.original.json +32 -33
- package/src/app.js +19 -2
- package/src/app.mobile.test.mjs +351 -0
- package/src/app.test.mjs +31 -27
- package/src/app.timeout.test.mjs +141 -0
- package/src/html/collectPageTypesAssets.test.mjs +1 -0
- package/src/html/getPageAssets.test.mjs +1 -0
- package/src/html/renderPage.contentSecurityPolicy.test.mjs +13 -10
- package/src/html/renderPage.test.mjs +16 -13
- package/src/html/template.test.mjs +1 -0
- package/src/initServer.test.mjs +12 -12
- package/src/lib/getPathSegments.js +16 -1
- package/src/lib/getRequestSurface.js +25 -0
- package/src/middleware/apiContext.js +7 -4
- package/src/middleware/apiContext.test.mjs +48 -30
- package/src/middleware/createSameOriginGuard.test.mjs +1 -0
- package/src/middleware/errorHandler.js +33 -45
- package/src/middleware/errorHandler.test.mjs +11 -11
- package/src/middleware/refuseOtherBuild.test.mjs +3 -3
- package/src/middleware/requestTimeout.js +7 -1
- package/src/middleware/stampBuildId.test.mjs +1 -0
- package/src/middleware/stampCaller.test.mjs +1 -0
- package/src/routes/agentBearer.test.mjs +175 -0
- package/src/routes/apiPage.js +12 -1
- package/src/routes/apiPage.test.mjs +5 -5
- package/src/routes/auth.test.mjs +6 -6
- package/src/routes/clientError.js +14 -2
- package/src/routes/clientError.test.mjs +106 -0
- package/src/routes/endpoints.js +24 -0
- package/src/routes/endpointsLink.test.mjs +112 -0
- package/src/routes/endpointsTextAnswer.test.mjs +8 -8
- package/src/routes/mcp.js +6 -0
- package/src/routes/mcp.test.mjs +23 -8
- package/src/routes/mcpMemberToken.test.mjs +8 -8
- package/src/routes/mcpProtectedResourceMetadata.test.mjs +2 -2
- package/src/routes/mobileRoot.js +30 -0
- package/src/routes/mobileSignIn.js +46 -0
- package/src/routes/mobileSignIn.test.mjs +58 -0
- package/src/routes/mobileSignInCallback.js +34 -0
- package/src/routes/mobileSignInCallback.test.mjs +51 -0
- package/src/routes/mountMobileWellKnown.js +35 -0
- package/src/routes/mountMobileWellKnown.test.mjs +79 -0
- package/src/routes/mountOauthDiscovery.test.mjs +5 -5
- package/src/routes/mountPageRoutes.js +9 -2
- package/src/routes/mountPageRoutes.test.mjs +33 -3
- package/src/routes/normalizeMcpProtocolVersionHeader.test.mjs +1 -0
- package/src/routes/requestBody.test.mjs +12 -12
- package/src/routes/websocket.js +4 -2
- package/src/routes/websocket.test.mjs +2 -2
- package/lib/server/log/maskCredentialKeys.js +0 -37
|
@@ -0,0 +1,175 @@
|
|
|
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 'fs';
|
|
18
|
+
import path from 'path';
|
|
19
|
+
import { fileURLToPath } from 'url';
|
|
20
|
+
|
|
21
|
+
import { Hono } from 'hono';
|
|
22
|
+
import { vi, afterAll, beforeEach, expect, test } from 'vitest';
|
|
23
|
+
|
|
24
|
+
// A phone shell calls /api/agent with its session as a bearer, the x-lowdefy-shell header and no
|
|
25
|
+
// cookie. The route sits behind the same apiContext middleware as /api/request and
|
|
26
|
+
// /api/endpoints, so the caller is resolved by the one resolver (resolveAuthentication) from the
|
|
27
|
+
// request's own headers, on its general (not MCP) branch. resolveAuthentication's bearer branch
|
|
28
|
+
// itself is covered in @lowdefy/api (resolveAuthentication.test.js, bearerSession.mongodb.test.js);
|
|
29
|
+
// this pins that the agent route reaches it and runs as the caller it resolves.
|
|
30
|
+
|
|
31
|
+
const sessions = { 'phone-session-token': { id: 'u-phone', roles: ['member'] } };
|
|
32
|
+
|
|
33
|
+
const mockResolveAuthentication = vi.fn(async (context, { headers }) => {
|
|
34
|
+
const authorization = headers.get('authorization') ?? '';
|
|
35
|
+
const token = authorization.startsWith('Bearer ') ? authorization.slice(7) : null;
|
|
36
|
+
context.user = sessions[token] ?? null;
|
|
37
|
+
});
|
|
38
|
+
const mockCallAgent = vi.fn(async () => ({
|
|
39
|
+
response: new Response('data: {"type":"start"}\n\ndata: [DONE]\n\n'),
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
vi.doMock('@lowdefy/api', () => ({
|
|
43
|
+
callAgent: mockCallAgent,
|
|
44
|
+
createApiContext: vi.fn(),
|
|
45
|
+
createRequestSignal: vi.fn(({ clientSignal }) => clientSignal),
|
|
46
|
+
ensureMcpOauthResource: vi.fn(async () => {}),
|
|
47
|
+
parseRequestBody: ({ text }) => JSON.parse(text),
|
|
48
|
+
resolveAuthentication: mockResolveAuthentication,
|
|
49
|
+
resolvePinnedOrganization: vi.fn(async () => {}),
|
|
50
|
+
resolveTenantPreflight: vi.fn(async () => {}),
|
|
51
|
+
}));
|
|
52
|
+
vi.doMock('../../lib/build/appMeta.js', () => ({ default: {} }));
|
|
53
|
+
vi.doMock('../../lib/build/config.js', () => ({ default: {} }));
|
|
54
|
+
vi.doMock('../../lib/build/i18n.js', () => ({ default: {} }));
|
|
55
|
+
vi.doMock('../../lib/build/logger.js', () => ({ default: { sentry: {} } }));
|
|
56
|
+
vi.doMock('../../lib/server/log/createHandleError.js', () => ({
|
|
57
|
+
default: vi.fn(() => vi.fn()),
|
|
58
|
+
}));
|
|
59
|
+
vi.doMock('../../lib/server/log/createLogger.js', () => ({
|
|
60
|
+
default: vi.fn(() => ({
|
|
61
|
+
debug: vi.fn(),
|
|
62
|
+
info: vi.fn(),
|
|
63
|
+
warn: vi.fn(),
|
|
64
|
+
error: vi.fn(),
|
|
65
|
+
})),
|
|
66
|
+
}));
|
|
67
|
+
vi.doMock('../../lib/server/fileCache.js', () => ({ default: {} }));
|
|
68
|
+
vi.doMock('../../lib/server/auth/getAuth.js', () => ({
|
|
69
|
+
default: vi.fn(() => ({ api: {} })),
|
|
70
|
+
}));
|
|
71
|
+
vi.doMock('../../lib/server/auth/getStrategies.js', () => ({
|
|
72
|
+
default: vi.fn(() => null),
|
|
73
|
+
}));
|
|
74
|
+
vi.doMock('../../lib/server/log/logRequest.js', () => ({ default: vi.fn() }));
|
|
75
|
+
vi.doMock('../../lib/server/sentry/setSentryUser.js', () => ({
|
|
76
|
+
default: vi.fn(),
|
|
77
|
+
}));
|
|
78
|
+
|
|
79
|
+
// apiContext statically imports the app build's plugin artifacts, which only exist in a built app
|
|
80
|
+
// (build/** is gitignored). The same fixtures as middleware/apiContext.test.mjs.
|
|
81
|
+
const dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
82
|
+
const pluginsDir = path.resolve(dirname, '../../build/plugins');
|
|
83
|
+
const fixtures = [
|
|
84
|
+
'agents.js',
|
|
85
|
+
'connections.js',
|
|
86
|
+
'notifications.js',
|
|
87
|
+
path.join('operators', 'server.js'),
|
|
88
|
+
path.join('operators', 'serverJsMap.js'),
|
|
89
|
+
'steps.js',
|
|
90
|
+
'websockets.js',
|
|
91
|
+
].map((file) => path.join(pluginsDir, file));
|
|
92
|
+
|
|
93
|
+
const createdFixtures = [];
|
|
94
|
+
fixtures.forEach((absolutePath) => {
|
|
95
|
+
if (!fs.existsSync(absolutePath)) {
|
|
96
|
+
fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
|
|
97
|
+
fs.writeFileSync(
|
|
98
|
+
absolutePath,
|
|
99
|
+
'export default {};\nexport const interpolateProperties = () => {};\nexport const renderEmail = () => {};\n'
|
|
100
|
+
);
|
|
101
|
+
createdFixtures.push(absolutePath);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
fixtures.forEach((absolutePath) => {
|
|
105
|
+
vi.doMock(absolutePath, () => ({
|
|
106
|
+
default: {},
|
|
107
|
+
interpolateProperties: () => {},
|
|
108
|
+
renderEmail: () => {},
|
|
109
|
+
}));
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
afterAll(() => {
|
|
113
|
+
createdFixtures.forEach((absolutePath) => fs.rmSync(absolutePath, { force: true }));
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const { default: apiContext } = await import('../middleware/apiContext.js');
|
|
117
|
+
const { default: agentHandler } = await import('./agent.js');
|
|
118
|
+
|
|
119
|
+
function createApp() {
|
|
120
|
+
const app = new Hono();
|
|
121
|
+
app.use('/api/*', apiContext());
|
|
122
|
+
app.all('/api/agent/*', agentHandler);
|
|
123
|
+
return app;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function postChat(headers) {
|
|
127
|
+
return createApp().request('/api/agent/atlas-chat/atlas?conversationId=c1', {
|
|
128
|
+
method: 'POST',
|
|
129
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
130
|
+
body: JSON.stringify({ messages: [], sharedState: { now: 'today' } }),
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
beforeEach(() => {
|
|
135
|
+
mockResolveAuthentication.mockClear();
|
|
136
|
+
mockCallAgent.mockClear();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
test('a shell chat call with a bearer session runs the agent as that caller', async () => {
|
|
140
|
+
const res = await postChat({
|
|
141
|
+
authorization: 'Bearer phone-session-token',
|
|
142
|
+
'x-lowdefy-shell': '7.4.0',
|
|
143
|
+
});
|
|
144
|
+
expect(res.status).toEqual(200);
|
|
145
|
+
expect(res.headers.get('content-type')).toEqual('text/event-stream');
|
|
146
|
+
expect(await res.text()).toEqual('data: {"type":"start"}\n\ndata: [DONE]\n\n');
|
|
147
|
+
expect(mockCallAgent).toHaveBeenCalledTimes(1);
|
|
148
|
+
const [context, params] = mockCallAgent.mock.calls[0];
|
|
149
|
+
expect(context.user).toEqual({ id: 'u-phone', roles: ['member'] });
|
|
150
|
+
expect(params).toEqual({
|
|
151
|
+
agentId: 'atlas',
|
|
152
|
+
pageId: 'atlas-chat',
|
|
153
|
+
messages: [],
|
|
154
|
+
conversationId: 'c1',
|
|
155
|
+
sharedState: { now: 'today' },
|
|
156
|
+
sharedStateReadOnly: undefined,
|
|
157
|
+
pathParams: undefined,
|
|
158
|
+
urlQuery: undefined,
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test('the agent route resolves its caller through the general branch from the raw headers', async () => {
|
|
163
|
+
await postChat({ authorization: 'Bearer phone-session-token', 'x-lowdefy-shell': '7.4.0' });
|
|
164
|
+
expect(mockResolveAuthentication).toHaveBeenCalledTimes(1);
|
|
165
|
+
const [, options] = mockResolveAuthentication.mock.calls[0];
|
|
166
|
+
expect(options.mcp).toBe(false);
|
|
167
|
+
expect(options.headers.get('authorization')).toEqual('Bearer phone-session-token');
|
|
168
|
+
expect(options.headers.get('cookie')).toBeNull();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test('a shell chat call with an unknown bearer runs the agent signed out', async () => {
|
|
172
|
+
await postChat({ authorization: 'Bearer ended-session', 'x-lowdefy-shell': '7.4.0' });
|
|
173
|
+
const [context] = mockCallAgent.mock.calls[0];
|
|
174
|
+
expect(context.user).toBeNull();
|
|
175
|
+
});
|
package/src/routes/apiPage.js
CHANGED
|
@@ -20,6 +20,7 @@ import appMeta from '../../lib/build/appMeta.js';
|
|
|
20
20
|
import authJson from '../../lib/build/auth.js';
|
|
21
21
|
import lowdefyConfig from '../../lib/build/config.js';
|
|
22
22
|
import getRequestPath from '../lib/getRequestPath.js';
|
|
23
|
+
import getRequestSurface from '../lib/getRequestSurface.js';
|
|
23
24
|
|
|
24
25
|
const basePath = lowdefyConfig.basePath ?? '';
|
|
25
26
|
|
|
@@ -34,7 +35,11 @@ async function apiPageHandler(c) {
|
|
|
34
35
|
const callbackUrl = `${basePath}/${path}${new URL(c.req.url).search}`;
|
|
35
36
|
// The client forwards its current query string on the fetch so Dynamic block
|
|
36
37
|
// resolution sees the same urlQuery as an initial HTML load.
|
|
37
|
-
const result = await getPageConfig(context, {
|
|
38
|
+
const result = await getPageConfig(context, {
|
|
39
|
+
path,
|
|
40
|
+
urlQuery: c.req.query(),
|
|
41
|
+
surface: getRequestSurface(c),
|
|
42
|
+
});
|
|
38
43
|
const { pageId, pathParams } = result;
|
|
39
44
|
if (result.status === 'unauthenticated') {
|
|
40
45
|
// The client follows this redirect with a full page load, so the login
|
|
@@ -63,6 +68,12 @@ async function apiPageHandler(c) {
|
|
|
63
68
|
403
|
|
64
69
|
);
|
|
65
70
|
}
|
|
71
|
+
if (result.status === 'wrong_surface') {
|
|
72
|
+
// The page is for the other surface: a shell opens a web page in the
|
|
73
|
+
// browser, and a browser shows its 404.
|
|
74
|
+
context.logger.info({ event: 'api_page_wrong_surface', pageId, path, surface: result.surface });
|
|
75
|
+
return c.json({ pageConfig: null, surface: result.surface }, 404);
|
|
76
|
+
}
|
|
66
77
|
if (result.status !== 'ok') {
|
|
67
78
|
context.logger.info({ event: 'api_page_not_found', pageId, path });
|
|
68
79
|
return c.json({ pageConfig: null }, 404);
|
|
@@ -15,17 +15,17 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { Hono } from 'hono';
|
|
18
|
-
import {
|
|
18
|
+
import { vi, expect, test } from 'vitest';
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
vi.doMock('../../lib/build/appMeta.js', () => ({
|
|
21
21
|
default: { buildId: 'build-abc' },
|
|
22
22
|
}));
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
vi.doMock('../../lib/build/auth.js', () => ({
|
|
25
25
|
default: { authPages: { signIn: '/auth/login', twoFactorEnrol: '/two-factor-enrol' } },
|
|
26
26
|
}));
|
|
27
27
|
|
|
28
|
-
|
|
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:
|
|
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;
|
package/src/routes/auth.test.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
|
|
17
17
|
import { serve } from '@hono/node-server';
|
|
18
18
|
import { Hono } from 'hono';
|
|
19
|
-
import {
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
default:
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
+
});
|
package/src/routes/endpoints.js
CHANGED
|
@@ -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 {
|
|
18
|
+
import { vi, beforeEach, expect, test } from 'vitest';
|
|
19
19
|
|
|
20
|
-
const mockGetEndpointConfig =
|
|
21
|
-
const mockRunWebhookEndpoint =
|
|
22
|
-
|
|
23
|
-
callEndpoint:
|
|
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:
|
|
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:
|
|
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:
|
|
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);
|