@lowdefy/api 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.
Files changed (126) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +99 -31
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +172 -98
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/isUserBanned.js +28 -0
  21. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  22. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  23. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  24. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  25. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  26. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  27. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  28. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  29. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  30. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  31. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  33. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  34. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  35. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  36. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  37. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  38. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  39. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  40. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  41. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  42. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  43. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  44. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  45. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +57 -11
  46. package/dist/routes/auth/organizations/checkInvitationContactLink.js +60 -0
  47. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +47 -12
  48. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  49. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  50. package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +40 -16
  51. package/dist/routes/auth/organizations/createBeforeAcceptInvitationHook.js +35 -0
  52. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  53. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  54. package/dist/routes/auth/organizations/createEmailSendGate.js +35 -7
  55. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  56. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  57. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  58. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  59. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  60. package/dist/routes/auth/organizations/isEmailAdmitted.js +25 -14
  61. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  62. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  63. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  64. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  65. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  66. package/dist/routes/auth/requestHooks/buildRequestHooks.js +78 -2
  67. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  68. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  69. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  70. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  71. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  72. package/dist/routes/auth/runReportingFaults.js +32 -0
  73. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  74. package/dist/routes/endpoints/callEndpoint.js +6 -3
  75. package/dist/routes/endpoints/control/controlFor.js +9 -6
  76. package/dist/routes/endpoints/control/controlIf.js +8 -3
  77. package/dist/routes/endpoints/control/controlLog.js +3 -1
  78. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  79. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  80. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  81. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  82. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  83. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  84. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  85. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  86. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  87. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  88. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  89. package/dist/routes/endpoints/handleRequest.js +3 -2
  90. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  91. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  92. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  93. package/dist/routes/endpoints/runRoutine.js +5 -5
  94. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  95. package/dist/routes/endpoints/test/runTest.js +30 -11
  96. package/dist/routes/mcp/createMcpServer.js +2 -7
  97. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  98. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  99. package/dist/routes/mobile/createAssetLinks.js +38 -0
  100. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  101. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  102. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  103. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  104. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  105. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  106. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  107. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  108. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  109. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  110. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  111. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  112. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  113. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  114. package/dist/routes/page/getPageConfig.js +25 -1
  115. package/dist/routes/request/callRequestResolver.js +29 -36
  116. package/dist/routes/request/stampTypedError.js +37 -0
  117. package/dist/routes/request/summarisedError.js +62 -0
  118. package/dist/routes/request/wrapResolverError.js +61 -0
  119. package/dist/routes/websocket/checkWebsocketAccess.js +81 -0
  120. package/dist/routes/websocket/createChannelRegistry.js +62 -17
  121. package/dist/routes/websocket/createWebSocketConnection.js +59 -21
  122. package/dist/routes/websocket/prepareChannel.js +11 -0
  123. package/dist/test/createMemoryAuth.js +125 -0
  124. package/package.json +20 -22
  125. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  126. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -12,7 +12,8 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import { type } from '@lowdefy/helpers';
15
+ */ import { isExpectedError } from '@lowdefy/errors';
16
+ import { type } from '@lowdefy/helpers';
16
17
  import { runInCredentialScope } from '@lowdefy/node-utils';
17
18
  import getCallerFingerprint from './getCallerFingerprint.js';
18
19
  import redactErrorResponse from '../../response/redactErrorResponse.js';
@@ -30,7 +31,9 @@ const CALLER_CHECK_FAILED_CODE = 1011;
30
31
  // out, lost its membership, changed roles or switched organization, the socket
31
32
  // closes with code 4401; the client reconnects, which authenticates afresh.
32
33
  // Each check is a live session read - nothing is cached, so a revoked session
