@lowdefy/api 0.0.0-experimental-20260720072521 → 0.0.0-experimental-20260720135014
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/dist/context/createApiContext.js +1 -9
- package/dist/context/createAuthorize.js +8 -19
- package/dist/context/createEvaluateOperators.js +1 -2
- package/dist/index.js +3 -13
- package/dist/routes/agent/callAgent.js +180 -7
- package/dist/routes/{websocket/authorizeWebsocket.js → auth/callbacks/addUserFieldsToSession.js} +11 -10
- package/dist/routes/auth/callbacks/addUserFieldsToToken.js +30 -0
- package/dist/routes/auth/{hooks/composeAfterSlot.js → callbacks/createCallbackPlugins.js} +6 -11
- package/dist/routes/auth/callbacks/createCallbacks.js +46 -0
- package/dist/routes/auth/callbacks/createJWTCallback.js +77 -0
- package/dist/routes/auth/callbacks/createRedirectCallback.js +41 -0
- package/dist/routes/auth/callbacks/createSessionCallback.js +81 -0
- package/dist/routes/auth/callbacks/createSignInCallback.js +40 -0
- package/dist/routes/auth/callbacks/validateSessionRoles.js +33 -0
- package/dist/routes/{websocket/getWebsocketConfig.js → auth/createAdapter.js} +8 -14
- package/dist/routes/auth/createLogger.js +38 -0
- package/dist/routes/auth/createProviders.js +25 -0
- package/dist/routes/auth/events/createCreateUserEvent.js +41 -0
- package/dist/routes/auth/{organizations/getHookRequestHeaders.js → events/createEventPlugins.js} +6 -9
- package/dist/routes/auth/events/createEvents.js +56 -0
- package/dist/routes/auth/events/createLinkAccountEvent.js +43 -0
- package/dist/routes/auth/{strategies/getAuthStrategies.js → events/createSessionEvent.js} +17 -14
- package/dist/routes/auth/events/createSignInEvent.js +46 -0
- package/dist/routes/auth/events/createSignOutEvent.js +43 -0
- package/dist/routes/auth/events/createUpdateUserEvent.js +41 -0
- package/dist/routes/auth/getNextAuthConfig.js +75 -0
- package/dist/routes/endpoints/authorizeApiEndpoint.js +2 -8
- package/dist/routes/endpoints/callEndpoint.js +0 -20
- package/dist/routes/endpoints/control/controlReject.js +1 -3
- package/dist/routes/endpoints/control/controlThrow.js +1 -4
- package/dist/routes/endpoints/handleEndpointCall.js +1 -62
- package/dist/routes/endpoints/handleRequest.js +1 -8
- package/dist/routes/endpoints/handleValidateSchema.js +1 -3
- package/dist/routes/endpoints/runRoutine.js +0 -18
- package/dist/routes/endpoints/test/runTest.js +4 -3
- package/dist/routes/page/getPageConfig.js +8 -42
- package/dist/routes/request/authorizeRequest.js +2 -8
- package/dist/routes/request/callRequest.js +1 -8
- package/dist/routes/request/callRequestResolver.js +2 -6
- package/dist/test/testContext.js +6 -6
- package/package.json +10 -16
- package/dist/context/applySystemTrust.js +0 -33
- package/dist/context/createSystemContext.js +0 -72
- package/dist/context/normalizeInjectedCaller.js +0 -41
- package/dist/context/resolveAuthentication.js +0 -107
- package/dist/context/resolveStrategyCaller.js +0 -56
- package/dist/email/renderAuthEmail.js +0 -98
- package/dist/email/resolveThemeLogo.js +0 -35
- package/dist/routes/agent/prepareAgent.js +0 -169
- package/dist/routes/auth/buildAdminPlugin.js +0 -55
- package/dist/routes/auth/buildCaptchaPlugin.js +0 -61
- package/dist/routes/auth/buildPhoneNumberPlugin.js +0 -57
- package/dist/routes/auth/buildProviders.js +0 -51
- package/dist/routes/auth/createAuthLogger.js +0 -31
- package/dist/routes/auth/createSendEmail.js +0 -49
- package/dist/routes/auth/getBetterAuth.js +0 -72
- package/dist/routes/auth/getBetterAuthConfig.js +0 -439
- package/dist/routes/auth/getUserAdminRole.js +0 -32
- package/dist/routes/auth/hooks/authHookPoints.js +0 -192
- package/dist/routes/auth/hooks/buildEngineHooks.js +0 -43
- package/dist/routes/auth/hooks/buildHooks.js +0 -111
- package/dist/routes/auth/hooks/composeBeforeSlot.js +0 -41
- package/dist/routes/auth/hooks/createHookDispatch.js +0 -59
- package/dist/routes/auth/hooks/createUserAfterHook.js +0 -33
- package/dist/routes/auth/hooks/createUserBeforeHook.js +0 -47
- package/dist/routes/auth/hooks/findHookUser.js +0 -27
- package/dist/routes/auth/modelNames.js +0 -29
- package/dist/routes/auth/organizations/buildOrganizationPlugin.js +0 -136
- package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +0 -211
- package/dist/routes/auth/organizations/createAfterAcceptInvitationHook.js +0 -75
- package/dist/routes/auth/organizations/createAutoJoinHook.js +0 -63
- package/dist/routes/auth/organizations/ensureOrganization.js +0 -95
- package/dist/routes/auth/organizations/findPendingInvitation.js +0 -43
- package/dist/routes/auth/organizations/getOrganizationBinding.js +0 -65
- package/dist/routes/auth/organizations/resolvePinnedOrganization.js +0 -48
- package/dist/routes/auth/organizations/syncUserAdminRole.js +0 -102
- package/dist/routes/auth/resolveCookiePrefix.js +0 -30
- package/dist/routes/auth/strategies/createAuthStrategies.js +0 -77
- package/dist/routes/endpoints/handleAgentCall.js +0 -83
- package/dist/routes/endpoints/handleAuthStep.js +0 -124
- package/dist/routes/endpoints/handleRenderNotification.js +0 -189
- package/dist/routes/endpoints/runDetachedEndpoint.js +0 -85
- package/dist/routes/endpoints/runScheduledEndpoint.js +0 -102
- package/dist/routes/endpoints/runWebhookEndpoint.js +0 -118
- package/dist/routes/endpoints/runWebhookVerify.js +0 -94
- package/dist/routes/endpoints/scheduleBackground.js +0 -48
- package/dist/routes/notifications/derivePreview.js +0 -30
- package/dist/routes/notifications/getNotificationConfig.js +0 -32
- package/dist/routes/notifications/resolveNotificationLinks.js +0 -72
- package/dist/routes/page/dynamic/resolveDynamicContent.js +0 -172
- package/dist/routes/page/dynamic/unescapeOperators.js +0 -36
- package/dist/routes/page/dynamic/validateFragment.js +0 -104
- package/dist/routes/request/resolveTenant.js +0 -57
- package/dist/routes/websocket/createChannelRegistry.js +0 -278
- package/dist/routes/websocket/createWebSocketConnection.js +0 -131
- package/dist/routes/websocket/getWebsocketResolver.js +0 -33
- package/dist/routes/websocket/prepareChannel.js +0 -84
|
@@ -1,189 +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 { validate } from '@lowdefy/ajv';
|
|
16
|
-
import { ConfigError } from '@lowdefy/errors';
|
|
17
|
-
import { type } from '@lowdefy/helpers';
|
|
18
|
-
import addStepResult from './addStepResult.js';
|
|
19
|
-
import derivePreview from '../notifications/derivePreview.js';
|
|
20
|
-
import getNotificationConfig from '../notifications/getNotificationConfig.js';
|
|
21
|
-
import resolveNotificationLinks from '../notifications/resolveNotificationLinks.js';
|
|
22
|
-
import resolveThemeLogo from '../../email/resolveThemeLogo.js';
|
|
23
|
-
function itemHasPageLinks(item, dataKeys) {
|
|
24
|
-
const links = Object.values(item.links ?? {});
|
|
25
|
-
const arrayLinks = dataKeys.flatMap((key)=>(type.isArray(item[key]) ? item[key] : []).map((entry)=>entry?.link));
|
|
26
|
-
return [
|
|
27
|
-
...links,
|
|
28
|
-
...arrayLinks
|
|
29
|
-
].some((link)=>type.isObject(link) && !type.isNone(link.pageId));
|
|
30
|
-
}
|
|
31
|
-
async function handleRenderNotification(context, routineContext, { step }) {
|
|
32
|
-
const { logger, evaluateOperators } = context;
|
|
33
|
-
logger.debug({
|
|
34
|
-
event: 'debug_start_render_notification',
|
|
35
|
-
step
|
|
36
|
-
});
|
|
37
|
-
const evaluatedProperties = evaluateOperators({
|
|
38
|
-
input: step.properties,
|
|
39
|
-
items: routineContext.items,
|
|
40
|
-
location: step.stepId,
|
|
41
|
-
payload: routineContext.payload,
|
|
42
|
-
state: routineContext.state,
|
|
43
|
-
steps: routineContext.steps
|
|
44
|
-
});
|
|
45
|
-
const { notificationId, data, landingPage, recordId } = evaluatedProperties;
|
|
46
|
-
let { serverUrl } = evaluatedProperties;
|
|
47
|
-
if (!type.isString(notificationId)) {
|
|
48
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.notificationId must evaluate to a string. Received ${JSON.stringify(notificationId)}.`, {
|
|
49
|
-
configKey: step['~k']
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
if (type.isArray(data)) {
|
|
53
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.data must evaluate to an object. Received an array — iterate with a ":for" control and render one item per step.`, {
|
|
54
|
-
configKey: step['~k']
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
if (!type.isObject(data)) {
|
|
58
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.data must evaluate to an object. Received ${JSON.stringify(data)}.`, {
|
|
59
|
-
configKey: step['~k']
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
if (!type.isNone(serverUrl)) {
|
|
63
|
-
if (!type.isString(serverUrl) || serverUrl === '') {
|
|
64
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.serverUrl must evaluate to a non-empty string. Received ${JSON.stringify(serverUrl)}.`, {
|
|
65
|
-
configKey: step['~k']
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
serverUrl = serverUrl.replace(/\/$/, '');
|
|
69
|
-
}
|
|
70
|
-
if (!type.isNone(landingPage) && !type.isString(landingPage)) {
|
|
71
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage must evaluate to a string. Received ${JSON.stringify(landingPage)}.`, {
|
|
72
|
-
configKey: step['~k']
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
if (!type.isNone(recordId) && !type.isString(recordId)) {
|
|
76
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.recordId must evaluate to a string. Received ${JSON.stringify(recordId)}.`, {
|
|
77
|
-
configKey: step['~k']
|
|
78
|
-
});
|
|
79
|
-
}
|
|
80
|
-
const notificationConfig = await getNotificationConfig(context, {
|
|
81
|
-
notificationId,
|
|
82
|
-
configKey: step['~k']
|
|
83
|
-
});
|
|
84
|
-
const configKey = notificationConfig['~k'];
|
|
85
|
-
const Template = context.notifications[notificationConfig.type];
|
|
86
|
-
if (!Template) {
|
|
87
|
-
throw new ConfigError(`Notification template type "${notificationConfig.type}" can not be found.`, {
|
|
88
|
-
configKey
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
const { renderEmail, interpolateProperties } = context;
|
|
92
|
-
if (!type.isFunction(renderEmail) || !type.isFunction(interpolateProperties)) {
|
|
93
|
-
// plugins/notifications.js exports real implementations whenever the app
|
|
94
|
-
// has notifications built — reaching this means the build artifact and
|
|
95
|
-
// config are out of sync.
|
|
96
|
-
throw new ConfigError('Email rendering is not available. Rebuild the app — @lowdefy/email-templates is installed when "notifications:" is configured.', {
|
|
97
|
-
configKey
|
|
98
|
-
});
|
|
99
|
-
}
|
|
100
|
-
const app = await context.readConfigFile('app.json') ?? {};
|
|
101
|
-
const basePath = context.config?.basePath ?? '';
|
|
102
|
-
// Resolve after the merge so a per-notification theme.logo override also
|
|
103
|
-
// resolves; precedence stays notification theme over app.email.
|
|
104
|
-
const theme = resolveThemeLogo({
|
|
105
|
-
theme: {
|
|
106
|
-
...app.email ?? {},
|
|
107
|
-
...notificationConfig.theme ?? {}
|
|
108
|
-
},
|
|
109
|
-
serverUrl,
|
|
110
|
-
basePath
|
|
111
|
-
});
|
|
112
|
-
if (itemHasPageLinks(data, Template.dataKeys ?? [])) {
|
|
113
|
-
if (type.isNone(serverUrl)) {
|
|
114
|
-
throw new ConfigError(`Notification "${notificationId}" has links but no server URL is available. Set the serverUrl step property.`, {
|
|
115
|
-
configKey: step['~k']
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
// Landing URLs embed the record id — without it the landing page cannot
|
|
119
|
-
// resolve the record and every link in the email would be dead.
|
|
120
|
-
if (!type.isNone(landingPage) && type.isNone(recordId)) {
|
|
121
|
-
throw new ConfigError(`RenderNotification step "${step.stepId}" properties.landingPage requires properties.recordId to compose landing URLs.`, {
|
|
122
|
-
configKey: step['~k']
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
const resolvedItem = resolveNotificationLinks({
|
|
127
|
-
item: data,
|
|
128
|
-
dataKeys: Template.dataKeys ?? [],
|
|
129
|
-
serverUrl: serverUrl ?? '',
|
|
130
|
-
basePath,
|
|
131
|
-
landingPage,
|
|
132
|
-
recordId
|
|
133
|
-
});
|
|
134
|
-
let interpolated;
|
|
135
|
-
try {
|
|
136
|
-
interpolated = interpolateProperties({
|
|
137
|
-
properties: notificationConfig.properties,
|
|
138
|
-
data: resolvedItem,
|
|
139
|
-
markdownProperties: Template.markdownProperties ?? []
|
|
140
|
-
});
|
|
141
|
-
} catch (error) {
|
|
142
|
-
throw new ConfigError(`Notification "${notificationId}" template interpolation failed: ${error.message}`, {
|
|
143
|
-
configKey,
|
|
144
|
-
cause: error
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
if (Template.schema) {
|
|
148
|
-
const { valid, errors } = validate({
|
|
149
|
-
schema: Template.schema,
|
|
150
|
-
data: interpolated,
|
|
151
|
-
returnErrors: true
|
|
152
|
-
});
|
|
153
|
-
if (!valid) {
|
|
154
|
-
throw new ConfigError(`Notification "${notificationId}" properties do not match template "${notificationConfig.type}" schema: ${errors?.[0]?.message}.`, {
|
|
155
|
-
configKey
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
const { html, text } = await renderEmail({
|
|
160
|
-
Template,
|
|
161
|
-
properties: interpolated,
|
|
162
|
-
data: resolvedItem,
|
|
163
|
-
theme,
|
|
164
|
-
links: resolvedItem.links ?? {}
|
|
165
|
-
});
|
|
166
|
-
const result = {
|
|
167
|
-
subject: interpolated.subject,
|
|
168
|
-
title: interpolated.title ?? interpolated.subject,
|
|
169
|
-
preview: derivePreview({
|
|
170
|
-
properties: interpolated
|
|
171
|
-
}),
|
|
172
|
-
html,
|
|
173
|
-
text,
|
|
174
|
-
data: resolvedItem
|
|
175
|
-
};
|
|
176
|
-
addStepResult(context, routineContext, {
|
|
177
|
-
result,
|
|
178
|
-
stepId: step.stepId
|
|
179
|
-
});
|
|
180
|
-
logger.debug({
|
|
181
|
-
event: 'debug_end_render_notification',
|
|
182
|
-
stepId: step.stepId,
|
|
183
|
-
notificationId
|
|
184
|
-
});
|
|
185
|
-
return {
|
|
186
|
-
status: 'continue'
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
export default handleRenderNotification;
|
|
@@ -1,85 +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 { serializer } from '@lowdefy/helpers';
|
|
16
|
-
import applySystemTrust from '../../context/applySystemTrust.js';
|
|
17
|
-
import createAuthorize from '../../context/createAuthorize.js';
|
|
18
|
-
import createEvaluateOperators from '../../context/createEvaluateOperators.js';
|
|
19
|
-
import getEndpointConfig from './getEndpointConfig.js';
|
|
20
|
-
import runRoutine from './runRoutine.js';
|
|
21
|
-
// Runs an endpoint invoked through the detached route (a CallApi step with
|
|
22
|
-
// `detached: true` fire-and-forgets an HTTP call back to the deployment, so the
|
|
23
|
-
// target runs in its OWN function invocation with a fresh duration budget).
|
|
24
|
-
// The transport is authorized by CRON_SECRET, which proves the loopback request
|
|
25
|
-
// originated from the deployment (an ORIGIN proof, not an identity). A detached
|
|
26
|
-
// call is a fresh invocation, not a fresh principal (Decision 4): it runs with
|
|
27
|
-
// the SAME identity the dispatching run had, carried across the hop and
|
|
28
|
-
// rehydrated here. There is no detached-specific authorization rule - nested
|
|
29
|
-
// calls flow through the normal `authorize` path against the carried identity.
|
|
30
|
-
// Payload arrives serialized (dates etc. survive the HTTP hop via
|
|
31
|
-
// @lowdefy/helpers serializer).
|
|
32
|
-
async function runDetachedEndpoint(context, { endpointId, payload, principal }) {
|
|
33
|
-
const { logger } = context;
|
|
34
|
-
context.endpointId = endpointId;
|
|
35
|
-
// Rehydrate the dispatcher's identity carried across the CRON_SECRET-gated
|
|
36
|
-
// hop BEFORE deriving authorize and evaluateOperators, so both the auth check
|
|
37
|
-
// and the `_user` operator see the carried identity. This is a sanctioned
|
|
38
|
-
// substitute writer for resolveAuthentication - the principal was resolved
|
|
39
|
-
// upstream and built server-side, never from user input. A stale principal
|
|
40
|
-
// (roles changed between dispatch and run) is acceptable for at-most-once
|
|
41
|
-
// fire-and-forget - no re-resolution.
|
|
42
|
-
if (principal?.system === true) {
|
|
43
|
-
// The dispatcher was a trusted system context (cron, hook, or a verified
|
|
44
|
-
// webhook) - the detached run inherits it and blanket-passes.
|
|
45
|
-
applySystemTrust(context);
|
|
46
|
-
} else {
|
|
47
|
-
// The dispatcher was a real user (or a strategy caller) - carry that
|
|
48
|
-
// identity. This is NOT a system context (context.system stays unset), so
|
|
49
|
-
// nested authorization is re-checked against these roles exactly as it
|
|
50
|
-
// would be in-invocation - the run reaches nothing the dispatcher could not
|
|
51
|
-
// reach synchronously.
|
|
52
|
-
context.user = serializer.deserialize(principal?.user ?? null);
|
|
53
|
-
context.authorize = createAuthorize(context);
|
|
54
|
-
}
|
|
55
|
-
context.evaluateOperators = createEvaluateOperators(context);
|
|
56
|
-
logger.debug({
|
|
57
|
-
event: 'debug_detached_endpoint',
|
|
58
|
-
endpointId
|
|
59
|
-
});
|
|
60
|
-
const endpointConfig = await getEndpointConfig(context, {
|
|
61
|
-
endpointId
|
|
62
|
-
});
|
|
63
|
-
const routineContext = {
|
|
64
|
-
steps: {},
|
|
65
|
-
payload: serializer.deserialize(payload ?? {}),
|
|
66
|
-
arrayIndices: [],
|
|
67
|
-
items: {},
|
|
68
|
-
state: {},
|
|
69
|
-
endpointDepth: 0
|
|
70
|
-
};
|
|
71
|
-
const { error, response, status } = await runRoutine(context, routineContext, {
|
|
72
|
-
routine: endpointConfig.routine
|
|
73
|
-
});
|
|
74
|
-
const success = ![
|
|
75
|
-
'error',
|
|
76
|
-
'reject'
|
|
77
|
-
].includes(status);
|
|
78
|
-
return {
|
|
79
|
-
error: serializer.serialize(error),
|
|
80
|
-
response: serializer.serialize(response),
|
|
81
|
-
status: success ? 'success' : status,
|
|
82
|
-
success
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
export default runDetachedEndpoint;
|
|
@@ -1,102 +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 { serializer } from '@lowdefy/helpers';
|
|
16
|
-
import { ConfigError } from '@lowdefy/errors';
|
|
17
|
-
import applySystemTrust from '../../context/applySystemTrust.js';
|
|
18
|
-
import createEvaluateOperators from '../../context/createEvaluateOperators.js';
|
|
19
|
-
import getEndpointConfig from './getEndpointConfig.js';
|
|
20
|
-
import runRoutine from './runRoutine.js';
|
|
21
|
-
import scheduleBackground from './scheduleBackground.js';
|
|
22
|
-
// Runs an endpoint routine on a schedule (cron). Unlike callEndpoint this does NOT check the
|
|
23
|
-
// endpoint's `auth` config and does NOT block InternalApi: a cron run is authorized by the transport
|
|
24
|
-
// layer (CRON_SECRET) plus the endpoint declaring the firing schedule, and runs as a system context
|
|
25
|
-
// (no user session, so `_user` resolves to undefined). An InternalApi with schedules is therefore a
|
|
26
|
-
// cron-only endpoint that is never client-callable.
|
|
27
|
-
async function runScheduledEndpoint(context, { endpointId, cron }) {
|
|
28
|
-
const { logger } = context;
|
|
29
|
-
context.endpointId = endpointId;
|
|
30
|
-
context.evaluateOperators = createEvaluateOperators(context);
|
|
31
|
-
logger.debug({
|
|
32
|
-
event: 'debug_scheduled_endpoint',
|
|
33
|
-
endpointId,
|
|
34
|
-
cron
|
|
35
|
-
});
|
|
36
|
-
const endpointConfig = await getEndpointConfig(context, {
|
|
37
|
-
endpointId
|
|
38
|
-
});
|
|
39
|
-
const schedules = endpointConfig.schedules;
|
|
40
|
-
if (!Array.isArray(schedules) || schedules.length === 0) {
|
|
41
|
-
throw new ConfigError(`API Endpoint "${endpointId}" is not scheduled.`);
|
|
42
|
-
}
|
|
43
|
-
// Vercel sends the firing expression in x-vercel-cron-schedule; cron expressions are unique per
|
|
44
|
-
// endpoint (enforced at build) so this is unambiguous. Without a cron (e.g. local testing) fall
|
|
45
|
-
// back to the single schedule, otherwise require it to disambiguate the payload.
|
|
46
|
-
let schedule;
|
|
47
|
-
if (cron) {
|
|
48
|
-
schedule = schedules.find((s)=>s.cron === cron);
|
|
49
|
-
} else if (schedules.length === 1) {
|
|
50
|
-
schedule = schedules[0];
|
|
51
|
-
}
|
|
52
|
-
if (!schedule) {
|
|
53
|
-
throw new ConfigError(`No schedule matching cron "${cron}" for API Endpoint "${endpointId}".`);
|
|
54
|
-
}
|
|
55
|
-
// Cron is trusted at the transport (CRON_SECRET), so it holds a system
|
|
56
|
-
// context from construction, regardless of any session cookie sent with the
|
|
57
|
-
// request (Decisions 1, 2). The request context is a pre-resolved substitute
|
|
58
|
-
// writer for resolveAuthentication - the engine's single-writer carve-out -
|
|
59
|
-
// and applySystemTrust sets the same invariant bundle createSystemContext
|
|
60
|
-
// produces for the hook path.
|
|
61
|
-
applySystemTrust(context);
|
|
62
|
-
const routineContext = {
|
|
63
|
-
steps: {},
|
|
64
|
-
payload: schedule.payload ?? {},
|
|
65
|
-
arrayIndices: [],
|
|
66
|
-
items: {},
|
|
67
|
-
state: {},
|
|
68
|
-
endpointDepth: 0
|
|
69
|
-
};
|
|
70
|
-
// async: true — acknowledge the cron trigger immediately and run in the
|
|
71
|
-
// background; transport auth (CRON_SECRET) already passed at the route.
|
|
72
|
-
if (endpointConfig.async === true) {
|
|
73
|
-
scheduleBackground(context, {
|
|
74
|
-
event: 'background_scheduled_endpoint',
|
|
75
|
-
endpointId
|
|
76
|
-
}, ()=>runRoutine(context, routineContext, {
|
|
77
|
-
routine: endpointConfig.routine
|
|
78
|
-
}));
|
|
79
|
-
return {
|
|
80
|
-
error: null,
|
|
81
|
-
response: serializer.serialize({
|
|
82
|
-
accepted: true
|
|
83
|
-
}),
|
|
84
|
-
status: 'accepted',
|
|
85
|
-
success: true
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
const { error, response, status } = await runRoutine(context, routineContext, {
|
|
89
|
-
routine: endpointConfig.routine
|
|
90
|
-
});
|
|
91
|
-
const success = ![
|
|
92
|
-
'error',
|
|
93
|
-
'reject'
|
|
94
|
-
].includes(status);
|
|
95
|
-
return {
|
|
96
|
-
error: serializer.serialize(error),
|
|
97
|
-
response: serializer.serialize(response),
|
|
98
|
-
status: success ? 'success' : status,
|
|
99
|
-
success
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
export default runScheduledEndpoint;
|
|
@@ -1,118 +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 { serializer, type } from '@lowdefy/helpers';
|
|
16
|
-
import { ConfigError } from '@lowdefy/errors';
|
|
17
|
-
import applySystemTrust from '../../context/applySystemTrust.js';
|
|
18
|
-
import createAuthorize from '../../context/createAuthorize.js';
|
|
19
|
-
import createEvaluateOperators from '../../context/createEvaluateOperators.js';
|
|
20
|
-
import getEndpointConfig from './getEndpointConfig.js';
|
|
21
|
-
import runRoutine from './runRoutine.js';
|
|
22
|
-
import runWebhookVerify from './runWebhookVerify.js';
|
|
23
|
-
// Runs an endpoint declared `webhook` — a third-party webhook receiver
|
|
24
|
-
// (SNS, Event Grid, Stripe, ...) served on the standard /api/endpoints route,
|
|
25
|
-
// but taking the request RAW: bodies are the caller's own format, not
|
|
26
|
-
// Lowdefy's { payload } envelope, so the routine receives
|
|
27
|
-
// { body, query, headers } as its payload and its return value is sent back
|
|
28
|
-
// verbatim (handshakes require exact response shapes). Only endpoints that
|
|
29
|
-
// opt in are runnable here (a missing flag reads as a missing endpoint — no
|
|
30
|
-
// probing).
|
|
31
|
-
//
|
|
32
|
-
// The transport is public by design, so the run starts caller-less AND
|
|
33
|
-
// UNTRUSTED (Decision 3): context.user = null, context.system unset. It earns
|
|
34
|
-
// trust only when its declared `webhook.verify` gate passes, run mechanically
|
|
35
|
-
// BEFORE the routine body - so verification can never be forgotten, mis-ordered,
|
|
36
|
-
// or placed after a privileged CallApi. A webhook with no declared verifier
|
|
37
|
-
// runs untrusted throughout, so any nested protected CallApi fails closed.
|
|
38
|
-
async function runWebhookEndpoint(context, { endpointId, body, query, headers }) {
|
|
39
|
-
const { logger } = context;
|
|
40
|
-
context.endpointId = endpointId;
|
|
41
|
-
context.evaluateOperators = createEvaluateOperators(context);
|
|
42
|
-
logger.debug({
|
|
43
|
-
event: 'debug_webhook_endpoint',
|
|
44
|
-
endpointId
|
|
45
|
-
});
|
|
46
|
-
const endpointConfig = await getEndpointConfig(context, {
|
|
47
|
-
endpointId
|
|
48
|
-
});
|
|
49
|
-
// webhook may be `true` or a `{ verify }` object — gate on truthiness.
|
|
50
|
-
if (!endpointConfig.webhook) {
|
|
51
|
-
const err = new ConfigError(`API Endpoint "${endpointId}" does not exist.`);
|
|
52
|
-
logger.debug({
|
|
53
|
-
params: {
|
|
54
|
-
endpointId
|
|
55
|
-
},
|
|
56
|
-
err
|
|
57
|
-
}, err.message);
|
|
58
|
-
throw err;
|
|
59
|
-
}
|
|
60
|
-
// Caller-less and UNTRUSTED: with context.system unset, createAuthorize fails
|
|
61
|
-
// closed on any protected target exactly as an unauthenticated call would
|
|
62
|
-
// (Api and InternalApi alike — InternalApi is an HTTP-exposure choice, not a
|
|
63
|
-
// trust tier, so it earns no special pass).
|
|
64
|
-
context.user = null;
|
|
65
|
-
context.authorize = createAuthorize(context);
|
|
66
|
-
// A declared verifier is the only thing that can make the run trusted, and it
|
|
67
|
-
// runs before any routine step. On success the runner (not routine or
|
|
68
|
-
// resolver code) sets context.system, matching the state createSystemContext
|
|
69
|
-
// produces for cron. On failure the routine never runs.
|
|
70
|
-
const verify = type.isObject(endpointConfig.webhook) ? endpointConfig.webhook.verify : undefined;
|
|
71
|
-
if (!type.isNone(verify)) {
|
|
72
|
-
const verified = await runWebhookVerify(context, {
|
|
73
|
-
verify,
|
|
74
|
-
body,
|
|
75
|
-
query,
|
|
76
|
-
headers
|
|
77
|
-
});
|
|
78
|
-
if (!verified) {
|
|
79
|
-
logger.warn({
|
|
80
|
-
event: 'webhook_verify_failed',
|
|
81
|
-
endpointId
|
|
82
|
-
});
|
|
83
|
-
return {
|
|
84
|
-
error: null,
|
|
85
|
-
response: null,
|
|
86
|
-
status: 'unauthorized',
|
|
87
|
-
success: false
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
applySystemTrust(context);
|
|
91
|
-
}
|
|
92
|
-
const routineContext = {
|
|
93
|
-
steps: {},
|
|
94
|
-
payload: {
|
|
95
|
-
body: body ?? null,
|
|
96
|
-
query: query ?? {},
|
|
97
|
-
headers: headers ?? {}
|
|
98
|
-
},
|
|
99
|
-
arrayIndices: [],
|
|
100
|
-
items: {},
|
|
101
|
-
state: {},
|
|
102
|
-
endpointDepth: 0
|
|
103
|
-
};
|
|
104
|
-
const { error, response, status } = await runRoutine(context, routineContext, {
|
|
105
|
-
routine: endpointConfig.routine
|
|
106
|
-
});
|
|
107
|
-
const success = ![
|
|
108
|
-
'error',
|
|
109
|
-
'reject'
|
|
110
|
-
].includes(status);
|
|
111
|
-
return {
|
|
112
|
-
error: serializer.serialize(error),
|
|
113
|
-
response: serializer.serialize(response),
|
|
114
|
-
status: success ? 'success' : status,
|
|
115
|
-
success
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
export default runWebhookEndpoint;
|
|
@@ -1,94 +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
|
-
import callRequestResolver from '../request/callRequestResolver.js';
|
|
17
|
-
import evaluateRequestOperators from '../request/evaluateOperators.js';
|
|
18
|
-
import getConnection from '../connections/getConnection.js';
|
|
19
|
-
import getConnectionConfig from '../connections/getConnectionConfig.js';
|
|
20
|
-
import getRequestResolver from '../request/getRequestResolver.js';
|
|
21
|
-
import resolveTenant from '../request/resolveTenant.js';
|
|
22
|
-
// Runs the endpoint's declared `webhook.verify` request plugin as a gate,
|
|
23
|
-
// against the RAW request (body, query, headers), before the routine body
|
|
24
|
-
// (Decision 3). The verifier is a request plugin - the same class of code as a
|
|
25
|
-
// connection request - resolved and invoked through the request-plugin
|
|
26
|
-
// machinery, never as a routine step. It reads the request and reports a
|
|
27
|
-
// verdict; the RUNNER (not routine or resolver code) performs the trust
|
|
28
|
-
// transition, so there is no trust-writing capability on the resolver surface.
|
|
29
|
-
//
|
|
30
|
-
// Returns true only when the verifier passes: it must not throw and must return
|
|
31
|
-
// `true` or `{ verified: true }`. A verifier that throws (e.g. a bad signature)
|
|
32
|
-
// is a failed gate, not a server fault - it fails closed to a false verdict.
|
|
33
|
-
// Config-resolution errors (missing connection / unknown request type) throw:
|
|
34
|
-
// a misconfigured verifier breaks loudly in development rather than silently
|
|
35
|
-
// trusting or silently failing.
|
|
36
|
-
async function runWebhookVerify(context, { verify, body, query, headers }) {
|
|
37
|
-
const payload = {
|
|
38
|
-
body: body ?? null,
|
|
39
|
-
query: query ?? {},
|
|
40
|
-
headers: headers ?? {}
|
|
41
|
-
};
|
|
42
|
-
const connectionConfig = await getConnectionConfig(context, {
|
|
43
|
-
connectionId: verify.connectionId,
|
|
44
|
-
configKey: verify['~k']
|
|
45
|
-
});
|
|
46
|
-
const connection = getConnection(context, {
|
|
47
|
-
connectionConfig
|
|
48
|
-
});
|
|
49
|
-
const requestConfig = {
|
|
50
|
-
type: verify.type,
|
|
51
|
-
connectionId: verify.connectionId,
|
|
52
|
-
requestId: 'webhook.verify',
|
|
53
|
-
properties: verify.properties ?? {},
|
|
54
|
-
// Webhooks run in system context, so a verifier on a tenant connection
|
|
55
|
-
// fails closed (caught below, verdict false) unless the verify config
|
|
56
|
-
// opts out with tenant: none.
|
|
57
|
-
tenant: verify.tenant,
|
|
58
|
-
'~k': verify['~k']
|
|
59
|
-
};
|
|
60
|
-
const requestResolver = getRequestResolver(context, {
|
|
61
|
-
connection,
|
|
62
|
-
requestConfig
|
|
63
|
-
});
|
|
64
|
-
const tenant = resolveTenant(context, {
|
|
65
|
-
connection,
|
|
66
|
-
connectionConfig,
|
|
67
|
-
requestConfig
|
|
68
|
-
});
|
|
69
|
-
const { connectionProperties, requestProperties } = evaluateRequestOperators(context, {
|
|
70
|
-
connectionConfig,
|
|
71
|
-
payload,
|
|
72
|
-
requestConfig,
|
|
73
|
-
state: {},
|
|
74
|
-
steps: {}
|
|
75
|
-
});
|
|
76
|
-
try {
|
|
77
|
-
const response = await callRequestResolver(context, {
|
|
78
|
-
connectionProperties,
|
|
79
|
-
endpointDepth: 0,
|
|
80
|
-
requestConfig,
|
|
81
|
-
requestProperties,
|
|
82
|
-
requestResolver,
|
|
83
|
-
tenant
|
|
84
|
-
});
|
|
85
|
-
return response === true || type.isObject(response) && response.verified === true;
|
|
86
|
-
} catch (error) {
|
|
87
|
-
context.logger.debug({
|
|
88
|
-
event: 'debug_webhook_verify_error',
|
|
89
|
-
err: error
|
|
90
|
-
}, error.message);
|
|
91
|
-
return false;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
export default runWebhookVerify;
|
|
@@ -1,48 +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
|
-
*/ // Run work after the response is sent. Platforms that reap the invocation once
|
|
16
|
-
// the response is flushed (Vercel fluid compute) inject context.waitUntil in
|
|
17
|
-
// their server's apiContext middleware to keep the invocation alive until the
|
|
18
|
-
// promise settles (bounded by the function's maxDuration); locally /
|
|
19
|
-
// self-hosted there is no waitUntil and the promise simply runs detached on
|
|
20
|
-
// the still-alive Node process.
|
|
21
|
-
//
|
|
22
|
-
// The outcome only exists in logs — completion and failure are logged through
|
|
23
|
-
// the request logger so they reach the platform log stream (and any log
|
|
24
|
-
// drains); a background failure must never surface as an unhandled rejection.
|
|
25
|
-
function scheduleBackground(context, { event, endpointId }, fn) {
|
|
26
|
-
const { logger } = context;
|
|
27
|
-
const promise = (async ()=>{
|
|
28
|
-
try {
|
|
29
|
-
const result = await fn();
|
|
30
|
-
logger.info({
|
|
31
|
-
event: `${event}_done`,
|
|
32
|
-
endpointId,
|
|
33
|
-
status: result?.status
|
|
34
|
-
});
|
|
35
|
-
} catch (err) {
|
|
36
|
-
logger.error({
|
|
37
|
-
event: `${event}_failed`,
|
|
38
|
-
endpointId,
|
|
39
|
-
err
|
|
40
|
-
}, err.message);
|
|
41
|
-
}
|
|
42
|
-
})();
|
|
43
|
-
if (context.waitUntil) {
|
|
44
|
-
context.waitUntil(promise);
|
|
45
|
-
}
|
|
46
|
-
return promise;
|
|
47
|
-
}
|
|
48
|
-
export default scheduleBackground;
|
|
@@ -1,30 +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
|
-
// Rough inversion of the interpolation pipeline for the preview text: strip
|
|
17
|
-
// author markdown syntax and unescape the backslash-escaped interpolated values.
|
|
18
|
-
function stripMarkdown(text) {
|
|
19
|
-
return text.replace(/```[\s\S]*?```/g, ' ').replace(/`([^`]*)`/g, '$1').replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/^#{1,6}\s+/gm, '').replace(/^\s*>\s?/gm, '').replace(/^\s*[-*+]\s+/gm, '').replace(/(\*\*|__|\*|_|~~)/g, '').replace(/\\([!-/:-@[-`{-~])/g, '$1').replace(/\s+/g, ' ').trim();
|
|
20
|
-
}
|
|
21
|
-
function derivePreview({ properties }) {
|
|
22
|
-
if (type.isString(properties.preview) && properties.preview !== '') {
|
|
23
|
-
return properties.preview;
|
|
24
|
-
}
|
|
25
|
-
if (type.isString(properties.message) && properties.message !== '') {
|
|
26
|
-
return stripMarkdown(properties.message).slice(0, 140);
|
|
27
|
-
}
|
|
28
|
-
return null;
|
|
29
|
-
}
|
|
30
|
-
export default derivePreview;
|