@plitzi/sdk-actions 0.0.0-stage → 0.39.3
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/CHANGELOG.md +18 -0
- package/README.md +54 -2
- package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
- package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
- package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
- package/dist/chunks/load-DBWRZn7G.mjs +48 -0
- package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
- package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
- package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
- package/dist/chunks/remote-DopPgCMK.mjs +404 -0
- package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
- package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
- package/dist/connectors/connectors.d.ts +7 -0
- package/dist/connectors/engine.d.ts +47 -0
- package/dist/connectors/getByPath.d.ts +8 -0
- package/dist/connectors/projection.d.ts +18 -0
- package/dist/connectors/resolver.d.ts +27 -0
- package/dist/connectors/types.d.ts +19 -0
- package/dist/engine/configSeam.d.ts +10 -0
- package/dist/engine/connectorWrite.d.ts +12 -0
- package/dist/engine/fileStore.d.ts +60 -0
- package/dist/engine/fleet.d.ts +20 -0
- package/dist/engine/jobs/calls.d.ts +49 -0
- package/dist/engine/jobs/claimSpaces.d.ts +10 -0
- package/dist/engine/jobs/codeMarks.d.ts +10 -0
- package/dist/engine/jobs/endings.d.ts +42 -0
- package/dist/engine/jobs/failureStreak.d.ts +15 -0
- package/dist/engine/jobs/fileQueue.d.ts +34 -0
- package/dist/engine/jobs/flow.d.ts +11 -0
- package/dist/engine/jobs/jobs.d.ts +36 -0
- package/dist/engine/jobs/later.d.ts +27 -0
- package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
- package/dist/engine/jobs/memoryQueue.d.ts +33 -0
- package/dist/engine/jobs/memoryWatch.d.ts +21 -0
- package/dist/engine/jobs/notNow.d.ts +39 -0
- package/dist/engine/jobs/queueDocument.d.ts +15 -0
- package/dist/engine/jobs/queueRules.d.ts +64 -0
- package/dist/engine/jobs/scheduler.d.ts +70 -0
- package/dist/engine/jobs/schedules.d.ts +24 -0
- package/dist/engine/jobs/storeClock.d.ts +16 -0
- package/dist/engine/jobs/wake.d.ts +6 -0
- package/dist/engine/jobs/worker.d.ts +99 -0
- package/dist/engine/module.d.ts +96 -0
- package/dist/engine/moduleFor.d.ts +3 -0
- package/dist/engine/runtime/check.d.ts +24 -0
- package/dist/engine/runtime/credentials.d.ts +8 -0
- package/dist/engine/runtime/deadline.d.ts +19 -0
- package/dist/engine/runtime/email.d.ts +38 -0
- package/dist/engine/runtime/errors.d.ts +28 -0
- package/dist/engine/runtime/fileKv.d.ts +35 -0
- package/dist/engine/runtime/flags.d.ts +16 -0
- package/dist/engine/runtime/guards.d.ts +190 -0
- package/dist/engine/runtime/kvList.d.ts +28 -0
- package/dist/engine/runtime/kvStore.d.ts +36 -0
- package/dist/engine/runtime/limits.d.ts +12 -0
- package/dist/engine/runtime/memoryKv.d.ts +28 -0
- package/dist/engine/runtime/namespaceKv.d.ts +9 -0
- package/dist/engine/runtime/precheck.d.ts +28 -0
- package/dist/engine/runtime/rateLimit.d.ts +9 -0
- package/dist/engine/runtime/redisKv.d.ts +27 -0
- package/dist/engine/runtime/renderFailure.d.ts +24 -0
- package/dist/engine/runtime/renderResolver.d.ts +16 -0
- package/dist/engine/runtime/renderShare.d.ts +12 -0
- package/dist/engine/runtime/report.d.ts +15 -0
- package/dist/engine/runtime/runAction.d.ts +26 -0
- package/dist/engine/runtime/runLogger.d.ts +37 -0
- package/dist/engine/runtime/runStats.d.ts +8 -0
- package/dist/engine/runtime/scope.d.ts +40 -0
- package/dist/engine/runtime/signing.d.ts +27 -0
- package/dist/engine/runtime/taskContext.d.ts +54 -0
- package/dist/engine/runtime/triggers.d.ts +12 -0
- package/dist/engine/taskCatalog.d.ts +28 -0
- package/dist/engine/tasks/auth.d.ts +2 -0
- package/dist/engine/tasks/builtins.d.ts +10 -0
- package/dist/engine/tasks/connector.d.ts +2 -0
- package/dist/engine/tasks/db.d.ts +2 -0
- package/dist/engine/tasks/email.d.ts +2 -0
- package/dist/engine/tasks/flow.d.ts +3 -0
- package/dist/engine/tasks/helpers.d.ts +16 -0
- package/dist/engine/tasks/http.d.ts +2 -0
- package/dist/engine/tasks/kv.d.ts +2 -0
- package/dist/engine/tasks/list.d.ts +2 -0
- package/dist/engine/tasks/names.d.ts +8 -0
- package/dist/engine/tasks/realtime.d.ts +3 -0
- package/dist/engine/tasks/registry.d.ts +19 -0
- package/dist/engine/tasks/transform.d.ts +2 -0
- package/dist/engine/transport/callHandler.d.ts +34 -0
- package/dist/engine/transport/cancelHandler.d.ts +23 -0
- package/dist/engine/transport/catalogHandler.d.ts +22 -0
- package/dist/engine/transport/stream.d.ts +22 -0
- package/dist/engine/transport/verifySignature.d.ts +16 -0
- package/dist/engine/transport/webhookHandler.d.ts +26 -0
- package/dist/engine/types.d.ts +442 -0
- package/dist/functions/build.d.ts +27 -0
- package/dist/functions/capabilities.d.ts +11 -0
- package/dist/functions/config.d.ts +111 -0
- package/dist/functions/context.d.ts +15 -0
- package/dist/functions/index.d.ts +17 -0
- package/dist/functions/index.mjs +461 -0
- package/dist/functions/jobControl.d.ts +22 -0
- package/dist/functions/jobs.d.ts +104 -0
- package/dist/functions/load.d.ts +22 -0
- package/dist/functions/local.d.ts +36 -0
- package/dist/functions/manifest.d.ts +32 -0
- package/dist/functions/native.d.ts +13 -0
- package/dist/functions/oauth.d.ts +33 -0
- package/dist/functions/routes.d.ts +50 -0
- package/dist/functions/runner/remote.d.ts +26 -0
- package/dist/functions/scope.d.ts +28 -0
- package/dist/functions/space.d.ts +41 -0
- package/dist/functions/tryEntry.d.ts +9 -0
- package/dist/index.d.ts +47 -0
- package/dist/index.mjs +545 -0
- package/dist/mongo/claimable.d.ts +5 -0
- package/dist/mongo/index.d.ts +4 -0
- package/dist/mongo/index.mjs +779 -0
- package/dist/mongo/jobQueue.d.ts +38 -0
- package/dist/mongo/kv.d.ts +15 -0
- package/dist/mysql/index.d.ts +5 -0
- package/dist/mysql/index.mjs +808 -0
- package/dist/mysql/jobQueue.d.ts +40 -0
- package/dist/mysql/kv.d.ts +18 -0
- package/dist/mysql/rows.d.ts +64 -0
- package/dist/mysql/schema.d.ts +28 -0
- package/dist/mysql/summary.d.ts +7 -0
- package/dist/realtime/declarations.d.ts +11 -0
- package/dist/realtime/failure.d.ts +6 -0
- package/dist/realtime/grants.d.ts +22 -0
- package/dist/realtime/handlers.d.ts +86 -0
- package/dist/realtime/hub.d.ts +71 -0
- package/dist/realtime/index.d.ts +105 -0
- package/dist/realtime/index.mjs +824 -0
- package/dist/realtime/jobs.d.ts +18 -0
- package/dist/realtime/message.d.ts +3 -0
- package/dist/realtime/presence.d.ts +33 -0
- package/dist/realtime/retained.d.ts +21 -0
- package/dist/realtime/socket.d.ts +30 -0
- package/dist/render/index.d.ts +10 -0
- package/dist/render/index.mjs +1 -0
- package/dist/render/protocol.d.ts +47 -0
- package/dist/render/remote.d.ts +16 -0
- package/dist/runtimes/bundle.d.ts +29 -0
- package/dist/runtimes/index.d.ts +3 -0
- package/dist/runtimes/index.mjs +229 -0
- package/dist/runtimes/stages.d.ts +52 -0
- package/dist/sqlite/index.d.ts +4 -0
- package/dist/sqlite/index.mjs +160 -0
- package/dist/sqlite/jobQueue.d.ts +35 -0
- package/dist/sqlite/kv.d.ts +34 -0
- package/dist/sqlite/open.d.ts +3 -0
- package/dist/types/config.d.ts +293 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.mjs +1 -0
- package/dist/types/jobs.d.ts +317 -0
- package/dist/worker/elsewhere.d.ts +16 -0
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.mjs +1703 -0
- package/dist/worker/origin.d.ts +12 -0
- package/dist/worker/pageEngine.d.ts +11 -0
- package/dist/worker/stages/action.d.ts +24 -0
- package/dist/worker/stages/cors.d.ts +9 -0
- package/dist/worker/stages/forward.d.ts +12 -0
- package/dist/worker/stages/functionRoutes.d.ts +10 -0
- package/dist/worker/stages/queuedCalls.d.ts +15 -0
- package/dist/worker/stages/realtime.d.ts +9 -0
- package/dist/worker/stages/render.d.ts +9 -0
- package/dist/worker/worker.d.ts +39 -0
- package/package.json +76 -3
|
@@ -0,0 +1,1703 @@
|
|
|
1
|
+
import { handleRealtimePublish, handleRealtimeSocket, handleRealtimeSubscribe, realtimeModuleFor } from "../realtime/index.mjs";
|
|
2
|
+
import { a as createActionResolver, i as readRenderAsk, n as RENDER_PATH, t as createRemoteRenderResolver } from "../chunks/remote-DopPgCMK.mjs";
|
|
3
|
+
import { F as readKeptCall, P as keepCall, R as writeConnectorRecord, S as ACTIONS_FLEET_STORES, h as precheckRun, t as createActionsModule } from "../chunks/module-WdDzbjHy.mjs";
|
|
4
|
+
import { a as triggerParams, i as findTriggerNode, t as ActionRunError } from "../chunks/errors-bCBfIe7c.mjs";
|
|
5
|
+
import { r as createConnectorResolver, t as describeCatalog } from "../chunks/taskCatalog-S1IozUTD.mjs";
|
|
6
|
+
import { t as isFunctionsDefinition } from "../chunks/load-DBWRZn7G.mjs";
|
|
7
|
+
import { privateOriginsOf } from "@plitzi/sdk-kernel/outbound";
|
|
8
|
+
import { isConnectorManifestDraft, validateConnectorManifest } from "@plitzi/sdk-shared/connectors";
|
|
9
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
10
|
+
import { isRecord } from "@plitzi/sdk-shared/helpers";
|
|
11
|
+
import { FUNCTION_ROUTES_PREFIX, isActionDocument, triggerAccess, triggerHasStaleVerify, triggerVerify, validateActionDocument } from "@plitzi/sdk-shared/actions";
|
|
12
|
+
import { configureServerLog, defaultLogLevel, serverLog } from "@plitzi/sdk-kernel/log";
|
|
13
|
+
import { statsRecorderFor, statsStage } from "@plitzi/sdk-kernel/stats";
|
|
14
|
+
import { protocolRefusal } from "@plitzi/sdk-shared/functions";
|
|
15
|
+
import { bearerMatches, clientIp, createHttpServer, createMiddlewaresStage, crossSiteWritesStage, healthStage, makeHandler, onAbort, openEventStream, readRawBody, readRawBytes, requestAuthority, requestOrigin, runsFleetJobs, writeWebResponse } from "@plitzi/sdk-kernel/http";
|
|
16
|
+
import { forcedFlagsFor } from "@plitzi/sdk-shared/flags";
|
|
17
|
+
import { resolveDebugAuthorization } from "@plitzi/sdk-kernel/identity";
|
|
18
|
+
import { request } from "node:http";
|
|
19
|
+
// src/engine/transport/stream.ts
|
|
20
|
+
/**
|
|
21
|
+
* How long a hand-rolled `EventSource` waits before reconnecting, if one ever gets here.
|
|
22
|
+
*
|
|
23
|
+
* A day, deliberately. `EventSource` reconnects whenever a stream ends — INCLUDING on normal completion — so a
|
|
24
|
+
* client using it would start a fresh run every time one finished, forever. Our own client uses `fetch` and a
|
|
25
|
+
* reader for exactly this reason; this value is what stops somebody else's from becoming a loop.
|
|
26
|
+
*/
|
|
27
|
+
var RETRY_MS = 864e5;
|
|
28
|
+
/**
|
|
29
|
+
* Opens a run's Server-Sent Events response.
|
|
30
|
+
*
|
|
31
|
+
* The run's id travels on the response head rather than in a frame: a streaming step returns as soon as the stream
|
|
32
|
+
* OPENS — that is what makes it a stream — so anything it learns from a frame arrives after the flow has already
|
|
33
|
+
* carried on. The head is the one place a caller can read the id in time to cancel the run it just started.
|
|
34
|
+
*/
|
|
35
|
+
var openStream = (raw, onAbort, runId) => {
|
|
36
|
+
const stream = openEventStream(raw, {
|
|
37
|
+
onAbort,
|
|
38
|
+
headers: { "X-Plitzi-Run-Id": runId },
|
|
39
|
+
retryMs: RETRY_MS
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
send: (frame) => stream.send(frame.event, frame.data),
|
|
43
|
+
close: stream.close,
|
|
44
|
+
isOpen: stream.isOpen
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
/** Whether this caller asked for a stream. The negotiation is the client's, so a page that cannot read one never
|
|
48
|
+
* gets one by accident. */
|
|
49
|
+
var wantsStream = (accept) => {
|
|
50
|
+
return (Array.isArray(accept) ? accept.join(",") : accept ?? "").includes("text/event-stream");
|
|
51
|
+
};
|
|
52
|
+
// src/engine/runtime/report.ts
|
|
53
|
+
/**
|
|
54
|
+
* Reports a request that never became a run.
|
|
55
|
+
*
|
|
56
|
+
* Its own function rather than a call at each refusal so the two transports cannot end up reporting different
|
|
57
|
+
* things — and so the rule that a report may not fail the answer is written once. A deployment's sink throwing
|
|
58
|
+
* must not turn a clean 401 into a 500: the caller was refused either way, and the refusal is the part that has
|
|
59
|
+
* to reach them.
|
|
60
|
+
*
|
|
61
|
+
* Nothing is filtered here. A duplicate delivery is a well-behaved sender retrying and an invalid signature is a
|
|
62
|
+
* broken integration, but which of those is worth a row in somebody's activity feed is a policy, and policies
|
|
63
|
+
* belong to the deployment.
|
|
64
|
+
*/
|
|
65
|
+
var reportReject = async (config, record) => {
|
|
66
|
+
if (config.stats) statsRecorderFor(config.stats, config.health?.version).refuse(record.reason);
|
|
67
|
+
try {
|
|
68
|
+
await config.action?.onReject?.(record);
|
|
69
|
+
} catch (error) {
|
|
70
|
+
serverLog.error("Actions", "reject record failed", error);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
// src/engine/transport/callHandler.ts
|
|
74
|
+
/**
|
|
75
|
+
* How a refusal reaches the caller.
|
|
76
|
+
*
|
|
77
|
+
* Every reason maps to a status the client can act on without parsing prose — a 409 means "your other run is still
|
|
78
|
+
* going", a 429 means "come back", a 508 means "you built a loop". `recursion` is the one worth the unusual code:
|
|
79
|
+
* 508 Loop Detected says exactly what happened, and anything else would read as a server fault.
|
|
80
|
+
*/
|
|
81
|
+
var STATUS_BY_REASON = {
|
|
82
|
+
not_found: 404,
|
|
83
|
+
disabled: 409,
|
|
84
|
+
unauthenticated: 401,
|
|
85
|
+
forbidden: 403,
|
|
86
|
+
invalid_input: 422,
|
|
87
|
+
duplicate: 409,
|
|
88
|
+
over_capacity: 429,
|
|
89
|
+
quota: 402,
|
|
90
|
+
recursion: 508,
|
|
91
|
+
timeout: 504,
|
|
92
|
+
aborted: 499,
|
|
93
|
+
failed: 500
|
|
94
|
+
};
|
|
95
|
+
var parseBody$1 = (body) => {
|
|
96
|
+
if (!body) return;
|
|
97
|
+
try {
|
|
98
|
+
const parsed = JSON.parse(body);
|
|
99
|
+
return parsed !== null && typeof parsed === "object" ? parsed : void 0;
|
|
100
|
+
} catch {
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
var send$2 = (res, status, payload, runId) => {
|
|
105
|
+
res.setStatus(status);
|
|
106
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
107
|
+
res.setHeader("Cache-Control", "no-store");
|
|
108
|
+
if (runId) res.setHeader("X-Plitzi-Run-Id", runId);
|
|
109
|
+
res.send(JSON.stringify(payload));
|
|
110
|
+
};
|
|
111
|
+
var fail$1 = (res, reason, error, runId) => send$2(res, STATUS_BY_REASON[reason], {
|
|
112
|
+
error,
|
|
113
|
+
reason
|
|
114
|
+
}, runId);
|
|
115
|
+
/**
|
|
116
|
+
* Whether the caller may be told what the flow DID, as opposed to what it answered.
|
|
117
|
+
*
|
|
118
|
+
* The dev-tools Actions tab reads the trace, so this is the rule that decides what it can show — and it is the
|
|
119
|
+
* action's own access rule, not the server's mode. An action open to everybody has already decided that starting
|
|
120
|
+
* it is anybody's business, so its steps are too; one that asks for a session owes its steps to a session and to
|
|
121
|
+
* nobody else. `devMode` on its own is not an answer to that question: it says this deployment is being built,
|
|
122
|
+
* not that whoever just posted to the endpoint is the person building it.
|
|
123
|
+
*
|
|
124
|
+
* It is deliberately a second lock on a door `precheckRun` already shut — an anonymous call to a `session` action
|
|
125
|
+
* never becomes a run. That is the point: the trace is the one part of the answer that carries the author's own
|
|
126
|
+
* data, and the day a deployment mounts a trigger of its own is the day it stops being covered by the first lock.
|
|
127
|
+
*/
|
|
128
|
+
var mayReadTrace = (trigger, user) => triggerAccess(triggerParams(trigger))?.mode === "public" || user !== void 0;
|
|
129
|
+
/**
|
|
130
|
+
* Handles an action-addressed call.
|
|
131
|
+
*
|
|
132
|
+
* The browser names an action and hands it inputs. Everything that decides whether the run may happen — the
|
|
133
|
+
* document, the access rule, the input contract, the lineage — is the runner's, so a deployment mounting its own
|
|
134
|
+
* trigger cannot end up with a weaker set of checks than this endpoint applies.
|
|
135
|
+
*/
|
|
136
|
+
var handleActionCall = async (deps) => {
|
|
137
|
+
const { req, res, raw, config, module, signal, callerId, lineage } = deps;
|
|
138
|
+
const { environment = "main", spaceId, revision = 0, authoring } = req.ctx.spaceDeployment ?? {};
|
|
139
|
+
if (typeof spaceId !== "number") {
|
|
140
|
+
fail$1(res, "not_found", "Invalid space deployment");
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
const body = parseBody$1(req.body);
|
|
144
|
+
if (!body?.actionId) {
|
|
145
|
+
fail$1(res, "invalid_input", "Expected { actionId, input }");
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (body.trigger === "render" && config.devMode !== true) {
|
|
149
|
+
fail$1(res, "forbidden", "A render is run from the command line on a development server alone (devMode)");
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const trigger = body.trigger === "render" ? "render" : "call";
|
|
153
|
+
/**
|
|
154
|
+
* A call that never became a run, told to whoever keeps the deployment's records.
|
|
155
|
+
*
|
|
156
|
+
* The caller already learns the reason from the status and the payload — that is what makes a refusal
|
|
157
|
+
* actionable for them. This is the other half: an author watching their own space see that calls are arriving
|
|
158
|
+
* and being turned away, which is otherwise a thing only the browser's network tab knows.
|
|
159
|
+
*/
|
|
160
|
+
const reject = (reason, detail) => reportReject(config, {
|
|
161
|
+
actionId: body.actionId,
|
|
162
|
+
spaceId,
|
|
163
|
+
environment,
|
|
164
|
+
trigger,
|
|
165
|
+
reason,
|
|
166
|
+
callerId,
|
|
167
|
+
...detail === void 0 ? {} : { detail }
|
|
168
|
+
});
|
|
169
|
+
const entry = await config.action?.lookups?.getAction(spaceId, body.actionId, {
|
|
170
|
+
environment,
|
|
171
|
+
revision
|
|
172
|
+
});
|
|
173
|
+
if (!entry) {
|
|
174
|
+
await reject("not_found", "No action with this identifier at the revision being served");
|
|
175
|
+
fail$1(res, "not_found", "Unknown action");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const limits = await module.limitsFor(spaceId, entry.document);
|
|
179
|
+
const origin = requestOrigin(req);
|
|
180
|
+
const input = body.input ?? {};
|
|
181
|
+
const begin = {
|
|
182
|
+
spaceId,
|
|
183
|
+
actionId: entry.id,
|
|
184
|
+
callerId,
|
|
185
|
+
input,
|
|
186
|
+
...body.idempotencyKey ? { idempotencyKey: body.idempotencyKey } : {},
|
|
187
|
+
ttlMs: limits.timeoutMs
|
|
188
|
+
};
|
|
189
|
+
/**
|
|
190
|
+
* The answer this key already produced, for a caller repeating itself after the first run finished.
|
|
191
|
+
*
|
|
192
|
+
* Only ever a key the caller NAMED: they told us which request this is, so answering the retry with what it
|
|
193
|
+
* answered the first time is what they asked for. Not metered and not counted — nothing ran.
|
|
194
|
+
*/
|
|
195
|
+
const replayed = await module.guards.replay(begin);
|
|
196
|
+
if (replayed) {
|
|
197
|
+
res.setHeader("X-Plitzi-Replayed", "true");
|
|
198
|
+
send$2(res, 200, {
|
|
199
|
+
...replayed,
|
|
200
|
+
replayed: true
|
|
201
|
+
}, replayed.runId);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const at = {
|
|
205
|
+
environment,
|
|
206
|
+
revision
|
|
207
|
+
};
|
|
208
|
+
const keepable = trigger === "call" && module.jobs !== void 0 && !wantsStream(req.headers.accept);
|
|
209
|
+
/**
|
|
210
|
+
* Keeps the call, to run as the caller's the moment its code has a runner again, answering 202 with what reads it
|
|
211
|
+
* back — rather than started and failed half-way.
|
|
212
|
+
*/
|
|
213
|
+
const keep = async () => {
|
|
214
|
+
if (!module.jobs) return;
|
|
215
|
+
const kept = await keepCall(module.jobs.queue, {
|
|
216
|
+
spaceId,
|
|
217
|
+
environment,
|
|
218
|
+
actionId: entry.id,
|
|
219
|
+
input,
|
|
220
|
+
...req.ctx.user ? { user: req.ctx.user } : {},
|
|
221
|
+
callerId,
|
|
222
|
+
...body.idempotencyKey ? { idempotencyKey: body.idempotencyKey } : {},
|
|
223
|
+
...origin ? { origin } : {},
|
|
224
|
+
at
|
|
225
|
+
});
|
|
226
|
+
if ("refused" in kept) {
|
|
227
|
+
await reject("over_capacity", kept.refused);
|
|
228
|
+
fail$1(res, "over_capacity", kept.refused);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
serverLog.info("Action", `${entry.id} kept in the queue for space=${String(spaceId)}: no functions runner answers`);
|
|
232
|
+
send$2(res, 202, {
|
|
233
|
+
status: "queued",
|
|
234
|
+
jobId: kept.jobId,
|
|
235
|
+
ticket: kept.ticket,
|
|
236
|
+
runId: "",
|
|
237
|
+
output: {}
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
let run;
|
|
241
|
+
let entryPoint;
|
|
242
|
+
try {
|
|
243
|
+
entryPoint = precheckRun(entry, {
|
|
244
|
+
trigger,
|
|
245
|
+
input,
|
|
246
|
+
user: req.ctx.user,
|
|
247
|
+
lineage
|
|
248
|
+
}).trigger;
|
|
249
|
+
if (keepable && await module.codeAway(spaceId, entry.document, at)) {
|
|
250
|
+
await keep();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
run = await module.guards.begin(begin);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
const reason = error instanceof ActionRunError ? error.reason : "failed";
|
|
256
|
+
const joined = reason === "duplicate" ? module.guards.join(begin) : void 0;
|
|
257
|
+
if (joined) {
|
|
258
|
+
const answer = await joined;
|
|
259
|
+
res.setHeader("X-Plitzi-Joined", "true");
|
|
260
|
+
if (answer) send$2(res, 200, {
|
|
261
|
+
runId: answer.runId,
|
|
262
|
+
status: answer.status,
|
|
263
|
+
output: answer.output,
|
|
264
|
+
...answer.error === void 0 ? {} : { error: answer.error },
|
|
265
|
+
joined: true
|
|
266
|
+
}, answer.runId);
|
|
267
|
+
else fail$1(res, "failed", "The same call was already running, and it ended with no answer");
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
await reject(reason, error instanceof Error ? error.message : void 0);
|
|
271
|
+
fail$1(res, reason, error instanceof Error ? error.message : "Action refused");
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
await config.adapters.meter?.({
|
|
275
|
+
kind: "server_action",
|
|
276
|
+
cached: false,
|
|
277
|
+
req,
|
|
278
|
+
spaceId,
|
|
279
|
+
environment,
|
|
280
|
+
revision
|
|
281
|
+
});
|
|
282
|
+
const abortRun = () => run.controller.abort();
|
|
283
|
+
const releaseAbort = onAbort(signal, abortRun);
|
|
284
|
+
const stream = wantsStream(req.headers.accept) ? openStream(raw, abortRun, run.runId) : void 0;
|
|
285
|
+
/**
|
|
286
|
+
* What a debugger may be told about this run, beside its answer.
|
|
287
|
+
*
|
|
288
|
+
* The OUTLINE — which steps ran, how each ended, where the flow broke — goes to a page whose debugging the
|
|
289
|
+
* deployment authorized: a dev server, or a space that switched dev tools on for its own site. Nothing else gets
|
|
290
|
+
* it, and it carries nothing a step was given or returned.
|
|
291
|
+
*
|
|
292
|
+
* The full TRACE, with every step's results, only to an authoring request or a development server: those results
|
|
293
|
+
* can hold another visitor's data, and sending them to an authoring request is what puts a SERVER run in the same
|
|
294
|
+
* Workflow debugger as a client one. Both are gated on the ACTION too — one behind a session tells an anonymous
|
|
295
|
+
* caller nothing about its flow.
|
|
296
|
+
*
|
|
297
|
+
* Answered once the run is over, for the answer and for the failure alike: a run that died on its deadline is
|
|
298
|
+
* exactly the one somebody is debugging.
|
|
299
|
+
*/
|
|
300
|
+
const readsRun = mayReadTrace(entryPoint, req.ctx.user);
|
|
301
|
+
const fullTrace = readsRun && (authoring === true || config.devMode === true);
|
|
302
|
+
const showsOutline = async () => readsRun && (fullTrace || await resolveDebugAuthorization(config, async () => (await config.adapters.getOfflineData(spaceId, environment, revision))?.schema.settings));
|
|
303
|
+
/**
|
|
304
|
+
* The flags a tester forced on the page this call came from, so the flow sees the feature the page was drawn with.
|
|
305
|
+
* Only for a page allowed to debug — the cookie is the visitor's own, and anywhere else it would let any of them
|
|
306
|
+
* switch a feature on for the server too. The authorization is asked only when there is a cookie to honour.
|
|
307
|
+
*/
|
|
308
|
+
const forcedFlags = await forcedFlagsFor({
|
|
309
|
+
cookie: req.headers.cookie,
|
|
310
|
+
authority: requestAuthority(req)
|
|
311
|
+
}, () => resolveDebugAuthorization(config, async () => (await config.adapters.getOfflineData(spaceId, environment, revision))?.schema.settings));
|
|
312
|
+
let outcome;
|
|
313
|
+
try {
|
|
314
|
+
const result = await module.runAction({
|
|
315
|
+
entry,
|
|
316
|
+
input,
|
|
317
|
+
spaceId,
|
|
318
|
+
environment,
|
|
319
|
+
trigger,
|
|
320
|
+
user: req.ctx.user,
|
|
321
|
+
callerId,
|
|
322
|
+
...origin ? { origin } : {},
|
|
323
|
+
runId: run.runId,
|
|
324
|
+
lineage,
|
|
325
|
+
at: {
|
|
326
|
+
environment,
|
|
327
|
+
revision
|
|
328
|
+
},
|
|
329
|
+
...forcedFlags ? { forcedFlags } : {},
|
|
330
|
+
signal: run.controller.signal,
|
|
331
|
+
...stream ? {
|
|
332
|
+
emit: (chunk) => stream.send({
|
|
333
|
+
event: "data",
|
|
334
|
+
data: { chunk }
|
|
335
|
+
}),
|
|
336
|
+
onNode: (id, status) => stream.send({
|
|
337
|
+
event: "node",
|
|
338
|
+
data: {
|
|
339
|
+
id,
|
|
340
|
+
status
|
|
341
|
+
}
|
|
342
|
+
})
|
|
343
|
+
} : {}
|
|
344
|
+
});
|
|
345
|
+
outcome = result;
|
|
346
|
+
const outline = await showsOutline();
|
|
347
|
+
if (stream) {
|
|
348
|
+
stream.send({
|
|
349
|
+
event: "done",
|
|
350
|
+
data: {
|
|
351
|
+
runId: result.runId,
|
|
352
|
+
status: result.status,
|
|
353
|
+
output: result.output,
|
|
354
|
+
...result.error === void 0 ? {} : { error: result.error },
|
|
355
|
+
...result.code === void 0 ? {} : { code: result.code },
|
|
356
|
+
...outline ? { steps: result.steps } : {}
|
|
357
|
+
}
|
|
358
|
+
});
|
|
359
|
+
stream.close();
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const payload = {
|
|
363
|
+
runId: result.runId,
|
|
364
|
+
status: result.status,
|
|
365
|
+
output: result.output,
|
|
366
|
+
...result.error === void 0 ? {} : { error: result.error },
|
|
367
|
+
...result.code === void 0 ? {} : { code: result.code }
|
|
368
|
+
};
|
|
369
|
+
if (outline) payload.steps = result.steps;
|
|
370
|
+
if (fullTrace) payload.trace = result.trace;
|
|
371
|
+
send$2(res, 200, payload, result.runId);
|
|
372
|
+
} catch (error) {
|
|
373
|
+
const reason = error instanceof ActionRunError ? error.reason : "failed";
|
|
374
|
+
const message = error instanceof ActionRunError ? error.message : "Action failed";
|
|
375
|
+
if (!(error instanceof ActionRunError)) serverLog.error("Actions", "run failed", error);
|
|
376
|
+
const steps = error instanceof ActionRunError && error.steps && await showsOutline() ? error.steps : void 0;
|
|
377
|
+
const untouched = error instanceof ActionRunError && !error.steps?.some((step) => step.phase === "flow" && step.status === "success");
|
|
378
|
+
if (keepable && reason === "over_capacity" && untouched && await module.codeAway(spaceId, entry.document, at)) {
|
|
379
|
+
await keep();
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (stream) {
|
|
383
|
+
stream.send({
|
|
384
|
+
event: "error",
|
|
385
|
+
data: {
|
|
386
|
+
runId: run.runId,
|
|
387
|
+
error: message,
|
|
388
|
+
reason,
|
|
389
|
+
...steps ? { steps } : {}
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
stream.close();
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
send$2(res, STATUS_BY_REASON[reason], {
|
|
396
|
+
error: message,
|
|
397
|
+
reason,
|
|
398
|
+
...steps ? { steps } : {}
|
|
399
|
+
}, run.runId);
|
|
400
|
+
} finally {
|
|
401
|
+
releaseAbort();
|
|
402
|
+
await module.guards.end(run, outcome);
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
// src/engine/transport/catalogHandler.ts
|
|
406
|
+
/**
|
|
407
|
+
* Serves the tasks this server can run.
|
|
408
|
+
*
|
|
409
|
+
* The editor asks the SERVER what steps exist instead of holding a hardcoded list, and that is the whole reason a
|
|
410
|
+
* self-hoster's own task appears in their builder with no fork: registering it is publishing it. It also means a
|
|
411
|
+
* deployment with no database driver never offers `db.query` — the catalog is what that deployment actually has,
|
|
412
|
+
* not what the SDK could imagine.
|
|
413
|
+
*
|
|
414
|
+
* Session-gated by the pipeline: the catalog names a deployment's server-side capabilities, which is not something
|
|
415
|
+
* to hand an anonymous visitor.
|
|
416
|
+
*/
|
|
417
|
+
var handleActionCatalog = async ({ res, module, spaceId, at }) => {
|
|
418
|
+
const registry = spaceId === void 0 ? module.registry : await module.registryFor(spaceId, at);
|
|
419
|
+
res.setStatus(200);
|
|
420
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
421
|
+
res.setHeader("Cache-Control", "no-store");
|
|
422
|
+
res.send(JSON.stringify({ tasks: describeCatalog(registry) }));
|
|
423
|
+
};
|
|
424
|
+
// src/engine/transport/verifySignature.ts
|
|
425
|
+
/**
|
|
426
|
+
* Digests as senders actually write them.
|
|
427
|
+
*
|
|
428
|
+
* A provider sends the same bytes in one of a few dressings — bare hex, base64, `sha256=<hex>` (GitHub), or a
|
|
429
|
+
* comma-separated list of `k=v` pairs where one value is the signature (Stripe). Accepting all of them is what
|
|
430
|
+
* lets one declarative verification cover real webhooks instead of only the tidy ones.
|
|
431
|
+
*/
|
|
432
|
+
var candidates = (header) => {
|
|
433
|
+
const parts = [header.trim()];
|
|
434
|
+
for (const segment of header.split(",")) {
|
|
435
|
+
const [, value] = segment.split("=", 2);
|
|
436
|
+
if (value) parts.push(value.trim());
|
|
437
|
+
}
|
|
438
|
+
return parts;
|
|
439
|
+
};
|
|
440
|
+
/** Constant time, and only for equal-length values: a length comparison leaks nothing an attacker cannot measure
|
|
441
|
+
* from the encoding anyway, while `timingSafeEqual` throws outright on a mismatch. */
|
|
442
|
+
var matches = (expected, received) => {
|
|
443
|
+
const a = Buffer.from(expected);
|
|
444
|
+
const b = Buffer.from(received);
|
|
445
|
+
return a.length === b.length && timingSafeEqual(a, b);
|
|
446
|
+
};
|
|
447
|
+
/**
|
|
448
|
+
* Checks an inbound webhook signature against the RAW body.
|
|
449
|
+
*
|
|
450
|
+
* Raw, before parsing, because a signature covers bytes: `JSON.parse` then `JSON.stringify` reorders keys and
|
|
451
|
+
* drops whitespace, and the digest of the result is not the digest the sender computed. That is the single most
|
|
452
|
+
* common way a webhook verification is written wrong, and it fails closed — which is why it is worth naming here
|
|
453
|
+
* rather than trusting every caller to remember.
|
|
454
|
+
*/
|
|
455
|
+
var verifySignature = (verification, secret, headers, rawBody) => {
|
|
456
|
+
const raw = headers[verification.header.toLowerCase()];
|
|
457
|
+
const signature = Array.isArray(raw) ? raw[0] : raw;
|
|
458
|
+
if (!signature) return {
|
|
459
|
+
ok: false,
|
|
460
|
+
reason: `Missing "${verification.header}" signature`
|
|
461
|
+
};
|
|
462
|
+
if (!secret) return {
|
|
463
|
+
ok: false,
|
|
464
|
+
reason: "Signing secret is not available"
|
|
465
|
+
};
|
|
466
|
+
let signed = rawBody;
|
|
467
|
+
if (verification.timestampHeader) {
|
|
468
|
+
const rawStamp = headers[verification.timestampHeader.toLowerCase()];
|
|
469
|
+
const stamp = Array.isArray(rawStamp) ? rawStamp[0] : rawStamp;
|
|
470
|
+
if (!stamp) return {
|
|
471
|
+
ok: false,
|
|
472
|
+
reason: `Missing "${verification.timestampHeader}" timestamp`
|
|
473
|
+
};
|
|
474
|
+
const sentAt = Number.parseInt(stamp, 10);
|
|
475
|
+
if (!Number.isFinite(sentAt)) return {
|
|
476
|
+
ok: false,
|
|
477
|
+
reason: "Timestamp is not a number"
|
|
478
|
+
};
|
|
479
|
+
const tolerance = verification.toleranceSeconds;
|
|
480
|
+
if (tolerance !== void 0 && Math.abs(Date.now() / 1e3 - sentAt) > tolerance) return {
|
|
481
|
+
ok: false,
|
|
482
|
+
reason: "Signature is outside its tolerance window"
|
|
483
|
+
};
|
|
484
|
+
signed = `${stamp}.${rawBody}`;
|
|
485
|
+
}
|
|
486
|
+
const hex = createHmac(verification.algorithm, secret).update(signed).digest("hex");
|
|
487
|
+
const base64 = createHmac(verification.algorithm, secret).update(signed).digest("base64");
|
|
488
|
+
return candidates(signature).some((value) => matches(hex, value) || matches(base64, value)) ? { ok: true } : {
|
|
489
|
+
ok: false,
|
|
490
|
+
reason: "Signature does not match"
|
|
491
|
+
};
|
|
492
|
+
};
|
|
493
|
+
// src/engine/transport/webhookHandler.ts
|
|
494
|
+
var DEFAULT_PER_MINUTE = 60;
|
|
495
|
+
var send$1 = (res, status, payload) => {
|
|
496
|
+
res.setStatus(status);
|
|
497
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
498
|
+
res.setHeader("Cache-Control", "no-store");
|
|
499
|
+
res.send(JSON.stringify(payload));
|
|
500
|
+
};
|
|
501
|
+
/**
|
|
502
|
+
* The signing secret, from the credential the verification NAMES.
|
|
503
|
+
*
|
|
504
|
+
* Named outright rather than templated. This runs before anything else does — before the body is parsed, before a
|
|
505
|
+
* run exists — so there is no flow scope for a token to resolve against, and one that rendered to nothing would
|
|
506
|
+
* leave the endpoint verifying every request against an empty secret.
|
|
507
|
+
*/
|
|
508
|
+
var resolveSecret = async (verification, spaceId, getCredential) => {
|
|
509
|
+
const secret = (await getCredential?.(spaceId, verification.credential))?.[verification.secretField ?? "secret"];
|
|
510
|
+
return typeof secret === "string" ? secret : "";
|
|
511
|
+
};
|
|
512
|
+
/**
|
|
513
|
+
* Handles an inbound webhook.
|
|
514
|
+
*
|
|
515
|
+
* The public face of an action, and the one an attacker can reach without a session — so everything that costs
|
|
516
|
+
* anything happens after the signature is checked, in this order: the action must exist and declare the trigger,
|
|
517
|
+
* the rate limit must allow it, the signature must verify, and only then does a run start.
|
|
518
|
+
*
|
|
519
|
+
* The answer is deliberately thin. A sender needs to know it was accepted; it has no business learning whether an
|
|
520
|
+
* action exists, why a run failed, or what the flow did — and a 404 that distinguishes "no such action" from
|
|
521
|
+
* "wrong signature" is an oracle for both.
|
|
522
|
+
*/
|
|
523
|
+
var handleActionWebhook = async (deps) => {
|
|
524
|
+
const { req, res, config, module, signal, actionId, callerId, lineage } = deps;
|
|
525
|
+
const { environment = "main", spaceId, revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
526
|
+
if (typeof spaceId !== "number") {
|
|
527
|
+
send$1(res, 404, { error: "Not found" });
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Every way this ends without a run, told to whoever configured the endpoint.
|
|
532
|
+
*
|
|
533
|
+
* A rejected webhook is the single most common way an integration is broken, and until this existed it was
|
|
534
|
+
* indistinguishable from the sender never firing: the reason went to the process log, where the person setting
|
|
535
|
+
* up the integration cannot see it. The SENDER still learns nothing it should not — that answer is unchanged.
|
|
536
|
+
*/
|
|
537
|
+
const reject = (reason, detail) => reportReject(config, {
|
|
538
|
+
actionId,
|
|
539
|
+
spaceId,
|
|
540
|
+
environment,
|
|
541
|
+
trigger: "webhook",
|
|
542
|
+
reason,
|
|
543
|
+
callerId,
|
|
544
|
+
...detail === void 0 ? {} : { detail }
|
|
545
|
+
});
|
|
546
|
+
const entry = await config.action?.lookups?.getAction(spaceId, actionId);
|
|
547
|
+
const trigger = entry ? findTriggerNode(entry.document.nodes, "webhook") : void 0;
|
|
548
|
+
if (!entry || !trigger) {
|
|
549
|
+
await reject("not_found", entry ? "The action declares no webhook trigger" : "No action with this identifier");
|
|
550
|
+
send$1(res, 404, { error: "Not found" });
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
const stepParams = triggerParams(trigger);
|
|
554
|
+
const verify = triggerVerify(stepParams);
|
|
555
|
+
/**
|
|
556
|
+
* A verification nothing reads is not an unsigned webhook — it is a broken one, and it is refused.
|
|
557
|
+
*
|
|
558
|
+
* The check used to be a JSON blob and is now fields on the step. A document stored before that carries the
|
|
559
|
+
* blob and no signing credential, and reading it as "unsigned" would turn a protected endpoint into a public
|
|
560
|
+
* one without a single line of it changing. Fail closed, and say which document to fix.
|
|
561
|
+
*/
|
|
562
|
+
if (triggerHasStaleVerify(stepParams)) {
|
|
563
|
+
serverLog.error("Actions", `webhook "${actionId}" in space ${spaceId} carries a signature check in a format nothing reads any more, so it is refused. Name the signing credential on the trigger step.`);
|
|
564
|
+
await reject("unverifiable", "The signature check is in a format nothing reads any more; name the signing credential on the trigger step");
|
|
565
|
+
send$1(res, 503, { error: "Unavailable" });
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
const perMinute = config.action?.rateLimit?.webhookPerMinute ?? DEFAULT_PER_MINUTE;
|
|
569
|
+
const window = Math.floor(Date.now() / 6e4);
|
|
570
|
+
try {
|
|
571
|
+
if (await module.kv(spaceId).increment(`hook:${actionId}:${callerId}:${window}`, 1, 120) > perMinute) {
|
|
572
|
+
res.setHeader("Retry-After", "60");
|
|
573
|
+
await reject("rate_limited", `More than ${perMinute} deliveries in one minute from this caller`);
|
|
574
|
+
send$1(res, 429, { error: "Too many requests" });
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
} catch {
|
|
578
|
+
await reject("unverifiable", "The rate-limit store could not answer, so the endpoint failed closed");
|
|
579
|
+
send$1(res, 503, { error: "Unavailable" });
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const rawBody = req.body ?? "";
|
|
583
|
+
if (verify) {
|
|
584
|
+
const check = verifySignature(verify, await resolveSecret(verify, spaceId, config.action?.lookups?.getCredential), req.headers, rawBody);
|
|
585
|
+
if (!check.ok) {
|
|
586
|
+
serverLog.warn("Actions", `webhook "${actionId}" rejected: ${check.reason}`);
|
|
587
|
+
await reject("invalid_signature", check.reason);
|
|
588
|
+
send$1(res, 401, { error: "Invalid signature" });
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
let payload = {};
|
|
593
|
+
try {
|
|
594
|
+
const parsed = rawBody ? JSON.parse(rawBody) : {};
|
|
595
|
+
payload = parsed !== null && typeof parsed === "object" ? parsed : {};
|
|
596
|
+
} catch {
|
|
597
|
+
await reject("malformed_body", "The body is not JSON");
|
|
598
|
+
send$1(res, 400, { error: "Body is not JSON" });
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
const input = {
|
|
602
|
+
...payload,
|
|
603
|
+
payload
|
|
604
|
+
};
|
|
605
|
+
const limits = await module.limitsFor(spaceId, entry.document);
|
|
606
|
+
const begin = {
|
|
607
|
+
spaceId,
|
|
608
|
+
actionId: entry.id,
|
|
609
|
+
callerId,
|
|
610
|
+
input,
|
|
611
|
+
idempotencyKey: deliveryId(req),
|
|
612
|
+
sharedKey: true,
|
|
613
|
+
ttlMs: limits.timeoutMs
|
|
614
|
+
};
|
|
615
|
+
const replayed = await module.guards.replay(begin);
|
|
616
|
+
if (replayed) {
|
|
617
|
+
send$1(res, 202, {
|
|
618
|
+
accepted: true,
|
|
619
|
+
runId: replayed.runId,
|
|
620
|
+
status: replayed.status,
|
|
621
|
+
replayed: true
|
|
622
|
+
});
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
let run;
|
|
626
|
+
try {
|
|
627
|
+
precheckRun(entry, {
|
|
628
|
+
trigger: "webhook",
|
|
629
|
+
input,
|
|
630
|
+
lineage
|
|
631
|
+
});
|
|
632
|
+
run = await module.guards.begin(begin);
|
|
633
|
+
} catch (error) {
|
|
634
|
+
const reason = error instanceof ActionRunError ? error.reason : "failed";
|
|
635
|
+
await reject(reason, error instanceof Error ? error.message : void 0);
|
|
636
|
+
send$1(res, reason === "duplicate" ? 202 : 400, { accepted: reason === "duplicate" });
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
await config.adapters.meter?.({
|
|
640
|
+
kind: "server_action",
|
|
641
|
+
cached: false,
|
|
642
|
+
req,
|
|
643
|
+
spaceId,
|
|
644
|
+
environment,
|
|
645
|
+
revision
|
|
646
|
+
});
|
|
647
|
+
const abortRun = () => run.controller.abort();
|
|
648
|
+
const releaseAbort = onAbort(signal, abortRun);
|
|
649
|
+
let outcome;
|
|
650
|
+
try {
|
|
651
|
+
const result = await module.runAction({
|
|
652
|
+
entry,
|
|
653
|
+
input,
|
|
654
|
+
spaceId,
|
|
655
|
+
environment,
|
|
656
|
+
trigger: "webhook",
|
|
657
|
+
callerId,
|
|
658
|
+
runId: run.runId,
|
|
659
|
+
lineage,
|
|
660
|
+
signal: run.controller.signal
|
|
661
|
+
});
|
|
662
|
+
outcome = result;
|
|
663
|
+
send$1(res, 200, {
|
|
664
|
+
accepted: true,
|
|
665
|
+
runId: result.runId,
|
|
666
|
+
status: result.status
|
|
667
|
+
});
|
|
668
|
+
} catch (error) {
|
|
669
|
+
serverLog.error("Actions", "webhook run failed", error);
|
|
670
|
+
send$1(res, 500, { accepted: false });
|
|
671
|
+
} finally {
|
|
672
|
+
releaseAbort();
|
|
673
|
+
await module.guards.end(run, outcome);
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
/** The delivery id a provider sends, under the header names the common ones use. */
|
|
677
|
+
var deliveryId = (req) => {
|
|
678
|
+
for (const name of [
|
|
679
|
+
"x-plitzi-delivery",
|
|
680
|
+
"x-github-delivery",
|
|
681
|
+
"x-request-id",
|
|
682
|
+
"idempotency-key"
|
|
683
|
+
]) {
|
|
684
|
+
const value = req.headers[name];
|
|
685
|
+
const single = Array.isArray(value) ? value[0] : value;
|
|
686
|
+
if (single) return single;
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
// src/engine/transport/cancelHandler.ts
|
|
690
|
+
/**
|
|
691
|
+
* Stops a run in flight.
|
|
692
|
+
*
|
|
693
|
+
* The socket closing already aborts a run, so this exists for the cases it cannot cover: a mobile client whose
|
|
694
|
+
* peer is gone without the server seeing it for minutes, and a run started in one tab that the visitor wants to
|
|
695
|
+
* stop from another. Ownership is checked in the guards — a run id travels to the browser, and holding one must
|
|
696
|
+
* not let anybody stop somebody else's run.
|
|
697
|
+
*
|
|
698
|
+
* A run that is not there, or is not the caller's, answers 404 either way: distinguishing them would turn this
|
|
699
|
+
* into an oracle for which run ids are live.
|
|
700
|
+
*
|
|
701
|
+
* Awaited because the run is usually somewhere else: behind a load balancer the tab asking to stop a checkout
|
|
702
|
+
* almost never reaches the replica running it, so the cancel is left in the shared store for the one that is.
|
|
703
|
+
*/
|
|
704
|
+
var handleActionCancel = async ({ res, module, runId, callerId }) => {
|
|
705
|
+
const cancelled = await module.guards.cancel(runId, callerId);
|
|
706
|
+
res.setStatus(cancelled ? 204 : 404);
|
|
707
|
+
res.setHeader("Cache-Control", "no-store");
|
|
708
|
+
res.send("");
|
|
709
|
+
};
|
|
710
|
+
// src/worker/origin.ts
|
|
711
|
+
/** Where a page server's pages call their actions when it is not told: this path, on their own origin. */
|
|
712
|
+
var DEFAULT_ACTION_PATH = "/_action";
|
|
713
|
+
/** What a page is told of its actions: their path on its own origin, or their address on `action.origin`. */
|
|
714
|
+
var publishedActionEndpoint = (action) => {
|
|
715
|
+
const path = action?.path ?? "/_action";
|
|
716
|
+
return action?.origin ? `${action.origin}${path}` : path;
|
|
717
|
+
};
|
|
718
|
+
/** An origin as a browser sends it: a scheme, a host and a port, nothing after. */
|
|
719
|
+
var originProblem = (origin, setting) => {
|
|
720
|
+
let parsed;
|
|
721
|
+
try {
|
|
722
|
+
parsed = new URL(origin);
|
|
723
|
+
} catch {
|
|
724
|
+
return `\`${setting}\` is "${origin}", which is not an address: write an origin, like https://actions.example.com`;
|
|
725
|
+
}
|
|
726
|
+
if (!["http:", "https:"].includes(parsed.protocol) || parsed.origin !== origin) return `\`${setting}\` is "${origin}": write the origin alone, as a browser sends it — ${parsed.origin}`;
|
|
727
|
+
};
|
|
728
|
+
/**
|
|
729
|
+
* What is wrong with an engine's actions on another origin, or nothing: `action.origin` an origin and, for the worker
|
|
730
|
+
* that serves them, the pages that call it named (`action.pageOrigins`) — a worker on another origin with none would
|
|
731
|
+
* refuse every page, or, answering any, let every site call with a visitor's cookies. A page server is told only where
|
|
732
|
+
* to call.
|
|
733
|
+
*/
|
|
734
|
+
var actionOriginProblem = (action, served) => {
|
|
735
|
+
if (!action?.origin) return action?.pageOrigins?.length ? "`action.pageOrigins` names the pages that call the actions on another origin, and `action.origin` is not set: set it to where they are served, or drop `pageOrigins` (a page calls its own origin)" : void 0;
|
|
736
|
+
const own = originProblem(action.origin, "action.origin");
|
|
737
|
+
if (own) return own;
|
|
738
|
+
if (served === "pages") return;
|
|
739
|
+
if (!action.pageOrigins?.length) return `The actions are served on another origin than the pages' (\`action.origin\` ${action.origin}), and \`action.pageOrigins\` names none of the pages that call them: name their origins, which its CORS answers with credentials and its cross-site check takes as its own`;
|
|
740
|
+
return action.pageOrigins.map((origin) => originProblem(origin, "action.pageOrigins")).find(Boolean);
|
|
741
|
+
};
|
|
742
|
+
// src/worker/elsewhere.ts
|
|
743
|
+
/**
|
|
744
|
+
* What a page server is handed when its actions run on a worker (`createWorker`): where its pages call them and where
|
|
745
|
+
* their channels are, and nothing that runs here — the gateway sends those paths to the worker. Give it the `action` and
|
|
746
|
+
* `realtime` the worker has, for the same paths — and, when the worker is on another origin, its `action.origin`: the pages
|
|
747
|
+
* are told the address there.
|
|
748
|
+
*
|
|
749
|
+
* With `render` its server elements that name an action or a connector are asked of the worker too (`/_render`, behind
|
|
750
|
+
* the worker's `render.secret`): this server then runs no action at all. Without it, a page that renders one shows it
|
|
751
|
+
* in its error state, said as an element no engine here resolves.
|
|
752
|
+
*/
|
|
753
|
+
var engineOnWorker = ({ action, realtime, render } = {}) => {
|
|
754
|
+
const problem = actionOriginProblem(action, "pages");
|
|
755
|
+
if (problem) throw new Error(problem);
|
|
756
|
+
return {
|
|
757
|
+
endpoints: [],
|
|
758
|
+
routes: [],
|
|
759
|
+
...render ? { resolveElement: createRemoteRenderResolver(render) } : {},
|
|
760
|
+
published: {
|
|
761
|
+
actionPath: publishedActionEndpoint(action),
|
|
762
|
+
...realtime === false ? {} : {
|
|
763
|
+
realtimePath: realtime?.path ?? "/_realtime",
|
|
764
|
+
realtimeTransport: realtime?.transport ?? "sse"
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
};
|
|
769
|
+
// src/engine/configSeam.ts
|
|
770
|
+
/**
|
|
771
|
+
* A guard that checks each object once: a deployment that caches what it reads hands back the same object on every
|
|
772
|
+
* call, and a render must not pay for validating its action again.
|
|
773
|
+
*/
|
|
774
|
+
var checkedOnce = (guard) => {
|
|
775
|
+
const seen = /* @__PURE__ */ new WeakMap();
|
|
776
|
+
return (value) => {
|
|
777
|
+
if (!isRecord(value)) return false;
|
|
778
|
+
const known = seen.get(value);
|
|
779
|
+
if (known !== void 0) return known;
|
|
780
|
+
const valid = guard(value);
|
|
781
|
+
seen.set(value, valid);
|
|
782
|
+
return valid;
|
|
783
|
+
};
|
|
784
|
+
};
|
|
785
|
+
var isManifest = checkedOnce(isConnectorManifestDraft);
|
|
786
|
+
var isDocument = checkedOnce(isActionDocument);
|
|
787
|
+
/** What `getFunctions` answers: built by `@plitzi/sdk-actions/functions` from a space's saved bundle, a live object. */
|
|
788
|
+
var isSpaceFunctions = (value) => isRecord(value) && isRecord(value.bundle) && typeof value.bundle.id === "string" && typeof value.bundle.load === "function" && isRecord(value.manifest);
|
|
789
|
+
/** What `getPluginFunctions` answers: a `SpaceFunctions` per plugin type. */
|
|
790
|
+
var isPluginFunctions = (value) => isRecord(value) && Object.values(value).every(isSpaceFunctions);
|
|
791
|
+
/** What `getData` answers: the space's data files' text, by path. */
|
|
792
|
+
var isProjectData = (value) => isRecord(value) && Object.values(value).every((text) => typeof text === "string");
|
|
793
|
+
/** Why a document is not one this server runs: the first problem its validator found, by where it is. */
|
|
794
|
+
var firstProblem = (errors) => {
|
|
795
|
+
const first = errors.at(0);
|
|
796
|
+
if (!first) return "it is not a document";
|
|
797
|
+
return first.path ? `${first.path}: ${first.message}` : first.message;
|
|
798
|
+
};
|
|
799
|
+
var manifestFrom = (found, spaceId, connectorId) => {
|
|
800
|
+
if (found === void 0 || found === null) return;
|
|
801
|
+
if (!isManifest(found)) throw new Error(`Connector "${connectorId}" of space ${String(spaceId)} is not a manifest this server can run — ${firstProblem(validateConnectorManifest(found).errors)}`);
|
|
802
|
+
return {
|
|
803
|
+
...found,
|
|
804
|
+
id: connectorId
|
|
805
|
+
};
|
|
806
|
+
};
|
|
807
|
+
/** An action as a lookup found it: the entry, or why it is not one. */
|
|
808
|
+
var readAction = (found) => {
|
|
809
|
+
const document = isRecord(found) ? found.document : void 0;
|
|
810
|
+
if (!isRecord(found) || typeof found.id !== "string") return { problem: "it has no id" };
|
|
811
|
+
return isDocument(document) ? { entry: {
|
|
812
|
+
id: found.id,
|
|
813
|
+
document
|
|
814
|
+
} } : { problem: firstProblem(validateActionDocument(document).errors) };
|
|
815
|
+
};
|
|
816
|
+
var connectorSeams = /* @__PURE__ */ new WeakMap();
|
|
817
|
+
/** The connector lookups a deployment configured, each manifest checked as it is read. One per config object. */
|
|
818
|
+
var connectorLookupsOf = (config) => {
|
|
819
|
+
const existing = connectorSeams.get(config);
|
|
820
|
+
if (existing) return existing;
|
|
821
|
+
const lookups = {
|
|
822
|
+
getConnector: async (spaceId, connectorId, at) => manifestFrom(await config.getConnector(spaceId, connectorId, at), spaceId, connectorId),
|
|
823
|
+
...config.getCredential ? { getCredential: config.getCredential } : {},
|
|
824
|
+
...config.fetchImpl ? { fetchImpl: config.fetchImpl } : {}
|
|
825
|
+
};
|
|
826
|
+
connectorSeams.set(config, lookups);
|
|
827
|
+
return lookups;
|
|
828
|
+
};
|
|
829
|
+
/**
|
|
830
|
+
* The action lookups a deployment configured, each document checked as it is read. Asked for one, a document that is
|
|
831
|
+
* not one is refused; listed, it is left out and said, so one broken action does not take its space's schedule down.
|
|
832
|
+
*/
|
|
833
|
+
/** What a deployment answered for a visitor, as a function may read it: the public fields alone, the rest dropped. */
|
|
834
|
+
var visitorOf = (found) => {
|
|
835
|
+
if (!isRecord(found) || typeof found.id !== "number" || typeof found.username !== "string") return;
|
|
836
|
+
return {
|
|
837
|
+
id: found.id,
|
|
838
|
+
username: found.username,
|
|
839
|
+
...typeof found.name === "string" && found.name ? { name: found.name } : {},
|
|
840
|
+
...typeof found.avatar === "string" && found.avatar ? { avatar: found.avatar } : {}
|
|
841
|
+
};
|
|
842
|
+
};
|
|
843
|
+
var actionLookupsOf = (config) => {
|
|
844
|
+
const { getConnector, getData, getFunctions, getPluginFunctions, getVisitor, listActions } = config;
|
|
845
|
+
return {
|
|
846
|
+
...getVisitor ? { getVisitor: async (spaceId, environment, who) => visitorOf(await getVisitor(spaceId, environment, who)) } : {},
|
|
847
|
+
getAction: async (spaceId, actionId, at) => {
|
|
848
|
+
const found = await config.getAction(spaceId, actionId, at);
|
|
849
|
+
if (found === void 0 || found === null) return;
|
|
850
|
+
const read = readAction(found);
|
|
851
|
+
if ("problem" in read) throw new Error(`Action "${actionId}" of space ${String(spaceId)} is not a document this server can run — ${read.problem}`);
|
|
852
|
+
return read.entry;
|
|
853
|
+
},
|
|
854
|
+
...listActions ? { listActions: async (spaceId, at) => (await listActions(spaceId, at)).flatMap((found) => {
|
|
855
|
+
const read = readAction(found);
|
|
856
|
+
if ("problem" in read) {
|
|
857
|
+
serverLog.warn("actions", `An action of space ${String(spaceId)} is left out — ${read.problem}`);
|
|
858
|
+
return [];
|
|
859
|
+
}
|
|
860
|
+
return [read.entry];
|
|
861
|
+
}) } : {},
|
|
862
|
+
...config.listScheduledSpaces ? { listScheduledSpaces: config.listScheduledSpaces } : {},
|
|
863
|
+
...config.getCredential ? { getCredential: config.getCredential } : {},
|
|
864
|
+
...getConnector ? { getConnector: async (spaceId, connectorId, at) => manifestFrom(await getConnector(spaceId, connectorId, at), spaceId, connectorId) } : {},
|
|
865
|
+
...getFunctions ? { getFunctions: async (spaceId, at) => {
|
|
866
|
+
const found = await getFunctions(spaceId, at);
|
|
867
|
+
if (found === void 0 || found === null) return;
|
|
868
|
+
if (!isSpaceFunctions(found)) throw new Error(`The functions of space ${String(spaceId)} are not what @plitzi/sdk-actions/functions builds for one`);
|
|
869
|
+
return found;
|
|
870
|
+
} } : {},
|
|
871
|
+
...getData ? { getData: async (spaceId, at) => {
|
|
872
|
+
const found = await getData(spaceId, at);
|
|
873
|
+
if (found === void 0 || found === null) return;
|
|
874
|
+
if (!isProjectData(found)) throw new Error(`The data of space ${String(spaceId)} is not its files' text by path`);
|
|
875
|
+
return found;
|
|
876
|
+
} } : {},
|
|
877
|
+
...getPluginFunctions ? { getPluginFunctions: async (spaceId, at) => {
|
|
878
|
+
const found = await getPluginFunctions(spaceId, at);
|
|
879
|
+
if (found === void 0 || found === null) return;
|
|
880
|
+
if (!isPluginFunctions(found)) throw new Error(`The plugin functions of space ${String(spaceId)} are not, by plugin type, what @plitzi/sdk-actions/functions builds for one`);
|
|
881
|
+
return found;
|
|
882
|
+
} } : {},
|
|
883
|
+
...config.getFlags ? { getFlags: config.getFlags } : {}
|
|
884
|
+
};
|
|
885
|
+
};
|
|
886
|
+
var isFunction = (value) => typeof value === "function";
|
|
887
|
+
/** A driver as `createDbDrivers` builds one: the engine a credential names, and how to query it. */
|
|
888
|
+
var isDbDriver = (value) => isRecord(value) && typeof value.engine === "string" && isFunction(value.query);
|
|
889
|
+
/** The functions config as `@plitzi/sdk-actions/functions` builds it: native and plugin definitions, a runner, ceilings. */
|
|
890
|
+
var isFunctionsConfig = (value) => isRecord(value) && (value.native === void 0 || Array.isArray(value.native) && value.native.every(isRecord)) && (value.plugins === void 0 || isRecord(value.plugins) && Object.values(value.plugins).every(isRecord)) && (value.runner === void 0 || isRecord(value.runner) && isFunction(value.runner.describe) && isFunction(value.runner.invoke)) && (value.limits === void 0 || isRecord(value.limits)) && (value.jobs === void 0 || isRecord(value.jobs) && (value.jobs.limitsFor === void 0 || isFunction(value.jobs.limitsFor))) && (value.oauth === void 0 || isRecord(value.oauth) && (value.oauth.callbackOrigin === void 0 || typeof value.oauth.callbackOrigin === "string"));
|
|
891
|
+
/** Whether a value is an origin as a browser writes it — `https://example.com`, no path or trailing slash. */
|
|
892
|
+
var isOrigin = (value) => {
|
|
893
|
+
try {
|
|
894
|
+
return new URL(value).origin === value;
|
|
895
|
+
} catch {
|
|
896
|
+
return false;
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
/** The deployment's database drivers, each held to what a `db` task calls — or why one is not, as the server starts. */
|
|
900
|
+
var dbDriversOf = (drivers) => {
|
|
901
|
+
if (drivers === void 0) return;
|
|
902
|
+
const wrong = drivers.findIndex((driver) => !isDbDriver(driver));
|
|
903
|
+
if (wrong >= 0) throw new Error(`action.dbDrivers[${String(wrong)}] is not a database driver: it needs an \`engine\` and a \`query\` function.`);
|
|
904
|
+
return drivers.filter(isDbDriver);
|
|
905
|
+
};
|
|
906
|
+
/** The deployment's functions config, held to what runs a space's code — or why it is not, as the server starts. */
|
|
907
|
+
var functionsConfigOf = (config) => {
|
|
908
|
+
if (config === void 0) return;
|
|
909
|
+
if (!isFunctionsConfig(config)) throw new Error("`functions` is not what @plitzi/sdk-actions/functions configures: `native` definitions, `plugins` by type, a `runner` with `describe` and `invoke`, `limits`, `jobs` with a `limitsFor` function, `oauth` with a `callbackOrigin`.");
|
|
910
|
+
const callbackOrigin = config.oauth?.callbackOrigin;
|
|
911
|
+
if (callbackOrigin !== void 0 && !isOrigin(callbackOrigin)) throw new Error(`\`functions.oauth.callbackOrigin\` is an origin, as a browser writes it — \`https://example.com\`, no path or slash — not "${callbackOrigin}"`);
|
|
912
|
+
return config;
|
|
913
|
+
};
|
|
914
|
+
// src/engine/runtime/runStats.ts
|
|
915
|
+
/**
|
|
916
|
+
* How a run's end reads to the process's stats: nothing when it answered; a limit when it reached one, or its code
|
|
917
|
+
* refused — the run's own doing, which no error rate counts; and why it failed otherwise.
|
|
918
|
+
*/
|
|
919
|
+
var endOf = (record) => {
|
|
920
|
+
if (record.status === "completed" || record.status === "skipped") return;
|
|
921
|
+
if (record.limit) return { limit: record.limit };
|
|
922
|
+
if (record.refused) return { refused: true };
|
|
923
|
+
return { failed: record.reason ?? (record.status === "aborted" ? "aborted" : "error") };
|
|
924
|
+
};
|
|
925
|
+
/**
|
|
926
|
+
* The deployment's `onRun` with the process's stats fed first (`stats`): each run's duration, how it ended, and
|
|
927
|
+
* which action of which space it was — what a slow minute on the pools' screen is traced back to.
|
|
928
|
+
* A stats update cannot throw, so the deployment's own record is never kept from running.
|
|
929
|
+
*/
|
|
930
|
+
var recordedRun = (stats, onRun) => async (record) => {
|
|
931
|
+
stats.run(record.durationMs, endOf(record), {
|
|
932
|
+
spaceId: record.spaceId,
|
|
933
|
+
kind: "action",
|
|
934
|
+
name: record.actionId,
|
|
935
|
+
trigger: record.trigger,
|
|
936
|
+
runId: record.runId
|
|
937
|
+
});
|
|
938
|
+
await onRun?.(record);
|
|
939
|
+
};
|
|
940
|
+
// src/engine/moduleFor.ts
|
|
941
|
+
/**
|
|
942
|
+
* The one actions module for a server, whoever asks first.
|
|
943
|
+
*
|
|
944
|
+
* Two places need it and they are built at different moments: the page pipeline mounts the endpoint, and the RSC
|
|
945
|
+
* adapter is assembled before that to resolve `render` elements. Constructing one each would give a server two
|
|
946
|
+
* guard sets — and two sets each believing they hold the only run in flight is the same as having no single-flight
|
|
947
|
+
* at all.
|
|
948
|
+
*
|
|
949
|
+
* Memoized on the config OBJECT, which is exactly the lifetime wanted: one per `createServer` call, released with
|
|
950
|
+
* it, and a fresh one per server in a test file that builds several.
|
|
951
|
+
*/
|
|
952
|
+
var modules = /* @__PURE__ */ new WeakMap();
|
|
953
|
+
var actionsModuleFor = (config) => {
|
|
954
|
+
const lookups = config.action?.lookups;
|
|
955
|
+
if (!lookups) return;
|
|
956
|
+
const existing = modules.get(config);
|
|
957
|
+
if (existing) return existing;
|
|
958
|
+
const stats = config.stats ? statsRecorderFor(config.stats, config.health?.version) : void 0;
|
|
959
|
+
const module = createActionsModule({
|
|
960
|
+
lookups: actionLookupsOf(lookups),
|
|
961
|
+
flags: config.flags,
|
|
962
|
+
functions: functionsConfigOf(config.functions),
|
|
963
|
+
limits: config.action?.limits,
|
|
964
|
+
limitsFor: config.action?.limitsFor,
|
|
965
|
+
admitRun: config.action?.admitRun,
|
|
966
|
+
concurrency: config.action?.concurrency,
|
|
967
|
+
kv: config.action?.kv,
|
|
968
|
+
jobs: config.action?.jobs,
|
|
969
|
+
rateLimit: config.action?.rateLimit,
|
|
970
|
+
idempotency: config.action?.idempotency,
|
|
971
|
+
signingSecret: config.action?.signingSecret,
|
|
972
|
+
dbDrivers: dbDriversOf(config.action?.dbDrivers),
|
|
973
|
+
email: config.action?.email,
|
|
974
|
+
outbound: { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) },
|
|
975
|
+
onRun: stats ? recordedRun(stats, config.action?.onRun) : config.action?.onRun,
|
|
976
|
+
realtime: realtimeModuleFor(config)
|
|
977
|
+
});
|
|
978
|
+
if (stats) {
|
|
979
|
+
const sizes = module.guards.slots();
|
|
980
|
+
stats.slot("calls", sizes.calls.of, () => module.guards.slots().calls.used);
|
|
981
|
+
stats.slot("renders", sizes.renders.of, () => module.guards.slots().renders.used);
|
|
982
|
+
const jobs = module.jobs;
|
|
983
|
+
const jobWorkers = config.action?.jobs === false ? 0 : config.action?.jobs?.workers ?? 4;
|
|
984
|
+
if (jobs && jobWorkers > 0) stats.slot("jobs", jobWorkers, () => jobs.worker.inFlight(), { queues: true });
|
|
985
|
+
}
|
|
986
|
+
modules.set(config, module);
|
|
987
|
+
return module;
|
|
988
|
+
};
|
|
989
|
+
// src/engine/connectorWrite.ts
|
|
990
|
+
var parseBody = (body) => {
|
|
991
|
+
if (!body) return;
|
|
992
|
+
try {
|
|
993
|
+
const parsed = JSON.parse(body);
|
|
994
|
+
return parsed !== null && typeof parsed === "object" ? parsed : void 0;
|
|
995
|
+
} catch {
|
|
996
|
+
return;
|
|
997
|
+
}
|
|
998
|
+
};
|
|
999
|
+
var fail = (res, status, error) => {
|
|
1000
|
+
res.setStatus(status);
|
|
1001
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1002
|
+
res.send(JSON.stringify({ error }));
|
|
1003
|
+
};
|
|
1004
|
+
/**
|
|
1005
|
+
* Handles POST /_action — the write counterpart of the RSC read endpoint.
|
|
1006
|
+
*
|
|
1007
|
+
* The browser names an **element**, never a connector or a URL. The element must exist in the published schema,
|
|
1008
|
+
* be server-driven and declare a connector, and the connector must declare the action. That chain is what stops
|
|
1009
|
+
* the endpoint from being a general-purpose proxy into the customer's backend: nothing reachable here is
|
|
1010
|
+
* reachable that the page itself does not already do.
|
|
1011
|
+
*/
|
|
1012
|
+
var handleAction = async (req, res, config, lookups) => {
|
|
1013
|
+
const { environment = "main", spaceId, revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
1014
|
+
if (typeof spaceId !== "number") {
|
|
1015
|
+
fail(res, 400, "Invalid space deployment");
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
const body = parseBody(req.body);
|
|
1019
|
+
const action = body?.action;
|
|
1020
|
+
if (!body?.elementId || !action) {
|
|
1021
|
+
fail(res, 400, "Expected { elementId, action, values }");
|
|
1022
|
+
return;
|
|
1023
|
+
}
|
|
1024
|
+
const element = (await config.adapters.getOfflineData(spaceId, environment, revision))?.schema.flat[body.elementId];
|
|
1025
|
+
if (!element || element.definition.runtime !== "server") {
|
|
1026
|
+
fail(res, 404, "Unknown provider element");
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
const { connector: connectorId, resource } = element.attributes;
|
|
1030
|
+
if (!connectorId) {
|
|
1031
|
+
fail(res, 400, "Element has no connector");
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
const manifest = await lookups.getConnector(spaceId, connectorId, {
|
|
1035
|
+
environment,
|
|
1036
|
+
revision
|
|
1037
|
+
});
|
|
1038
|
+
if (!manifest) {
|
|
1039
|
+
fail(res, 404, "Unknown connector");
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
if (!manifest.endpoints.write?.[action]) {
|
|
1043
|
+
fail(res, 405, `Connector does not allow "${action}"`);
|
|
1044
|
+
return;
|
|
1045
|
+
}
|
|
1046
|
+
const credential = manifest.credential && lookups.getCredential ? await lookups.getCredential(spaceId, manifest.credential) : void 0;
|
|
1047
|
+
try {
|
|
1048
|
+
const record = await writeConnectorRecord({
|
|
1049
|
+
manifest,
|
|
1050
|
+
credential,
|
|
1051
|
+
action,
|
|
1052
|
+
resource,
|
|
1053
|
+
recordId: body.recordId,
|
|
1054
|
+
values: body.values,
|
|
1055
|
+
fetchImpl: lookups.fetchImpl,
|
|
1056
|
+
outbound: { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) }
|
|
1057
|
+
});
|
|
1058
|
+
res.setStatus(200);
|
|
1059
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1060
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1061
|
+
res.send(JSON.stringify({ record: record ?? null }));
|
|
1062
|
+
} catch (err) {
|
|
1063
|
+
serverLog.error("Action", "connector write failed", err);
|
|
1064
|
+
fail(res, 502, "Connector write failed");
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
// src/worker/stages/action.ts
|
|
1068
|
+
var LINEAGE_HEADER = "x-plitzi-action-lineage";
|
|
1069
|
+
var safeParse = (body) => {
|
|
1070
|
+
try {
|
|
1071
|
+
return JSON.parse(body);
|
|
1072
|
+
} catch {
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
};
|
|
1076
|
+
/**
|
|
1077
|
+
* Who is asking, for the single-flight key and for cancellation ownership.
|
|
1078
|
+
*
|
|
1079
|
+
* A signed-in visitor is themselves; anyone else is their address. The address is a coarse identity — a shared
|
|
1080
|
+
* NAT makes two visitors look like one, which single-flight would read as a duplicate — so it is only ever used
|
|
1081
|
+
* for a `public` action, and the derived key also folds in the input: two people submitting different forms do
|
|
1082
|
+
* not collide.
|
|
1083
|
+
*/
|
|
1084
|
+
var callerIdOf = (ctx, req) => req.ctx.user ? `user:${req.ctx.user.id}` : `ip:${clientIp(ctx.raw, req)}`;
|
|
1085
|
+
var lineageOf = (req) => {
|
|
1086
|
+
const raw = req.headers[LINEAGE_HEADER];
|
|
1087
|
+
return (Array.isArray(raw) ? raw.join(",") : raw ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
1088
|
+
};
|
|
1089
|
+
/**
|
|
1090
|
+
* The action endpoint: server-driven provider writes, and server actions.
|
|
1091
|
+
*
|
|
1092
|
+
* Two addressing modes on one path, because both are "the browser asks the server to change something, naming it
|
|
1093
|
+
* rather than addressing it". An element-addressed body reaches a connector's declared write; an action-addressed
|
|
1094
|
+
* one runs a stored flow. Each mode is inert unless its own half of the config is present, so a deployment that
|
|
1095
|
+
* configures neither has no endpoint at all — and guessing what an unconfigured one should do would be the whole
|
|
1096
|
+
* vulnerability.
|
|
1097
|
+
*/
|
|
1098
|
+
/** `/_action`, its catalog, webhooks and cancels, and a connector's writes: over the engine's own configuration. */
|
|
1099
|
+
var createActionStage = (config, actions) => async (ctx) => {
|
|
1100
|
+
const { req } = ctx;
|
|
1101
|
+
const actionPath = config.action?.path ?? "/_action";
|
|
1102
|
+
const { connectors } = config;
|
|
1103
|
+
if (!connectors && !actions) return false;
|
|
1104
|
+
if (actions && req.method === "GET" && req.path === `${actionPath}/catalog`) {
|
|
1105
|
+
ctx.operation = "action:catalog";
|
|
1106
|
+
if (!req.ctx.user) {
|
|
1107
|
+
ctx.res.setStatus(401);
|
|
1108
|
+
ctx.res.send("");
|
|
1109
|
+
return true;
|
|
1110
|
+
}
|
|
1111
|
+
const { spaceId, environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
1112
|
+
await handleActionCatalog({
|
|
1113
|
+
res: ctx.res,
|
|
1114
|
+
module: actions,
|
|
1115
|
+
...typeof spaceId === "number" ? {
|
|
1116
|
+
spaceId,
|
|
1117
|
+
at: {
|
|
1118
|
+
environment,
|
|
1119
|
+
revision
|
|
1120
|
+
}
|
|
1121
|
+
} : {}
|
|
1122
|
+
});
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
if (actions && req.method === "POST" && req.path.startsWith(`${actionPath}/hook/`)) {
|
|
1126
|
+
ctx.operation = "action:webhook";
|
|
1127
|
+
req.body = await readRawBody(ctx.raw);
|
|
1128
|
+
await handleActionWebhook({
|
|
1129
|
+
req,
|
|
1130
|
+
res: ctx.res,
|
|
1131
|
+
config,
|
|
1132
|
+
module: actions,
|
|
1133
|
+
signal: ctx.signal,
|
|
1134
|
+
actionId: req.path.slice(`${actionPath}/hook/`.length),
|
|
1135
|
+
callerId: `ip:${clientIp(ctx.raw, req)}`,
|
|
1136
|
+
lineage: lineageOf(req)
|
|
1137
|
+
});
|
|
1138
|
+
return true;
|
|
1139
|
+
}
|
|
1140
|
+
if (actions && req.method === "DELETE" && req.path.startsWith(`${actionPath}/run/`)) {
|
|
1141
|
+
ctx.operation = "action:cancel";
|
|
1142
|
+
await handleActionCancel({
|
|
1143
|
+
res: ctx.res,
|
|
1144
|
+
module: actions,
|
|
1145
|
+
runId: req.path.slice(`${actionPath}/run/`.length),
|
|
1146
|
+
callerId: callerIdOf(ctx, req)
|
|
1147
|
+
});
|
|
1148
|
+
return true;
|
|
1149
|
+
}
|
|
1150
|
+
if (req.method !== "POST" || req.path !== actionPath) return false;
|
|
1151
|
+
req.body = await readRawBody(ctx.raw);
|
|
1152
|
+
const body = req.body ? safeParse(req.body) : void 0;
|
|
1153
|
+
const addressesAction = body !== void 0 && typeof body === "object" && body !== null && "actionId" in body;
|
|
1154
|
+
if (addressesAction && actions) {
|
|
1155
|
+
ctx.operation = "action:run";
|
|
1156
|
+
await handleActionCall({
|
|
1157
|
+
req,
|
|
1158
|
+
res: ctx.res,
|
|
1159
|
+
raw: ctx.rawRes,
|
|
1160
|
+
config,
|
|
1161
|
+
module: actions,
|
|
1162
|
+
signal: ctx.signal,
|
|
1163
|
+
callerId: callerIdOf(ctx, req),
|
|
1164
|
+
lineage: lineageOf(req)
|
|
1165
|
+
});
|
|
1166
|
+
return true;
|
|
1167
|
+
}
|
|
1168
|
+
if (addressesAction || !connectors) {
|
|
1169
|
+
ctx.operation = "action";
|
|
1170
|
+
ctx.res.setStatus(404);
|
|
1171
|
+
ctx.res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1172
|
+
ctx.res.send(JSON.stringify({
|
|
1173
|
+
error: "This server runs no actions",
|
|
1174
|
+
reason: "not_found"
|
|
1175
|
+
}));
|
|
1176
|
+
return true;
|
|
1177
|
+
}
|
|
1178
|
+
ctx.operation = "action";
|
|
1179
|
+
await handleAction(req, ctx.res, config, connectorLookupsOf(connectors));
|
|
1180
|
+
return true;
|
|
1181
|
+
};
|
|
1182
|
+
// src/worker/stages/functionRoutes.ts
|
|
1183
|
+
/**
|
|
1184
|
+
* The space's functions answering HTTP under `/fn/`: a request there that a declared route answers is run
|
|
1185
|
+
* by it — the deployment's own routes first, then the space's, in the sandbox — and anything else goes on to the page
|
|
1186
|
+
* server, which answers as it would have. `/fn` is never a page: its slug is refused, so the path is the functions'.
|
|
1187
|
+
*
|
|
1188
|
+
* After the auth chain, so `ctx.user` is who the session says; the session itself never reaches the code.
|
|
1189
|
+
*/
|
|
1190
|
+
var createFunctionRoutesStage = (actions) => async (ctx) => {
|
|
1191
|
+
const { req } = ctx;
|
|
1192
|
+
const { spaceId, environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
1193
|
+
if (typeof spaceId !== "number" || !req.path.startsWith(`${FUNCTION_ROUTES_PREFIX}/`)) return false;
|
|
1194
|
+
const route = await actions.routeFor({
|
|
1195
|
+
spaceId,
|
|
1196
|
+
environment,
|
|
1197
|
+
at: {
|
|
1198
|
+
environment,
|
|
1199
|
+
revision
|
|
1200
|
+
},
|
|
1201
|
+
...req.ctx.user ? { user: req.ctx.user } : {},
|
|
1202
|
+
callerId: req.ctx.user ? `user:${String(req.ctx.user.id)}` : `ip:${clientIp(ctx.raw, req)}`,
|
|
1203
|
+
...requestOrigin(req) ? { origin: requestOrigin(req) } : {},
|
|
1204
|
+
signal: ctx.signal
|
|
1205
|
+
}, req.method, req.path.slice(FUNCTION_ROUTES_PREFIX.length));
|
|
1206
|
+
if (!route) return false;
|
|
1207
|
+
ctx.operation = "function:route";
|
|
1208
|
+
const headers = new Headers();
|
|
1209
|
+
Object.entries(req.headers).forEach(([name, value]) => {
|
|
1210
|
+
if (!name.startsWith(":") && value !== void 0) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
|
|
1211
|
+
});
|
|
1212
|
+
const hasBody = req.method !== "GET" && req.method !== "HEAD";
|
|
1213
|
+
const { response, streamed } = await route.handle(new Request(`${requestOrigin(req) || `${req.protocol}://${req.hostname}`}${req.url}`, {
|
|
1214
|
+
method: req.method,
|
|
1215
|
+
headers,
|
|
1216
|
+
...hasBody ? { body: new Uint8Array(await readRawBytes(ctx.raw)) } : {}
|
|
1217
|
+
}));
|
|
1218
|
+
if (!response.headers.has("cache-control")) response.headers.set("Cache-Control", "no-store");
|
|
1219
|
+
if (streamed) {
|
|
1220
|
+
await writeWebResponse(ctx.rawRes, response, ctx.signal);
|
|
1221
|
+
return true;
|
|
1222
|
+
}
|
|
1223
|
+
ctx.res.setStatus(response.status);
|
|
1224
|
+
response.headers.forEach((value, name) => {
|
|
1225
|
+
ctx.res.setHeader(name, value);
|
|
1226
|
+
});
|
|
1227
|
+
ctx.res.send(Buffer.from(await response.arrayBuffer()));
|
|
1228
|
+
return true;
|
|
1229
|
+
};
|
|
1230
|
+
/** The secret a kept call is read with, beside its job: what the page was answered when it was kept. */
|
|
1231
|
+
var TICKET_HEADER = "x-plitzi-ticket";
|
|
1232
|
+
var MAX_KEY = 200;
|
|
1233
|
+
var send = (res, status, payload) => {
|
|
1234
|
+
res.setStatus(status);
|
|
1235
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1236
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1237
|
+
res.send(JSON.stringify(payload));
|
|
1238
|
+
};
|
|
1239
|
+
var parse$1 = (body) => {
|
|
1240
|
+
try {
|
|
1241
|
+
return JSON.parse(body);
|
|
1242
|
+
} catch {
|
|
1243
|
+
return;
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
/**
|
|
1247
|
+
* Calls kept for later, on the page server: what a page falls back to when no worker answered its call — the page
|
|
1248
|
+
* server serves the page's host whatever the workers do. A call is checked here as `/_action` checks it — the action
|
|
1249
|
+
* at the revision the page was published at, its access for the session asking, its input — and only then kept, as
|
|
1250
|
+
* the caller's, to run on the first worker that can (`keepCall`). `GET …/<job>` with its ticket reads where it is, and
|
|
1251
|
+
* once it ran what it answered.
|
|
1252
|
+
*/
|
|
1253
|
+
var createQueuedCallsStage = (config, actions) => {
|
|
1254
|
+
const lookups = config.action?.lookups ? actionLookupsOf(config.action.lookups) : void 0;
|
|
1255
|
+
return async (ctx) => {
|
|
1256
|
+
const { req, res } = ctx;
|
|
1257
|
+
if (req.path !== "/_plitzi/queued" && !req.path.startsWith(`/_plitzi/queued/`)) return false;
|
|
1258
|
+
ctx.operation = "action:queued";
|
|
1259
|
+
const { spaceId, environment = "main", revision = 0 } = req.ctx.spaceDeployment ?? {};
|
|
1260
|
+
const jobs = actions.jobs;
|
|
1261
|
+
if (typeof spaceId !== "number" || !jobs || !lookups) {
|
|
1262
|
+
send(res, 404, {
|
|
1263
|
+
error: "This server keeps no calls for later",
|
|
1264
|
+
reason: "not_found"
|
|
1265
|
+
});
|
|
1266
|
+
return true;
|
|
1267
|
+
}
|
|
1268
|
+
if (req.method === "GET" && req.path.startsWith(`/_plitzi/queued/`)) {
|
|
1269
|
+
const jobId = decodeURIComponent(req.path.slice(16));
|
|
1270
|
+
const raw = req.headers[TICKET_HEADER];
|
|
1271
|
+
const ticket = Array.isArray(raw) ? raw[0] : raw;
|
|
1272
|
+
const kept = ticket ? await readKeptCall(jobs.queue, spaceId, jobId, ticket) : void 0;
|
|
1273
|
+
if (!kept) {
|
|
1274
|
+
send(res, 404, {
|
|
1275
|
+
error: "No call is kept under this id for this ticket",
|
|
1276
|
+
reason: "not_found"
|
|
1277
|
+
});
|
|
1278
|
+
return true;
|
|
1279
|
+
}
|
|
1280
|
+
send(res, 200, kept);
|
|
1281
|
+
return true;
|
|
1282
|
+
}
|
|
1283
|
+
if (req.method !== "POST" || req.path !== "/_plitzi/queued") {
|
|
1284
|
+
send(res, 405, {
|
|
1285
|
+
error: "Keep a call with POST, read it with GET …/<job>",
|
|
1286
|
+
reason: "invalid_input"
|
|
1287
|
+
});
|
|
1288
|
+
return true;
|
|
1289
|
+
}
|
|
1290
|
+
const body = parse$1(await readRawBody(ctx.raw));
|
|
1291
|
+
const actionId = isRecord(body) ? body.actionId : void 0;
|
|
1292
|
+
const input = isRecord(body) ? body.input ?? {} : void 0;
|
|
1293
|
+
const idempotencyKey = isRecord(body) ? body.idempotencyKey : void 0;
|
|
1294
|
+
if (typeof actionId !== "string" || !isRecord(input) || idempotencyKey !== void 0 && (typeof idempotencyKey !== "string" || idempotencyKey.length > MAX_KEY)) {
|
|
1295
|
+
send(res, 400, {
|
|
1296
|
+
error: `Expected { actionId, input, idempotencyKey? } (a key of at most ${String(MAX_KEY)} characters)`,
|
|
1297
|
+
reason: "invalid_input"
|
|
1298
|
+
});
|
|
1299
|
+
return true;
|
|
1300
|
+
}
|
|
1301
|
+
const at = {
|
|
1302
|
+
environment,
|
|
1303
|
+
revision
|
|
1304
|
+
};
|
|
1305
|
+
const entry = await lookups.getAction(spaceId, actionId, at);
|
|
1306
|
+
if (!entry) {
|
|
1307
|
+
send(res, 404, {
|
|
1308
|
+
error: "Unknown action",
|
|
1309
|
+
reason: "not_found"
|
|
1310
|
+
});
|
|
1311
|
+
return true;
|
|
1312
|
+
}
|
|
1313
|
+
try {
|
|
1314
|
+
precheckRun(entry, {
|
|
1315
|
+
trigger: "call",
|
|
1316
|
+
input,
|
|
1317
|
+
user: req.ctx.user
|
|
1318
|
+
});
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
const reason = error instanceof ActionRunError ? error.reason : "failed";
|
|
1321
|
+
send(res, STATUS_BY_REASON[reason], {
|
|
1322
|
+
error: error instanceof Error ? error.message : "Action refused",
|
|
1323
|
+
reason
|
|
1324
|
+
});
|
|
1325
|
+
return true;
|
|
1326
|
+
}
|
|
1327
|
+
const origin = requestOrigin(req);
|
|
1328
|
+
const kept = await keepCall(jobs.queue, {
|
|
1329
|
+
spaceId,
|
|
1330
|
+
environment,
|
|
1331
|
+
actionId: entry.id,
|
|
1332
|
+
input,
|
|
1333
|
+
...req.ctx.user ? { user: req.ctx.user } : {},
|
|
1334
|
+
callerId: callerIdOf(ctx, req),
|
|
1335
|
+
...typeof idempotencyKey === "string" ? { idempotencyKey } : {},
|
|
1336
|
+
origin,
|
|
1337
|
+
at
|
|
1338
|
+
});
|
|
1339
|
+
if ("refused" in kept) {
|
|
1340
|
+
send(res, 429, {
|
|
1341
|
+
error: kept.refused,
|
|
1342
|
+
reason: "over_capacity"
|
|
1343
|
+
});
|
|
1344
|
+
return true;
|
|
1345
|
+
}
|
|
1346
|
+
send(res, 202, {
|
|
1347
|
+
status: "queued",
|
|
1348
|
+
jobId: kept.jobId,
|
|
1349
|
+
ticket: kept.ticket,
|
|
1350
|
+
runId: "",
|
|
1351
|
+
output: {}
|
|
1352
|
+
});
|
|
1353
|
+
return true;
|
|
1354
|
+
};
|
|
1355
|
+
};
|
|
1356
|
+
// src/worker/stages/realtime.ts
|
|
1357
|
+
/**
|
|
1358
|
+
* `/_realtime`: a page subscribing (GET, a stream that stays open) and publishing (POST) — or asking to switch the
|
|
1359
|
+
* same GET to a WebSocket, which does both.
|
|
1360
|
+
*
|
|
1361
|
+
* After the auth middleware, like the action endpoint: who may open a channel depends on who is asking.
|
|
1362
|
+
*/
|
|
1363
|
+
var createRealtimeStage = (realtime) => async (ctx) => {
|
|
1364
|
+
const { req } = ctx;
|
|
1365
|
+
if (req.path !== realtime.path) return false;
|
|
1366
|
+
const jobs = realtime.jobs();
|
|
1367
|
+
if (ctx.upgrade) {
|
|
1368
|
+
ctx.operation = "realtime:socket";
|
|
1369
|
+
await handleRealtimeSocket({
|
|
1370
|
+
req,
|
|
1371
|
+
res: ctx.res,
|
|
1372
|
+
raw: ctx.raw,
|
|
1373
|
+
upgrade: ctx.upgrade,
|
|
1374
|
+
hub: realtime.hub,
|
|
1375
|
+
resolveChannels: realtime.resolveChannels,
|
|
1376
|
+
grants: realtime.grants,
|
|
1377
|
+
allowedOrigins: realtime.allowedOrigins,
|
|
1378
|
+
...jobs ? { jobs } : {},
|
|
1379
|
+
...realtime.admitSpace ? { admitSpace: realtime.admitSpace } : {}
|
|
1380
|
+
});
|
|
1381
|
+
return true;
|
|
1382
|
+
}
|
|
1383
|
+
if (req.method === "GET") {
|
|
1384
|
+
ctx.operation = "realtime:subscribe";
|
|
1385
|
+
await handleRealtimeSubscribe({
|
|
1386
|
+
req,
|
|
1387
|
+
res: ctx.res,
|
|
1388
|
+
raw: ctx.rawRes,
|
|
1389
|
+
signal: ctx.signal,
|
|
1390
|
+
hub: realtime.hub,
|
|
1391
|
+
resolveChannels: realtime.resolveChannels,
|
|
1392
|
+
grants: realtime.grants,
|
|
1393
|
+
...jobs ? { jobs } : {},
|
|
1394
|
+
...realtime.admitSpace ? { admitSpace: realtime.admitSpace } : {}
|
|
1395
|
+
});
|
|
1396
|
+
return true;
|
|
1397
|
+
}
|
|
1398
|
+
if (req.method === "POST") {
|
|
1399
|
+
ctx.operation = "realtime:publish";
|
|
1400
|
+
req.body = await readRawBody(ctx.raw);
|
|
1401
|
+
await handleRealtimePublish({
|
|
1402
|
+
req,
|
|
1403
|
+
res: ctx.res,
|
|
1404
|
+
hub: realtime.hub
|
|
1405
|
+
});
|
|
1406
|
+
return true;
|
|
1407
|
+
}
|
|
1408
|
+
ctx.res.setStatus(405);
|
|
1409
|
+
ctx.res.setHeader("Allow", "GET, POST");
|
|
1410
|
+
ctx.res.send("");
|
|
1411
|
+
return true;
|
|
1412
|
+
};
|
|
1413
|
+
// src/worker/pageEngine.ts
|
|
1414
|
+
/**
|
|
1415
|
+
* The actions engine as a page server is handed it (RFC 0032, D11): the actions module, the realtime channels and the
|
|
1416
|
+
* connectors' writes, each built once from the engine's own configuration — `action`, `functions`, `connectors`,
|
|
1417
|
+
* `realtime` — and nothing of the page server's. Undefined when there is nothing of the engine to run.
|
|
1418
|
+
*
|
|
1419
|
+
* Its stages close over what it built, so they read nothing of the server they are mounted in: the same ones answer in
|
|
1420
|
+
* a page server and in a worker.
|
|
1421
|
+
*/
|
|
1422
|
+
var createPageEngine = (config) => {
|
|
1423
|
+
const problem = actionOriginProblem(config.action, "pages");
|
|
1424
|
+
if (problem) throw new Error(problem);
|
|
1425
|
+
const actions = actionsModuleFor(config);
|
|
1426
|
+
const realtime = realtimeModuleFor(config);
|
|
1427
|
+
/** The job worker's stop, once: begun when the server is told to stop, awaited before its sockets close. */
|
|
1428
|
+
let jobsStopped;
|
|
1429
|
+
const connectors = config.connectors ? connectorLookupsOf(config.connectors) : void 0;
|
|
1430
|
+
if (!actions && !realtime && !connectors) return;
|
|
1431
|
+
const resolveConnector = connectors ? createConnectorResolver(connectors, { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) }) : void 0;
|
|
1432
|
+
const lookups = config.action?.lookups ? actionLookupsOf(config.action.lookups) : void 0;
|
|
1433
|
+
const resolveAction = actions && lookups ? createActionResolver(lookups, actions) : void 0;
|
|
1434
|
+
const resolveElement = (context) => {
|
|
1435
|
+
const attributes = context.element.attributes;
|
|
1436
|
+
if (attributes.connector) return resolveConnector ? resolveConnector(context) : Promise.resolve(void 0);
|
|
1437
|
+
return attributes.action && resolveAction ? resolveAction(context) : Promise.resolve(void 0);
|
|
1438
|
+
};
|
|
1439
|
+
return {
|
|
1440
|
+
endpoints: [
|
|
1441
|
+
...actions || connectors ? [createActionStage(config, actions)] : [],
|
|
1442
|
+
...actions?.jobs ? [createQueuedCallsStage(config, actions)] : [],
|
|
1443
|
+
...realtime ? [createRealtimeStage(realtime)] : []
|
|
1444
|
+
],
|
|
1445
|
+
routes: actions ? [createFunctionRoutesStage(actions)] : [],
|
|
1446
|
+
...realtime ? { upgrades: (path) => path === realtime.path } : {},
|
|
1447
|
+
resolveElement,
|
|
1448
|
+
...lookups?.getData ? { data: lookups.getData } : {},
|
|
1449
|
+
published: {
|
|
1450
|
+
...actions || connectors ? { actionPath: publishedActionEndpoint(config.action) } : {},
|
|
1451
|
+
...realtime ? {
|
|
1452
|
+
realtimePath: realtime.path,
|
|
1453
|
+
realtimeTransport: realtime.transport
|
|
1454
|
+
} : {}
|
|
1455
|
+
},
|
|
1456
|
+
listening: () => {
|
|
1457
|
+
if (runsFleetJobs()) actions?.jobs?.start();
|
|
1458
|
+
},
|
|
1459
|
+
closing: () => realtime?.close(),
|
|
1460
|
+
stopping: () => {
|
|
1461
|
+
jobsStopped ??= actions?.jobs?.stop();
|
|
1462
|
+
},
|
|
1463
|
+
destroy: async () => {
|
|
1464
|
+
await (jobsStopped ??= actions?.jobs?.stop());
|
|
1465
|
+
},
|
|
1466
|
+
fleetStores: ACTIONS_FLEET_STORES,
|
|
1467
|
+
setPluginFunctions: (plugin, definition) => {
|
|
1468
|
+
if (!actions) throw new Error(`[SSR] This server runs no actions (\`action.lookups\`), so no plugin's functions: "${plugin}"`);
|
|
1469
|
+
if (definition !== void 0 && !isFunctionsDefinition(definition)) throw new Error(`[SSR] The functions of plugin "${plugin}" are not a definition: defineFunctions({ … })`);
|
|
1470
|
+
actions.setPluginFunctions(plugin, definition);
|
|
1471
|
+
}
|
|
1472
|
+
};
|
|
1473
|
+
};
|
|
1474
|
+
// src/worker/stages/cors.ts
|
|
1475
|
+
/** What a page's action calls send beside their cookies: the body's type. */
|
|
1476
|
+
var ALLOWED_HEADERS = "Content-Type";
|
|
1477
|
+
var ALLOWED_METHODS = "GET, POST, DELETE";
|
|
1478
|
+
/**
|
|
1479
|
+
* CORS for the pages that call the actions on another origin (`action.pageOrigins`): their calls carry the visitor's
|
|
1480
|
+
* cookies (`credentials: 'include'`), so each is answered with its own origin and credentials — never `*`, which a
|
|
1481
|
+
* browser refuses with credentials and which would let any site call with a visitor's cookies. A preflight from one of
|
|
1482
|
+
* them is answered here; from any other origin it is not, and the browser stops the call. A request of no listed origin
|
|
1483
|
+
* goes on unmarked: the cross-site check after this refuses its write.
|
|
1484
|
+
*/
|
|
1485
|
+
var createActionCorsStage = (pageOrigins) => {
|
|
1486
|
+
const allowed = new Set(pageOrigins);
|
|
1487
|
+
return ({ req, res }) => {
|
|
1488
|
+
const origin = req.headers.origin;
|
|
1489
|
+
if (typeof origin !== "string" || !allowed.has(origin)) return false;
|
|
1490
|
+
res.setHeader("Access-Control-Allow-Origin", origin);
|
|
1491
|
+
res.setHeader("Access-Control-Allow-Credentials", "true");
|
|
1492
|
+
res.setHeader("Vary", "Origin");
|
|
1493
|
+
if (req.method !== "OPTIONS") return false;
|
|
1494
|
+
res.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS);
|
|
1495
|
+
res.setHeader("Access-Control-Allow-Headers", ALLOWED_HEADERS);
|
|
1496
|
+
res.setHeader("Access-Control-Max-Age", "600");
|
|
1497
|
+
res.setStatus(204);
|
|
1498
|
+
res.end();
|
|
1499
|
+
return true;
|
|
1500
|
+
};
|
|
1501
|
+
};
|
|
1502
|
+
// src/worker/stages/forward.ts
|
|
1503
|
+
/** Said on a request one worker hands another: the second serves it, and never hands it on again. */
|
|
1504
|
+
var FORWARDED_HEADER = "x-plitzi-forwarded";
|
|
1505
|
+
/**
|
|
1506
|
+
* Hands a space's request to the worker that serves it, when the deployment keeps some spaces on workers of their own:
|
|
1507
|
+
* `forward` answers that worker's origin for the space, or nothing when this one serves it. The request goes as it
|
|
1508
|
+
* came — its method, its headers (its host among them, so the other resolves the same space), its body streamed — and
|
|
1509
|
+
* the answer comes back the same way, an event stream included. Once only: the other worker serves what it is handed.
|
|
1510
|
+
* One it cannot reach is answered 502, saying which, never served here in its place unsaid.
|
|
1511
|
+
*/
|
|
1512
|
+
var createForwardStage = (forward) => ({ raw, rawRes, req }) => {
|
|
1513
|
+
const spaceId = req.ctx.spaceDeployment?.spaceId;
|
|
1514
|
+
if (spaceId == null || raw.headers["x-plitzi-forwarded"] !== void 0) return false;
|
|
1515
|
+
const target = forward(spaceId);
|
|
1516
|
+
if (!target) return false;
|
|
1517
|
+
return new Promise((resolve) => {
|
|
1518
|
+
const upstream = request(new URL(raw.url ?? "/", target), {
|
|
1519
|
+
method: raw.method,
|
|
1520
|
+
headers: {
|
|
1521
|
+
...raw.headers,
|
|
1522
|
+
[FORWARDED_HEADER]: "1"
|
|
1523
|
+
}
|
|
1524
|
+
}, (answer) => {
|
|
1525
|
+
const headers = Object.fromEntries(Object.entries(answer.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, value]]));
|
|
1526
|
+
rawRes.writeHead(answer.statusCode ?? 502, headers);
|
|
1527
|
+
answer.on("data", (chunk) => {
|
|
1528
|
+
rawRes.write(chunk);
|
|
1529
|
+
});
|
|
1530
|
+
answer.on("end", () => {
|
|
1531
|
+
rawRes.end();
|
|
1532
|
+
resolve(true);
|
|
1533
|
+
});
|
|
1534
|
+
answer.on("error", () => {
|
|
1535
|
+
rawRes.end();
|
|
1536
|
+
resolve(true);
|
|
1537
|
+
});
|
|
1538
|
+
});
|
|
1539
|
+
upstream.on("error", (error) => {
|
|
1540
|
+
if (!rawRes.headersSent) {
|
|
1541
|
+
rawRes.writeHead(502, { "content-type": "application/json; charset=utf-8" });
|
|
1542
|
+
rawRes.write(JSON.stringify({ error: `The worker that serves space ${String(spaceId)} did not answer: ${error.message}` }));
|
|
1543
|
+
}
|
|
1544
|
+
rawRes.end();
|
|
1545
|
+
resolve(true);
|
|
1546
|
+
});
|
|
1547
|
+
raw.pipe(upstream);
|
|
1548
|
+
});
|
|
1549
|
+
};
|
|
1550
|
+
// src/worker/stages/render.ts
|
|
1551
|
+
var parse = (body) => {
|
|
1552
|
+
try {
|
|
1553
|
+
return JSON.parse(body);
|
|
1554
|
+
} catch {
|
|
1555
|
+
return;
|
|
1556
|
+
}
|
|
1557
|
+
};
|
|
1558
|
+
/**
|
|
1559
|
+
* `POST /_render`: a page server's server element, resolved here — the remote half of §4.3. Behind `render.secret`, so
|
|
1560
|
+
* the user it names is the one the page server signed in; ahead of the deployment middleware, because the host it
|
|
1561
|
+
* arrives on is the worker's own and the space is said in the ask. A failure is answered as one, with the runs that
|
|
1562
|
+
* fed it, so the page shows its error state and a debugger sees where the flow broke.
|
|
1563
|
+
*/
|
|
1564
|
+
var createRenderStage = (resolve, secret) => {
|
|
1565
|
+
const answer = (ctx, status, body) => {
|
|
1566
|
+
ctx.res.setStatus(status);
|
|
1567
|
+
ctx.res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1568
|
+
ctx.res.send(JSON.stringify(body));
|
|
1569
|
+
return true;
|
|
1570
|
+
};
|
|
1571
|
+
return async (ctx) => {
|
|
1572
|
+
const { req } = ctx;
|
|
1573
|
+
if (req.path !== "/_render") return false;
|
|
1574
|
+
ctx.operation = "render";
|
|
1575
|
+
if (req.method !== "POST") return answer(ctx, 405, { error: `${RENDER_PATH} is asked with POST` });
|
|
1576
|
+
if (!bearerMatches(req.headers.authorization, secret)) return answer(ctx, 401, { error: `${RENDER_PATH} is asked with the worker's render secret, as a bearer token` });
|
|
1577
|
+
const body = parse(await readRawBody(ctx.raw));
|
|
1578
|
+
const ask = readRenderAsk(body);
|
|
1579
|
+
if (typeof ask === "string") return answer(ctx, 400, { error: ask });
|
|
1580
|
+
const refusal = protocolRefusal(ask.protocol, "1.0", {
|
|
1581
|
+
here: "worker",
|
|
1582
|
+
there: "page server"
|
|
1583
|
+
});
|
|
1584
|
+
if (refusal) return answer(ctx, 409, { error: refusal });
|
|
1585
|
+
req.ctx.spaceDeployment = {
|
|
1586
|
+
spaceId: ask.spaceId,
|
|
1587
|
+
environment: ask.environment,
|
|
1588
|
+
revision: ask.revision
|
|
1589
|
+
};
|
|
1590
|
+
if (ask.user) req.ctx.user = ask.user;
|
|
1591
|
+
if (ask.rscParams) req.ctx.rscParams = ask.rscParams;
|
|
1592
|
+
const runs = [];
|
|
1593
|
+
req.ctx.actionRuns = runs;
|
|
1594
|
+
try {
|
|
1595
|
+
const data = await resolve({
|
|
1596
|
+
element: ask.element,
|
|
1597
|
+
input: ask.input,
|
|
1598
|
+
flat: ask.subtree,
|
|
1599
|
+
routeParams: ask.routeParams,
|
|
1600
|
+
queryParams: ask.queryParams,
|
|
1601
|
+
templateData: {
|
|
1602
|
+
...ask.templateData,
|
|
1603
|
+
paintedKeys: new Set(ask.templateData.paintedKeys)
|
|
1604
|
+
},
|
|
1605
|
+
req,
|
|
1606
|
+
spaceId: ask.spaceId,
|
|
1607
|
+
environment: ask.environment,
|
|
1608
|
+
user: ask.user,
|
|
1609
|
+
signal: ctx.signal
|
|
1610
|
+
});
|
|
1611
|
+
return answer(ctx, 200, {
|
|
1612
|
+
ok: true,
|
|
1613
|
+
data,
|
|
1614
|
+
runs
|
|
1615
|
+
});
|
|
1616
|
+
} catch (error) {
|
|
1617
|
+
const said = error instanceof Error && "said" in error && typeof error.said === "string" ? error.said : void 0;
|
|
1618
|
+
return answer(ctx, 200, {
|
|
1619
|
+
ok: false,
|
|
1620
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1621
|
+
refused: error instanceof Error && "refused" in error && error.refused === true,
|
|
1622
|
+
...said === void 0 ? {} : { said },
|
|
1623
|
+
runs
|
|
1624
|
+
});
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
};
|
|
1628
|
+
// src/worker/worker.ts
|
|
1629
|
+
/** What no stage of a worker answers: its paths are the engine's, and nothing else is served here. */
|
|
1630
|
+
var notFoundStage = ({ res }) => {
|
|
1631
|
+
res.setStatus(404);
|
|
1632
|
+
res.send("");
|
|
1633
|
+
return true;
|
|
1634
|
+
};
|
|
1635
|
+
/**
|
|
1636
|
+
* The actions engine as a server of its own (RFC 0032, D8): `/_action` and its webhooks, `/fn/` routes, `/_realtime` and
|
|
1637
|
+
* the job queue, on `@plitzi/sdk-kernel` alone — nothing of pages, RSC or signing in. It resolves the host's
|
|
1638
|
+
* deployment and who is calling with the same adapters a page server is given, so a gateway may send those paths of a
|
|
1639
|
+
* space's host here, beside the page servers or on another machine.
|
|
1640
|
+
*
|
|
1641
|
+
* Refused when there is nothing to run: a worker with no `action.lookups`, `connectors` or realtime would answer 404 to
|
|
1642
|
+
* every call with nothing said. Refused too on another origin (`action.origin`) with no `action.pageOrigins`, whose
|
|
1643
|
+
* pages its CORS answers with credentials and its cross-site check takes as its own.
|
|
1644
|
+
*/
|
|
1645
|
+
var createWorker = ({ identity, render, forward, ...config }) => {
|
|
1646
|
+
const problem = actionOriginProblem(config.action, "worker");
|
|
1647
|
+
if (problem) throw new Error(`createWorker: ${problem}`);
|
|
1648
|
+
if (render && render.secret.length < 32) throw new Error("createWorker: `render.secret` must be at least 32 characters — whoever holds it renders as anyone");
|
|
1649
|
+
configureServerLog({
|
|
1650
|
+
level: config.logLevel ?? defaultLogLevel(config.devMode),
|
|
1651
|
+
...config.logger ? { logger: config.logger } : {},
|
|
1652
|
+
...config.slowRunMs === void 0 ? {} : { slowRunMs: config.slowRunMs }
|
|
1653
|
+
});
|
|
1654
|
+
const pageOrigins = config.action?.origin ? config.action.pageOrigins ?? [] : [];
|
|
1655
|
+
const served = {
|
|
1656
|
+
...config,
|
|
1657
|
+
adapters: {
|
|
1658
|
+
...config.adapters,
|
|
1659
|
+
...identity
|
|
1660
|
+
},
|
|
1661
|
+
...pageOrigins.length > 0 ? { crossSiteWrites: {
|
|
1662
|
+
...config.crossSiteWrites,
|
|
1663
|
+
origins: [...config.crossSiteWrites?.origins ?? [], ...pageOrigins]
|
|
1664
|
+
} } : {}
|
|
1665
|
+
};
|
|
1666
|
+
const engine = createPageEngine(served);
|
|
1667
|
+
if (!engine) throw new Error("createWorker runs the actions engine, and was given none of it: name `action.lookups` (and `functions`, `connectors` or `realtime` as the deployment has them)");
|
|
1668
|
+
const stages = [
|
|
1669
|
+
healthStage,
|
|
1670
|
+
statsStage,
|
|
1671
|
+
...render && engine.resolveElement ? [createRenderStage(engine.resolveElement, render.secret)] : [],
|
|
1672
|
+
...pageOrigins.length > 0 ? [createActionCorsStage(pageOrigins)] : [],
|
|
1673
|
+
crossSiteWritesStage,
|
|
1674
|
+
createMiddlewaresStage(),
|
|
1675
|
+
...forward ? [createForwardStage(forward)] : [],
|
|
1676
|
+
...engine.endpoints,
|
|
1677
|
+
...engine.routes,
|
|
1678
|
+
notFoundStage
|
|
1679
|
+
];
|
|
1680
|
+
const makeHandlerForPort = (port) => {
|
|
1681
|
+
const buildContext = (raw, rawRes, req, res) => ({
|
|
1682
|
+
raw,
|
|
1683
|
+
rawRes,
|
|
1684
|
+
req,
|
|
1685
|
+
res,
|
|
1686
|
+
config: served,
|
|
1687
|
+
port
|
|
1688
|
+
});
|
|
1689
|
+
return makeHandler("Worker", buildContext, stages, {
|
|
1690
|
+
compression: served.compression,
|
|
1691
|
+
...engine.upgrades ? { upgrades: engine.upgrades } : {}
|
|
1692
|
+
});
|
|
1693
|
+
};
|
|
1694
|
+
return createHttpServer(served, makeHandlerForPort, {
|
|
1695
|
+
label: "Worker",
|
|
1696
|
+
...engine.listening ? { onListen: engine.listening } : {},
|
|
1697
|
+
...engine.closing ? { onClosing: engine.closing } : {},
|
|
1698
|
+
...engine.stopping ? { onStopping: engine.stopping } : {},
|
|
1699
|
+
...engine.destroy ? { onDestroy: engine.destroy } : {},
|
|
1700
|
+
...engine.fleetStores ? { fleetStores: engine.fleetStores } : {}
|
|
1701
|
+
});
|
|
1702
|
+
};
|
|
1703
|
+
export { DEFAULT_ACTION_PATH, createPageEngine, createWorker, engineOnWorker };
|