@lowdefy/server 7.0.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.
- 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 +5 -1
- package/lowdefy/build.test.mjs +31 -13
- package/lowdefy/createCustomPluginMessagesMap.mjs +2 -4
- package/lowdefy/createCustomPluginTypesMap.mjs +39 -11
- package/lowdefy/createCustomPluginTypesMap.test.mjs +249 -0
- package/package.json +31 -32
- package/package.original.json +31 -32
- package/src/app.js +19 -2
- package/src/app.mobile.test.mjs +351 -0
- package/src/app.test.mjs +31 -27
- 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/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
|
@@ -14,12 +14,27 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { HTTPException } from 'hono/http-exception';
|
|
18
|
+
|
|
17
19
|
// Splits the rest of a catch-all route into decoded segments, independent of
|
|
18
20
|
// any configured basePath. Mirrors the Next.js [...param] query arrays —
|
|
19
21
|
// nested ids (slashes in pageId or endpointId) are real.
|
|
22
|
+
// A malformed percent escape (`%ZZ`, a bare `%`) is the caller's own URL, so it answers 400, not
|
|
23
|
+
// the 500 decodeURIComponent's URIError would raise.
|
|
24
|
+
function decodeSegment(segment) {
|
|
25
|
+
try {
|
|
26
|
+
return decodeURIComponent(segment);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error instanceof URIError) {
|
|
29
|
+
throw new HTTPException(400, { message: 'Malformed URL path.' });
|
|
30
|
+
}
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
20
35
|
function getPathSegments(c, prefix) {
|
|
21
36
|
const rest = c.req.path.split(prefix)[1] ?? '';
|
|
22
|
-
return rest.split('/').filter(Boolean).map(
|
|
37
|
+
return rest.split('/').filter(Boolean).map(decodeSegment);
|
|
23
38
|
}
|
|
24
39
|
|
|
25
40
|
export default getPathSegments;
|
|
@@ -0,0 +1,25 @@
|
|
|
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 { type } from '@lowdefy/helpers';
|
|
18
|
+
|
|
19
|
+
// A mobile shell sends x-lowdefy-shell on its requests; a browser never does.
|
|
20
|
+
// The surface picks which pages a page request may serve (getPageConfig).
|
|
21
|
+
function getRequestSurface(c) {
|
|
22
|
+
return type.isNone(c.req.header('x-lowdefy-shell')) ? 'web' : 'mobile';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export default getRequestSurface;
|
|
@@ -128,6 +128,13 @@ function apiContext({ clientAddressHeader } = {}) {
|
|
|
128
128
|
websockets,
|
|
129
129
|
};
|
|
130
130
|
context.handleError = createHandleError({ context });
|
|
131
|
+
// Set as soon as the context can sink an error: the auth steps below can throw, and the
|
|
132
|
+
// error handler reads the context back to log a fault with the request id and its location
|
|
133
|
+
// rather than raw.
|
|
134
|
+
c.set('lowdefyContext', context);
|
|
135
|
+
// Echo the request id so clients and proxies can quote it when reporting
|
|
136
|
+
// a failure, and it can be matched to the rid on the server log lines.
|
|
137
|
+
c.header('x-request-id', context.rid);
|
|
131
138
|
// Resolved once per request: the auth route hands it to BetterAuth, and the
|
|
132
139
|
// request log records it.
|
|
133
140
|
context.clientAddress = getClientAddress({
|
|
@@ -170,10 +177,6 @@ function apiContext({ clientAddressHeader } = {}) {
|
|
|
170
177
|
void resolveTenantPreflight(context, {
|
|
171
178
|
captureError: (error) => captureSentryError({ error, context }),
|
|
172
179
|
});
|
|
173
|
-
c.set('lowdefyContext', context);
|
|
174
|
-
// Echo the request id so clients and proxies can quote it when reporting
|
|
175
|
-
// a failure, and it can be matched to the rid on the server log lines.
|
|
176
|
-
c.header('x-request-id', context.rid);
|
|
177
180
|
const startTime = performance.now();
|
|
178
181
|
// Handler errors never reject next() — Hono's compose routes them to the
|
|
179
182
|
// app-level error handler at the throwing dispatch level, so by the time
|
|
@@ -19,48 +19,48 @@ import path from 'path';
|
|
|
19
19
|
import { fileURLToPath } from 'url';
|
|
20
20
|
|
|
21
21
|
import { Hono } from 'hono';
|
|
22
|
-
import {
|
|
22
|
+
import { vi, afterAll, expect, test } from 'vitest';
|
|
23
23
|
|
|
24
24
|
const secret = 'planted-apicontext-secret';
|
|
25
25
|
process.env.LOWDEFY_SECRET_TEST = secret;
|
|
26
26
|
|
|
27
|
-
|
|
28
|
-
createApiContext:
|
|
29
|
-
createRequestSignal:
|
|
27
|
+
vi.doMock('@lowdefy/api', () => ({
|
|
28
|
+
createApiContext: vi.fn(),
|
|
29
|
+
createRequestSignal: vi.fn(({ clientSignal, timeoutSignal }) =>
|
|
30
30
|
AbortSignal.any([clientSignal, timeoutSignal].filter(Boolean))
|
|
31
31
|
),
|
|
32
32
|
// Returns what the server passes, so the test reads the auth-hook system context inputs.
|
|
33
|
-
createSystemContext:
|
|
34
|
-
ensureMcpOauthResource:
|
|
35
|
-
resolveAuthentication:
|
|
36
|
-
resolvePinnedOrganization:
|
|
37
|
-
resolveTenantPreflight:
|
|
33
|
+
createSystemContext: vi.fn((options) => options),
|
|
34
|
+
ensureMcpOauthResource: vi.fn(async () => {}),
|
|
35
|
+
resolveAuthentication: vi.fn(async () => {}),
|
|
36
|
+
resolvePinnedOrganization: vi.fn(async () => {}),
|
|
37
|
+
resolveTenantPreflight: vi.fn(async () => {}),
|
|
38
38
|
}));
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
default:
|
|
39
|
+
vi.doMock('../../lib/build/appMeta.js', () => ({ default: {} }));
|
|
40
|
+
vi.doMock('../../lib/build/config.js', () => ({ default: {} }));
|
|
41
|
+
vi.doMock('../../lib/build/i18n.js', () => ({ default: {} }));
|
|
42
|
+
vi.doMock('../../lib/build/logger.js', () => ({ default: { sentry: {} } }));
|
|
43
|
+
vi.doMock('../../lib/server/log/createHandleError.js', () => ({
|
|
44
|
+
default: vi.fn(() => vi.fn()),
|
|
45
45
|
}));
|
|
46
|
-
|
|
47
|
-
default:
|
|
48
|
-
debug:
|
|
49
|
-
info:
|
|
50
|
-
warn:
|
|
51
|
-
error:
|
|
46
|
+
vi.doMock('../../lib/server/log/createLogger.js', () => ({
|
|
47
|
+
default: vi.fn(() => ({
|
|
48
|
+
debug: vi.fn(),
|
|
49
|
+
info: vi.fn(),
|
|
50
|
+
warn: vi.fn(),
|
|
51
|
+
error: vi.fn(),
|
|
52
52
|
})),
|
|
53
53
|
}));
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
default:
|
|
54
|
+
vi.doMock('../../lib/server/fileCache.js', () => ({ default: {} }));
|
|
55
|
+
vi.doMock('../../lib/server/auth/getAuth.js', () => ({
|
|
56
|
+
default: vi.fn(() => null),
|
|
57
57
|
}));
|
|
58
|
-
|
|
59
|
-
default:
|
|
58
|
+
vi.doMock('../../lib/server/auth/getStrategies.js', () => ({
|
|
59
|
+
default: vi.fn(() => null),
|
|
60
60
|
}));
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
default:
|
|
61
|
+
vi.doMock('../../lib/server/log/logRequest.js', () => ({ default: vi.fn() }));
|
|
62
|
+
vi.doMock('../../lib/server/sentry/setSentryUser.js', () => ({
|
|
63
|
+
default: vi.fn(),
|
|
64
64
|
}));
|
|
65
65
|
|
|
66
66
|
// apiContext statically imports the app build's plugin artifacts, which only
|
|
@@ -94,7 +94,7 @@ fixtures.forEach(({ absolutePath, content }) => {
|
|
|
94
94
|
// A checkout that has built an app already holds real artifacts here, which import plugins this
|
|
95
95
|
// package does not depend on, so the stubs are also mocked over whatever is on disk.
|
|
96
96
|
fixtures.forEach(({ absolutePath }) => {
|
|
97
|
-
|
|
97
|
+
vi.doMock(absolutePath, () => ({
|
|
98
98
|
default: {},
|
|
99
99
|
interpolateProperties: () => {},
|
|
100
100
|
renderEmail: () => {},
|
|
@@ -176,3 +176,21 @@ test('a request that answers within the timeout leaves its signal unaborted', as
|
|
|
176
176
|
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
177
177
|
expect(signal.aborted).toBe(false);
|
|
178
178
|
});
|
|
179
|
+
|
|
180
|
+
test('a fault in authentication reaches the error handler with the request context', async () => {
|
|
181
|
+
const { resolveAuthentication } = await import('@lowdefy/api');
|
|
182
|
+
resolveAuthentication.mockRejectedValueOnce(new Error('Session store is down.'));
|
|
183
|
+
const app = new Hono();
|
|
184
|
+
let seen;
|
|
185
|
+
app.onError((error, c) => {
|
|
186
|
+
seen = c.get('lowdefyContext');
|
|
187
|
+
return c.text('failed', 500);
|
|
188
|
+
});
|
|
189
|
+
app.use('*', apiContext());
|
|
190
|
+
app.get('/api/ping', (c) => c.text('ok'));
|
|
191
|
+
const response = await app.request('/api/ping', { headers: { 'x-request-id': 'rid-1' } });
|
|
192
|
+
expect(response.status).toBe(500);
|
|
193
|
+
expect(seen?.rid).toBe('rid-1');
|
|
194
|
+
expect(seen?.handleError).toBeInstanceOf(Function);
|
|
195
|
+
expect(response.headers.get('x-request-id')).toBe('rid-1');
|
|
196
|
+
});
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { Hono } from 'hono';
|
|
18
18
|
|
|
19
19
|
import createSameOriginGuard from './createSameOriginGuard.js';
|
|
20
|
+
import { expect, test } from 'vitest';
|
|
20
21
|
|
|
21
22
|
function createApp({ allowNoOrigin } = {}) {
|
|
22
23
|
const guardSameOrigin = createSameOriginGuard({ allowNoOrigin });
|
|
@@ -15,10 +15,33 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { redactErrorResponse } from '@lowdefy/api';
|
|
18
|
+
import { isExpectedError } from '@lowdefy/errors';
|
|
18
19
|
import { HTTPException } from 'hono/http-exception';
|
|
19
20
|
|
|
20
21
|
import sentrySdk from '../../lib/server/sentry/sentrySdk.js';
|
|
21
22
|
|
|
23
|
+
// The HTTP answer to each expected outcome.
|
|
24
|
+
// AuthenticationError: an unauthenticated request to a protected endpoint.
|
|
25
|
+
// AuthorizationError: an authenticated caller whose roles do not permit the resource.
|
|
26
|
+
// TwoFactorEnrolmentRequiredError: an authorized caller who has not enrolled a second factor
|
|
27
|
+
// under auth.twoFactor.required. 403, not 401 - a 401 reads to the client as a dead session
|
|
28
|
+
// and bounces the user to sign-in, which is the loop the gate exists to avoid.
|
|
29
|
+
// UserError: an API client whose payload does not match the endpoint's payloadSchema (or any
|
|
30
|
+
// other UserError raised before a routine starts). A page's CallAPI payload the schema
|
|
31
|
+
// refuses is a ConfigError instead: the page's own config built it (validatePayload). A
|
|
32
|
+
// UserError raised inside a routine never gets here - it returns 200 with success: false
|
|
33
|
+
// through buildEndpointResult.
|
|
34
|
+
const expectedAnswers = {
|
|
35
|
+
AuthenticationError: { status: 401, warning: 'Unauthenticated request', text: 'Unauthorized' },
|
|
36
|
+
AuthorizationError: { status: 403, warning: 'Forbidden', text: 'Forbidden' },
|
|
37
|
+
TwoFactorEnrolmentRequiredError: {
|
|
38
|
+
status: 403,
|
|
39
|
+
warning: 'Two-factor enrolment required',
|
|
40
|
+
text: 'Two-factor enrolment required',
|
|
41
|
+
},
|
|
42
|
+
UserError: { status: 400, warning: 'Bad request', text: 'Bad Request' },
|
|
43
|
+
};
|
|
44
|
+
|
|
22
45
|
// Hono routes every handler error to the app-level error handler — upstream
|
|
23
46
|
// middleware try/catch never sees them (compose catches per dispatch level).
|
|
24
47
|
// API routes get the serialized error JSON the old apiWrapper returned;
|
|
@@ -26,53 +49,18 @@ import sentrySdk from '../../lib/server/sentry/sentrySdk.js';
|
|
|
26
49
|
function createErrorHandler({ basePath = '', logger }) {
|
|
27
50
|
return async function errorHandler(error, c) {
|
|
28
51
|
const path = basePath ? c.req.path.replace(basePath, '') : c.req.path;
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}
|
|
38
|
-
return c.text('Unauthorized', 401);
|
|
39
|
-
}
|
|
40
|
-
// An authenticated caller whose roles do not permit the resource. Expected
|
|
41
|
-
// traffic, not a fault: one warning line, no structured error log and no
|
|
42
|
-
// Sentry capture.
|
|
43
|
-
if (error.name === 'AuthorizationError') {
|
|
44
|
-
logger.warn(`Forbidden: ${c.req.method} ${c.req.path}`);
|
|
45
|
-
if (path.startsWith('/api/')) {
|
|
46
|
-
return c.json({ name: error.name, message: error.message }, 403);
|
|
47
|
-
}
|
|
48
|
-
return c.text('Forbidden', 403);
|
|
49
|
-
}
|
|
50
|
-
// An authorized caller who has not enrolled a second factor under
|
|
51
|
-
// auth.twoFactor.required. 403, not 401 - a 401 reads to the client as a dead
|
|
52
|
-
// session and bounces the user to sign-in, which is the loop the gate exists to
|
|
53
|
-
// avoid. Expected traffic under required: true, so one warning line and no
|
|
54
|
-
// Sentry capture, exactly as for AuthenticationError.
|
|
55
|
-
if (error.name === 'TwoFactorEnrolmentRequiredError') {
|
|
56
|
-
logger.warn(`Two-factor enrolment required: ${c.req.method} ${c.req.path}`);
|
|
57
|
-
if (path.startsWith('/api/')) {
|
|
58
|
-
return c.json({ name: error.name, message: error.message }, 403);
|
|
59
|
-
}
|
|
60
|
-
return c.text('Two-factor enrolment required', 403);
|
|
61
|
-
}
|
|
62
|
-
// An API client whose payload does not match the endpoint's declared
|
|
63
|
-
// payloadSchema (or any other UserError raised before a routine starts). A
|
|
64
|
-
// page's CallAPI payload the schema refuses is a ConfigError instead: the
|
|
65
|
-
// page's own config built it (validatePayload). The caller's own
|
|
66
|
-
// request is wrong, not the config or the server: a 400 with the message the
|
|
67
|
-
// caller needs, one warning line, no structured error log and no Sentry
|
|
68
|
-
// capture. A UserError raised inside a routine never gets here - it returns
|
|
69
|
-
// 200 with success: false through buildEndpointResult.
|
|
70
|
-
if (error.name === 'UserError') {
|
|
71
|
-
logger.warn(`Bad request: ${c.req.method} ${c.req.path} - ${error.message}`);
|
|
52
|
+
// An expected outcome - the system worked and said no - is one warning line and its
|
|
53
|
+
// status, with no structured error log and no Sentry capture, so probing cannot flood
|
|
54
|
+
// either. isExpectedError decides which errors those are; the table only gives the answer.
|
|
55
|
+
if (isExpectedError(error)) {
|
|
56
|
+
// A name expectedErrorNames gains before this table does is still a refusal: a 400.
|
|
57
|
+
const { status, warning, text } = expectedAnswers[error.name] ?? expectedAnswers.UserError;
|
|
58
|
+
const detail = error.name === 'UserError' ? ` - ${error.message}` : '';
|
|
59
|
+
logger.warn(`${warning}: ${c.req.method} ${c.req.path}${detail}`);
|
|
72
60
|
if (path.startsWith('/api/')) {
|
|
73
|
-
return c.json({ name: error.name, message: error.message },
|
|
61
|
+
return c.json({ name: error.name, message: error.message }, status);
|
|
74
62
|
}
|
|
75
|
-
return c.text(
|
|
63
|
+
return c.text(text, status);
|
|
76
64
|
}
|
|
77
65
|
// A route or transport that has already decided its own HTTP answer - hono's
|
|
78
66
|
// HTTPException carries the response to send. The MCP transport refuses an
|
|
@@ -16,12 +16,12 @@
|
|
|
16
16
|
|
|
17
17
|
import { Hono } from 'hono';
|
|
18
18
|
import { HTTPException } from 'hono/http-exception';
|
|
19
|
-
import {
|
|
19
|
+
import { vi, expect, test } from 'vitest';
|
|
20
20
|
|
|
21
21
|
// The handler is byte-identical to `server-dev`'s and `server-e2e`'s apart from
|
|
22
22
|
// the Sentry capture tested at the bottom of this file. Keep the three in sync
|
|
23
23
|
// when changing any of them.
|
|
24
|
-
const captureException =
|
|
24
|
+
const captureException = vi.fn();
|
|
25
25
|
|
|
26
26
|
const { default: sentrySdk } = await import('../../lib/server/sentry/sentrySdk.js');
|
|
27
27
|
const { default: createErrorHandler } = await import('./errorHandler.js');
|
|
@@ -32,7 +32,7 @@ const { default: createErrorHandler } = await import('./errorHandler.js');
|
|
|
32
32
|
const SECRET = 'SECRET-RECEIVED-VALUE';
|
|
33
33
|
|
|
34
34
|
function createLogger() {
|
|
35
|
-
return { error:
|
|
35
|
+
return { error: vi.fn(), warn: vi.fn() };
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
// The error handler is only reachable through hono's app-level onError, so the
|
|
@@ -92,7 +92,7 @@ function createErrorWithCause() {
|
|
|
92
92
|
|
|
93
93
|
test('errorHandler returns 401 with only name and message for an AuthenticationError on an api path', async () => {
|
|
94
94
|
const logger = createLogger();
|
|
95
|
-
const context = { handleError:
|
|
95
|
+
const context = { handleError: vi.fn() };
|
|
96
96
|
const res = await createApp({
|
|
97
97
|
context,
|
|
98
98
|
error: createAuthenticationError('Unauthenticated.'),
|
|
@@ -131,7 +131,7 @@ test('errorHandler returns text Unauthorized at 401 for an AuthenticationError o
|
|
|
131
131
|
|
|
132
132
|
test('errorHandler returns 403 with only name and message for an AuthorizationError on an api path', async () => {
|
|
133
133
|
const logger = createLogger();
|
|
134
|
-
const context = { handleError:
|
|
134
|
+
const context = { handleError: vi.fn() };
|
|
135
135
|
const res = await createApp({
|
|
136
136
|
context,
|
|
137
137
|
error: createAuthorizationError('Forbidden.'),
|
|
@@ -172,7 +172,7 @@ test('errorHandler returns text Forbidden at 403 for an AuthorizationError on a
|
|
|
172
172
|
|
|
173
173
|
test('errorHandler returns 403 with only name and message for a TwoFactorEnrolmentRequiredError on an api path', async () => {
|
|
174
174
|
const logger = createLogger();
|
|
175
|
-
const context = { handleError:
|
|
175
|
+
const context = { handleError: vi.fn() };
|
|
176
176
|
const res = await createApp({
|
|
177
177
|
context,
|
|
178
178
|
error: createTwoFactorEnrolmentRequiredError('Two-factor enrolment required.'),
|
|
@@ -202,7 +202,7 @@ test('errorHandler does not send a TwoFactorEnrolmentRequiredError through the r
|
|
|
202
202
|
|
|
203
203
|
test('errorHandler returns text at 403 for a TwoFactorEnrolmentRequiredError on a page path', async () => {
|
|
204
204
|
const logger = createLogger();
|
|
205
|
-
const context = { handleError:
|
|
205
|
+
const context = { handleError: vi.fn() };
|
|
206
206
|
const res = await createApp({
|
|
207
207
|
context,
|
|
208
208
|
error: createTwoFactorEnrolmentRequiredError('Two-factor enrolment required.'),
|
|
@@ -217,7 +217,7 @@ test('errorHandler returns text at 403 for a TwoFactorEnrolmentRequiredError on
|
|
|
217
217
|
|
|
218
218
|
test('errorHandler returns 400 with only name and message for a UserError on an api path', async () => {
|
|
219
219
|
const logger = createLogger();
|
|
220
|
-
const context = { handleError:
|
|
220
|
+
const context = { handleError: vi.fn() };
|
|
221
221
|
const res = await createApp({
|
|
222
222
|
context,
|
|
223
223
|
error: createUserError('Payload for endpoint "x" does not match its payloadSchema.'),
|
|
@@ -336,7 +336,7 @@ test('errorHandler returns text Internal Server Error at 500 on a page path with
|
|
|
336
336
|
|
|
337
337
|
test('errorHandler awaits context.handleError before serializing the response', async () => {
|
|
338
338
|
const context = {
|
|
339
|
-
handleError:
|
|
339
|
+
handleError: vi.fn(async (error) => {
|
|
340
340
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
341
341
|
error.handled = true;
|
|
342
342
|
}),
|
|
@@ -357,7 +357,7 @@ test('errorHandler awaits context.handleError before serializing the response',
|
|
|
357
357
|
// serialization or the error is logged a second time.
|
|
358
358
|
test('errorHandler returns handled true on the 500 envelope after handleError sets it', async () => {
|
|
359
359
|
const context = {
|
|
360
|
-
handleError:
|
|
360
|
+
handleError: vi.fn(async (error) => {
|
|
361
361
|
error.handled = true;
|
|
362
362
|
}),
|
|
363
363
|
};
|
|
@@ -408,7 +408,7 @@ test('errorHandler treats a basePath prefixed page path as a page path', async (
|
|
|
408
408
|
// captureSentryError), so the handler must not capture the same fault again.
|
|
409
409
|
test('errorHandler does not capture to Sentry when a lowdefyContext handled the error', async () => {
|
|
410
410
|
sentrySdk.current = { captureException };
|
|
411
|
-
const context = { handleError:
|
|
411
|
+
const context = { handleError: vi.fn() };
|
|
412
412
|
await createApp({
|
|
413
413
|
context,
|
|
414
414
|
error: createErrorWithCause(),
|
|
@@ -15,15 +15,15 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { Hono } from 'hono';
|
|
18
|
-
import {
|
|
18
|
+
import { vi, expect, test } from 'vitest';
|
|
19
19
|
|
|
20
20
|
import refuseOtherBuild from './refuseOtherBuild.js';
|
|
21
21
|
|
|
22
22
|
function createApp() {
|
|
23
|
-
const handler =
|
|
23
|
+
const handler = vi.fn((c) => c.json({ ran: true }));
|
|
24
24
|
const app = new Hono();
|
|
25
25
|
app.use('*', async (c, next) => {
|
|
26
|
-
c.set('lowdefyContext', { logger: { info:
|
|
26
|
+
c.set('lowdefyContext', { logger: { info: vi.fn() } });
|
|
27
27
|
await next();
|
|
28
28
|
});
|
|
29
29
|
app.post('/api/request/home/save', refuseOtherBuild({ buildId: 'build-2' }), handler);
|
|
@@ -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);
|