@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
|
@@ -15,33 +15,36 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { Hono } from 'hono';
|
|
18
|
-
import {
|
|
18
|
+
import { vi, beforeEach, expect, test } from 'vitest';
|
|
19
19
|
|
|
20
20
|
const { default: getPageConfig } = await import('@lowdefy/api/routes/page/getPageConfig.js');
|
|
21
21
|
|
|
22
|
-
const mockGetRootConfig =
|
|
23
|
-
|
|
24
|
-
createContentSecurityPolicy:
|
|
22
|
+
const mockGetRootConfig = vi.fn();
|
|
23
|
+
vi.doMock('@lowdefy/api', () => ({
|
|
24
|
+
createContentSecurityPolicy: vi.fn(),
|
|
25
25
|
getPageConfig,
|
|
26
26
|
getRootConfig: mockGetRootConfig,
|
|
27
27
|
}));
|
|
28
28
|
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
vi.doMock('../../lib/build/app.js', () => ({ default: {} }));
|
|
30
|
+
vi.doMock('../../lib/build/auth.js', () => ({
|
|
31
31
|
default: { authPages: { signIn: '/auth/login', twoFactorEnrol: '/two-factor-enrol' } },
|
|
32
32
|
}));
|
|
33
|
-
|
|
34
|
-
|
|
33
|
+
vi.doMock('../../lib/build/config.js', () => ({ default: { basePath: '' } }));
|
|
34
|
+
vi.doMock('../../lib/build/security.js', () => ({
|
|
35
35
|
default: { contentSecurityPolicy: null },
|
|
36
36
|
}));
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
vi.doMock('../../lib/build/theme.js', () => ({ default: {} }));
|
|
38
|
+
vi.doMock('./getAssets.js', () => ({ default: () => ({}) }));
|
|
39
|
+
vi.doMock('./getPageAssets.js', () => ({ default: () => ({}) }));
|
|
40
|
+
vi.doMock('./template.js', () => ({
|
|
41
41
|
default: ({ config, title }) => JSON.stringify({ config, title }),
|
|
42
42
|
}));
|
|
43
43
|
|
|
44
44
|
const { default: renderPage } = await import('./renderPage.js');
|
|
45
|
+
// The mobile sign-in route reaches the auth engine, which these tests never start.
|
|
46
|
+
vi.doMock('../routes/mobileSignIn.js', () => ({ default: () => null }));
|
|
47
|
+
vi.doMock('../routes/mobileSignInCallback.js', () => ({ default: () => null }));
|
|
45
48
|
const { default: mountPageRoutes } = await import('../routes/mountPageRoutes.js');
|
|
46
49
|
|
|
47
50
|
const routes = [
|
|
@@ -71,7 +74,7 @@ function createApp({
|
|
|
71
74
|
c.set('lowdefyContext', {
|
|
72
75
|
authEnforcement: { pagesProtectedByDefault },
|
|
73
76
|
authorizeOutcome: () => outcome,
|
|
74
|
-
logger: { info:
|
|
77
|
+
logger: { info: vi.fn() },
|
|
75
78
|
readConfigFile: async (file) => {
|
|
76
79
|
if (file === 'routes.json') return routeTable;
|
|
77
80
|
return pages[file.slice('pages/'.length, -'.json'.length)] ?? null;
|
package/src/initServer.test.mjs
CHANGED
|
@@ -14,38 +14,38 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import {
|
|
17
|
+
import { vi, expect, test } from 'vitest';
|
|
18
18
|
|
|
19
19
|
const calls = [];
|
|
20
|
-
const info =
|
|
20
|
+
const info = vi.fn();
|
|
21
21
|
const guards = { env: { BETTER_AUTH_URL: '^https://app\\.example\\.com$' } };
|
|
22
22
|
|
|
23
|
-
const checkEnvironmentGuards =
|
|
23
|
+
const checkEnvironmentGuards = vi.fn(() => {
|
|
24
24
|
calls.push('checkEnvironmentGuards');
|
|
25
25
|
});
|
|
26
|
-
const captureException =
|
|
27
|
-
const flush =
|
|
26
|
+
const captureException = vi.fn();
|
|
27
|
+
const flush = vi.fn(async () => true);
|
|
28
28
|
const sentry = { captureException, flush };
|
|
29
|
-
const initSentryServer =
|
|
29
|
+
const initSentryServer = vi.fn(async () => {
|
|
30
30
|
calls.push('initSentryServer');
|
|
31
31
|
return null;
|
|
32
32
|
});
|
|
33
|
-
const createApp =
|
|
33
|
+
const createApp = vi.fn();
|
|
34
34
|
|
|
35
|
-
|
|
35
|
+
vi.doMock('@lowdefy/node-utils/checkEnvironmentGuards.js', () => ({
|
|
36
36
|
default: checkEnvironmentGuards,
|
|
37
37
|
}));
|
|
38
|
-
|
|
38
|
+
vi.doMock('../lib/server/sentry/initSentry.js', () => ({
|
|
39
39
|
default: initSentryServer,
|
|
40
40
|
}));
|
|
41
|
-
|
|
41
|
+
vi.doMock('./app.js', () => {
|
|
42
42
|
calls.push('import app');
|
|
43
43
|
return { default: createApp };
|
|
44
44
|
});
|
|
45
|
-
|
|
45
|
+
vi.doMock('../lib/server/log/createLogger.js', () => ({
|
|
46
46
|
default: () => ({ info }),
|
|
47
47
|
}));
|
|
48
|
-
|
|
48
|
+
vi.doMock('../lib/build/config.js', () => ({
|
|
49
49
|
default: { environment: 'prod', environments: { prod: { guards } } },
|
|
50
50
|
}));
|
|
51
51
|
|
|
@@ -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);
|
|
@@ -22,6 +22,12 @@ import { timeout } from 'hono/timeout';
|
|
|
22
22
|
// timeout signal (which apiContext folds into context.signal) cancels the upstream
|
|
23
23
|
// calls the handler is waiting on, such as an AI provider call, instead of letting
|
|
24
24
|
// them run, and bill, after the response has gone.
|
|
25
|
+
//
|
|
26
|
+
// The 504 has no body. The handler runs on after the 504 is sent, on the same context:
|
|
27
|
+
// a header set on it then, by the middleware around the handler or by the handler
|
|
28
|
+
// itself (c.redirect sets one), makes hono rebuild the sent 504 from its body. Sending
|
|
29
|
+
// it has already read that body, so the rebuild throws. A response with no body
|
|
30
|
+
// rebuilds safely. The client reads any 504 as a timeout.
|
|
25
31
|
function requestTimeout({ timeoutMs }) {
|
|
26
32
|
return function requestTimeoutMiddleware(c, next) {
|
|
27
33
|
const controller = new AbortController();
|
|
@@ -30,7 +36,7 @@ function requestTimeout({ timeoutMs }) {
|
|
|
30
36
|
controller.abort(
|
|
31
37
|
new DOMException(`The request timeout of ${timeoutMs}ms was exceeded.`, 'TimeoutError')
|
|
32
38
|
);
|
|
33
|
-
return new HTTPException(504, {
|
|
39
|
+
return new HTTPException(504, { res: new Response(null, { status: 504 }) });
|
|
34
40
|
})(c, next);
|
|
35
41
|
};
|
|
36
42
|
}
|