33
- // closes the socket within a minute.
34
+ // closes the socket within a minute. The once-a-minute check also runs the
35
+ // websocket check of every open subscription that has one, so revoked access to
36
+ // a record ends that subscription within a minute.
34
37
  function createWebSocketConnection(context, { closeSocket, headers, registry, send, strategies }) {
35
38
  const { logger } = context;
36
39
  const callerFingerprint = getCallerFingerprint({
@@ -177,6 +180,26 @@ function createWebSocketConnection(context, { closeSocket, headers, registry, se
177
180
  });
178
181
  }
179
182
  }
183
+ function reportError({ error, frameType, requestId, websocketId }) {
184
+ logger.debug({
185
+ err: error
186
+ }, error.message);
187
+ // Expected outcomes - an auth refusal, a UserError - are one warn line, as over HTTP:
188
+ // no error log or Sentry report, but the client is still told.
189
+ if (isExpectedError(error)) {
190
+ logger.warn({
191
+ event: 'ws_refused',
192
+ frameType
193
+ }, error.message);
194
+ } else {
195
+ context.handleError(error);
196
+ }
197
+ sendErrorPayload({
198
+ error,
199
+ requestId,
200
+ websocketId
201
+ });
202
+ }
180
203
  async function processFrame(frame) {
181
204
  if (closed) {
182
205
  return;
@@ -184,30 +207,33 @@ function createWebSocketConnection(context, { closeSocket, headers, registry, se
184
207
  try {
185
208
  await handleFrame(frame);
186
209
  } catch (error) {
187
- logger.debug({
188
- err: error
189
- }, error.message);
190
- // Authentication and authorization refusals are expected traffic - one
191
- // warn line, no error log or Sentry report, but the client is still told.
192
- if ([
193
- 'AuthenticationError',
194
- 'AuthorizationError',
195
- 'TwoFactorEnrolmentRequiredError'
196
- ].includes(error.name)) {
197
- logger.warn({
198
- event: 'ws_refused',
199
- frameType: frame.type
200
- }, error.message);
201
- } else {
202
- context.handleError(error);
203
- }
204
- sendErrorPayload({
210
+ reportError({
205
211
  error,
212
+ frameType: frame.type,
206
213
  requestId: frame.requestId,
207
214
  websocketId: frame.websocketId
208
215
  });
209
216
  }
210
217
  }
218
+ // A refused subscription is closed by the registry. The error frame carries no
219
+ // requestId, so the client reads it as the feed failing, as it does a source error.
220
+ async function recheckSubscription(websocketId) {
221
+ if (closed) {
222
+ return;
223
+ }
224
+ try {
225
+ await registry.recheckAccess(context, {
226
+ websocketId,
227
+ subscriber
228
+ });
229
+ } catch (error) {
230
+ reportError({
231
+ error,
232
+ frameType: 'recheck',
233
+ websocketId
234
+ });
235
+ }
236
+ }
211
237
  function enqueue(websocketId, task) {
212
238
  const handled = (feedQueues.get(websocketId) ?? Promise.resolve()).then(task);
213
239
  const tail = handled.catch(()=>{});
@@ -249,9 +275,21 @@ function createWebSocketConnection(context, { closeSocket, headers, registry, se
249
275
  // routines it runs.
250
276
  await enqueue(frame.websocketId, ()=>runInCredentialScope(()=>processFrame(frame)));
251
277
  }
278
+ // A websocket check answers for one record, which the caller can lose access
279
+ // to without the caller changing, so the check runs again for every open
280
+ // subscription that has one. Each runs in its feed's queue, after any frame
281
+ // for that feed already waiting.
282
+ async function checkOpenConnection() {
283
+ if (!await checkCaller()) {
284
+ return;
285
+ }
286
+ await Promise.all(registry.getCheckedWebsocketIds({
287
+ subscriber
288
+ }).map((websocketId)=>enqueue(websocketId, ()=>runInCredentialScope(()=>recheckSubscription(websocketId)))));
289
+ }
252
290
  // One timer per connection, cleared by close. It does not keep the process
253
291
  // alive on its own.
254
- const callerCheckTimer = setInterval(checkCaller, CALLER_CHECK_INTERVAL_MS);
292
+ const callerCheckTimer = setInterval(checkOpenConnection, CALLER_CHECK_INTERVAL_MS);
255
293
  callerCheckTimer.unref();
256
294
  logger.debug({
257
295
  event: 'ws_connect'
@@ -14,6 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { type } from '@lowdefy/helpers';
16
16
  import authorizeWebsocket from './authorizeWebsocket.js';
17
+ import checkWebsocketAccess from './checkWebsocketAccess.js';
17
18
  import checkConnectionRead from '../request/checkConnectionRead.js';
18
19
  import getConnection from '../connections/getConnection.js';
19
20
  import getConnectionConfig from '../connections/getConnectionConfig.js';
@@ -27,6 +28,12 @@ import createEvaluateOperators from '../../context/createEvaluateOperators.js';
27
28
  // websocket definition can produce user- or filter-specific channels. The
28
29
  // evaluated result is the channel identity — subscribers whose evaluation is
29
30
  // identical share one running source.
31
+ //
32
+ // After the role check, the websocket's check endpoint runs, before anything is
33
+ // evaluated for a caller it refuses. The check is per caller and not part of the channel
34
+ // identity, so subscribers that each pass still share a source. A publish is
35
+ // checked too, with the same empty payload its properties are evaluated with,
36
+ // so a caller the check refuses can not publish into a channel either.
30
37
  async function prepareChannel(context, { websocketId, payload }) {
31
38
  context.evaluateOperators = createEvaluateOperators(context);
32
39
  const websocketConfig = await getWebsocketConfig(context, {
@@ -35,6 +42,10 @@ async function prepareChannel(context, { websocketId, payload }) {
35
42
  authorizeWebsocket(context, {
36
43
  websocketConfig
37
44
  });
45
+ await checkWebsocketAccess(context, {
46
+ payload,
47
+ websocketConfig
48
+ });
38
49
  const websocketResolver = getWebsocketResolver(context, {
39
50
  websocketConfig
40
51
  });
@@ -0,0 +1,125 @@
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
+ */ import { vi } from 'vitest';
16
+ // An in-memory auth database holding the unique indexes ensureAuthIndexes
17
+ // creates - one organization per slug, one member row per (user, org) - so the
18
+ // mint's recovery from a lost race runs against the same rejection a real
19
+ // database gives. `before` pauses an operation until the test releases it,
20
+ // which fixes the interleaving of two concurrent sessions.
21
+ function createMemoryAuth({ organizations = [], members = [], ensureUniqueIndexes } = {}) {
22
+ const db = {
23
+ organization: [
24
+ ...organizations
25
+ ],
26
+ member: [
27
+ ...members
28
+ ]
29
+ };
30
+ const pauses = [];
31
+ let ids = 0;
32
+ function matches(row, where) {
33
+ return where.every(({ field, value, operator })=>operator === 'ne' ? row[field] !== value : row[field] === value);
34
+ }
35
+ async function pause(operation, args) {
36
+ const found = pauses.find((entry)=>entry.match(operation, args));
37
+ if (found) {
38
+ pauses.splice(pauses.indexOf(found), 1);
39
+ found.reached();
40
+ await found.released;
41
+ }
42
+ }
43
+ const adapter = {
44
+ options: {
45
+ ensureUniqueIndexes: ensureUniqueIndexes ?? vi.fn(async ()=>{})
46
+ },
47
+ findOne: vi.fn(async ({ model, where })=>{
48
+ await pause('findOne', {
49
+ model,
50
+ where
51
+ });
52
+ return db[model].find((row)=>matches(row, where)) ?? null;
53
+ }),
54
+ findMany: vi.fn(async ({ model, where })=>{
55
+ if (model === 'invitation') return [];
56
+ return db[model].filter((row)=>matches(row, where));
57
+ }),
58
+ create: vi.fn(async ({ model, data })=>{
59
+ await pause('create', {
60
+ model,
61
+ data
62
+ });
63
+ const duplicate = model === 'organization' ? db.organization.some((row)=>row.slug === data.slug) : db.member.some((row)=>row.userId === data.userId && row.organizationId === data.organizationId);
64
+ if (duplicate) {
65
+ throw new Error(`E11000 duplicate key error collection: ${model}`);
66
+ }
67
+ ids += 1;
68
+ const row = {
69
+ id: `${model}_${ids}`,
70
+ ...data
71
+ };
72
+ db[model].push(row);
73
+ return {
74
+ ...row
75
+ };
76
+ }),
77
+ count: vi.fn(async ({ model, where })=>db[model].filter((row)=>matches(row, where)).length),
78
+ update: vi.fn(async ({ model, where, update })=>{
79
+ const row = db[model].find((candidate)=>matches(candidate, where));
80
+ Object.assign(row, update);
81
+ return {
82
+ ...row
83
+ };
84
+ })
85
+ };
86
+ const internalAdapter = {
87
+ findUserById: vi.fn(async (id)=>({
88
+ id,
89
+ email: `${id}@example.com`,
90
+ name: 'User One'
91
+ }))
92
+ };
93
+ const auth = {
94
+ $context: Promise.resolve({
95
+ adapter,
96
+ internalAdapter
97
+ })
98
+ };
99
+ // Pause the next operation matching `match` until release() is called;
100
+ // reached resolves once a session is waiting there.
101
+ function before(match) {
102
+ const entry = {
103
+ match
104
+ };
105
+ const reached = new Promise((resolve)=>{
106
+ entry.reached = resolve;
107
+ });
108
+ let release;
109
+ entry.released = new Promise((resolve)=>{
110
+ release = resolve;
111
+ });
112
+ pauses.push(entry);
113
+ return {
114
+ reached,
115
+ release
116
+ };
117
+ }
118
+ return {
119
+ auth,
120
+ adapter,
121
+ db,
122
+ before
123
+ };
124
+ }
125
+ export default createMemoryAuth;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lowdefy/api",
3
- "version": "7.1.0",
3
+ "version": "7.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "",
6
6
  "homepage": "https://lowdefy.com",
@@ -38,33 +38,31 @@
38
38
  "@better-auth/cimd": "1.7.7",
39
39
  "@better-auth/oauth-provider": "1.7.7",
40
40
  "@better-auth/passkey": "1.7.7",
41
- "@lowdefy/ajv": "7.1.0",
42
- "@lowdefy/build": "7.1.0",
43
- "@lowdefy/connection-smtp": "7.1.0",
44
- "@lowdefy/email-templates": "7.1.0",
45
- "@lowdefy/errors": "7.1.0",
46
- "@lowdefy/helpers": "7.1.0",
47
- "@lowdefy/node-utils": "7.1.0",
48
- "@lowdefy/nunjucks": "7.1.0",
49
- "@lowdefy/operators": "7.1.0",
50
- "@lowdefy/operators-js": "7.1.0",
51
- "@modelcontextprotocol/sdk": "1.31.0",
41
+ "@lowdefy/ajv": "7.3.0",
42
+ "@lowdefy/build": "7.3.0",
43
+ "@lowdefy/connection-smtp": "7.3.0",
44
+ "@lowdefy/email-templates": "7.3.0",
45
+ "@lowdefy/errors": "7.3.0",
46
+ "@lowdefy/helpers": "7.3.0",
47
+ "@lowdefy/node-utils": "7.3.0",
48
+ "@lowdefy/nunjucks": "7.3.0",
49
+ "@lowdefy/operators": "7.3.0",
50
+ "@lowdefy/operators-js": "7.3.0",
51
+ "@modelcontextprotocol/sdk": "1.32.2",
52
52
  "better-auth": "1.7.7",
53
53
  "jose": "^6.2.3",
54
54
  "mongodb-connection-string-url": "^7.0.2",
55
- "nodemailer": "10.0.13"
55
+ "nodemailer": "10.1.7"
56
56
  },
57
57
  "devDependencies": {
58
- "@jest/globals": "28.1.3",
59
- "@lowdefy/connection-mongodb": "7.1.0",
60
- "@lowdefy/plugin-better-auth": "7.1.0",
58
+ "@lowdefy/connection-mongodb": "7.3.0",
59
+ "@lowdefy/plugin-better-auth": "7.3.0",
61
60
  "@opentelemetry/api": "1.9.1",
62
- "@shelf/jest-mongodb": "4.3.2",
63
61
  "@swc/cli": "0.8.1",
64
62
  "@swc/core": "1.15.32",
65
- "@swc/jest": "0.2.39",
66
- "jest": "28.1.3",
67
- "mongodb": "7.2.0"
63
+ "mongodb": "7.2.0",
64
+ "mongodb-memory-server-core": "9.2.0",
65
+ "vitest": "4.1.12"
68
66
  },
69
67
  "publishConfig": {
70
68
  "access": "public"
@@ -72,7 +70,7 @@
72
70
  "scripts": {
73
71
  "build": "swc src --out-dir dist --config-file ../../.swcrc --cli-config-file ../../.swc-cli.json",
74
72
  "clean": "rm -rf dist",
75
- "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
76
- "test:mongodb": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config jest.mongodb.config.js"
73
+ "test": "vitest run",
74
+ "test:mongodb": "vitest run --config vitest.mongodb.config.js"
77
75
  }
78
76
  }
@@ -1,117 +0,0 @@
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
- */ import { type } from '@lowdefy/helpers';
16
- // The schemas that can describe a value: the schema itself and its oneOf,
17
- // anyOf and allOf branches, however nested.
18
- function expandSchema(schema) {
19
- const schemas = [];
20
- const pending = [
21
- schema
22
- ];
23
- while(pending.length > 0){
24
- const candidate = pending.pop();
25
- if (type.isObject(candidate)) {
26
- schemas.push(candidate);
27
- [
28
- ...candidate.oneOf ?? [],
29
- ...candidate.anyOf ?? [],
30
- ...candidate.allOf ?? []
31
- ].forEach((branch)=>pending.push(branch));
32
- }
33
- }
34
- return schemas;
35
- }
36
- function childSchemas({ schemas, key }) {
37
- return schemas.flatMap((schema)=>{
38
- if (type.isObject(schema.properties?.[key])) {
39
- return [
40
- schema.properties[key]
41
- ];
42
- }
43
- if (type.isObject(schema.additionalProperties)) {
44
- return [
45
- schema.additionalProperties
46
- ];
47
- }
48
- return [];
49
- });
50
- }
51
- // The urlKind the schemas give a value: a string when one marks it as a URL,
52
- // null when one opts it out with urlKind: false, undefined when none says.
53
- function findUrlKind(schemas) {
54
- const marked = schemas.find((candidate)=>type.isString(candidate.urlKind));
55
- if (marked) {
56
- return marked.urlKind;
57
- }
58
- if (schemas.some((candidate)=>candidate.urlKind === false)) {
59
- return null;
60
- }
61
- return undefined;
62
- }
63
- // Records, by path, the urlKind a block schema gives the value there. A block
64
- // marks each URL-valued property with urlKind ('url' and 'href' navigate, 'url'
65
- // the way the engine's link resolver does; 'src' loads; 'srcSet' lists
66
- // sources), so the policy judges URLs by what a property is, not by what it is
67
- // called; a marked array holds one URL per item. urlKind: false records null,
68
- // for a property whose name looks like a URL key but whose value is not a URL.
69
- // A value no schema marks either way is not recorded, so the policy falls back
70
- // to judging it by its key name.
71
- function collectUrlKinds({ value, schema, path }) {
72
- const kinds = new Map();
73
- const pending = [
74
- {
75
- value,
76
- schema,
77
- path
78
- }
79
- ];
80
- while(pending.length > 0){
81
- const item = pending.pop();
82
- const schemas = expandSchema(item.schema);
83
- const urlKind = findUrlKind(schemas);
84
- if (urlKind === null) {
85
- // Another schema branch may already have marked it as a URL.
86
- if (!kinds.has(item.path)) {
87
- kinds.set(item.path, null);
88
- }
89
- } else if (type.isString(urlKind)) {
90
- if (type.isArray(item.value)) {
91
- item.value.forEach((_, index)=>kinds.set(`${item.path}.${index}`, urlKind));
92
- } else {
93
- kinds.set(item.path, urlKind);
94
- }
95
- } else if (type.isArray(item.value)) {
96
- const itemSchemas = schemas.map((candidate)=>candidate.items).filter(type.isObject);
97
- item.value.forEach((child, index)=>itemSchemas.forEach((itemSchema)=>pending.push({
98
- value: child,
99
- schema: itemSchema,
100
- path: `${item.path}.${index}`
101
- })));
102
- } else if (type.isObject(item.value)) {
103
- Object.keys(item.value).forEach((key)=>{
104
- childSchemas({
105
- schemas,
106
- key
107
- }).forEach((childSchema)=>pending.push({
108
- value: item.value[key],
109
- schema: childSchema,
110
- path: `${item.path}.${key}`
111
- }));
112
- });
113
- }
114
- }
115
- return kinds;
116
- }
117
- export default collectUrlKinds;
@@ -1,34 +0,0 @@
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
- */ // A request type names in meta.credentialProperties the request properties that carry a
16
- // credential the secret scrub cannot recognise, such as a presigned link, whose signature is
17
- // derived from a secret rather than being one. Their values are masked in the request properties
18
- // an error keeps as received, so the error log never holds them.
19
- function maskCredentialProperties({ requestProperties, requestResolver }) {
20
- const credentialProperties = requestResolver.meta.credentialProperties ?? [];
21
- if (credentialProperties.length === 0) {
22
- return requestProperties;
23
- }
24
- const masked = {
25
- ...requestProperties
26
- };
27
- credentialProperties.forEach((property)=>{
28
- if (Object.hasOwn(masked, property)) {
29
- masked[property] = '[REDACTED]';
30
- }
31
- });
32
- return masked;
33
- }
34
- export default maskCredentialProperties;