@temps-sdk/plugin 0.1.0-beta.1 → 0.1.0-beta.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/README.md +43 -117
- package/dist/ai.d.ts +32 -0
- package/dist/ai.d.ts.map +1 -0
- package/dist/ai.js +38 -0
- package/dist/ai.js.map +1 -0
- package/dist/client.d.ts +41 -10
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +146 -89
- package/dist/client.js.map +1 -1
- package/dist/context.d.ts +21 -12
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +25 -36
- package/dist/context.js.map +1 -1
- package/dist/errors.d.ts +0 -23
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +0 -46
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +38 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +43 -6
- package/dist/index.js.map +1 -1
- package/dist/launch.d.ts +9 -0
- package/dist/launch.d.ts.map +1 -0
- package/dist/launch.js +96 -0
- package/dist/launch.js.map +1 -0
- package/dist/manifest-builder.d.ts +4 -9
- package/dist/manifest-builder.d.ts.map +1 -1
- package/dist/manifest-builder.js +7 -26
- package/dist/manifest-builder.js.map +1 -1
- package/dist/protocol.d.ts +28 -14
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js +50 -94
- package/dist/protocol.js.map +1 -1
- package/dist/runtime.d.ts +21 -12
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +318 -426
- package/dist/runtime.js.map +1 -1
- package/dist/tools.d.ts +22 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +239 -0
- package/dist/tools.js.map +1 -0
- package/dist/types.d.ts +149 -150
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +1 -4
- package/dist/types.js.map +1 -1
- package/dist/ui.d.ts.map +1 -1
- package/dist/ui.js +7 -26
- package/dist/ui.js.map +1 -1
- package/package.json +21 -22
- package/LICENSE +0 -21
- package/dist/api.d.ts +0 -33
- package/dist/api.d.ts.map +0 -1
- package/dist/api.js +0 -96
- package/dist/api.js.map +0 -1
- package/dist/auth.d.ts +0 -41
- package/dist/auth.d.ts.map +0 -1
- package/dist/auth.js +0 -102
- package/dist/auth.js.map +0 -1
package/dist/runtime.js
CHANGED
|
@@ -1,511 +1,403 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2024-2026 Temps Contributors
|
|
2
2
|
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
-
import {
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
/**
|
|
5
|
+
* Plugin runtime -- handles the full lifecycle of a Temps external plugin.
|
|
6
|
+
*
|
|
7
|
+
* Mirrors: crates/temps-plugin-sdk/src/runtime.rs
|
|
8
|
+
*
|
|
9
|
+
* Built for Bun -- compiled to a single binary via `bun build --compile`.
|
|
10
|
+
*
|
|
11
|
+
* Lifecycle:
|
|
12
|
+
* 1. Parse non-secret CLI arguments (--socket-path, --data-dir)
|
|
13
|
+
* 2. Emit protocol-2 hello and receive private launch configuration on stdin
|
|
14
|
+
* 3. Start Bun.serve on Unix domain socket
|
|
15
|
+
* 4. Emit ready to stdout (handshake phase 2)
|
|
16
|
+
* 5. Accept WebSocket connection from host on /_temps/channel
|
|
17
|
+
* 6. Create PluginContext with TempsClient
|
|
18
|
+
* 7. Call plugin.onStart()
|
|
19
|
+
* 8. Serve plugin routes, health, events, and embedded UI
|
|
20
|
+
* 9. Handle SIGTERM for graceful shutdown
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, mkdirSync, unlinkSync } from "node:fs";
|
|
4
23
|
import { dirname } from "node:path";
|
|
5
|
-
import { attachVerifiedCaller, verifyProxyHeaders, } from "./auth.js";
|
|
6
24
|
import { TempsClient } from "./client.js";
|
|
7
25
|
import { PluginContext } from "./context.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
26
|
+
import { emitManifest, emitReady, PLUGIN_CHANNEL_PATH, extractAuthContext, } from "./protocol.js";
|
|
27
|
+
import { createEmbeddedUiHandler } from "./ui.js";
|
|
28
|
+
import { ArgsError, InitializationError } from "./errors.js";
|
|
29
|
+
import { readLaunchConfig, authenticatedHostRequest, requiresHostAuthentication, validateHealthPath, } from "./launch.js";
|
|
30
|
+
/**
|
|
31
|
+
* Run a Temps plugin. This is the main entry point.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```ts
|
|
35
|
+
* import { runPlugin, createManifest } from "@temps-sdk/plugin";
|
|
36
|
+
*
|
|
37
|
+
* runPlugin({
|
|
38
|
+
* manifest: () => createManifest("my-plugin", "0.1.0")
|
|
39
|
+
* .displayName("My Plugin")
|
|
40
|
+
* .addNav("Dashboard", "layout-dashboard", "/dashboard")
|
|
41
|
+
* .build(),
|
|
42
|
+
*
|
|
43
|
+
* handler: (ctx) => async (req, res) => {
|
|
44
|
+
* res.writeHead(200, { "Content-Type": "application/json" });
|
|
45
|
+
* res.end(JSON.stringify({ hello: "world" }));
|
|
46
|
+
* },
|
|
47
|
+
* });
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
14
50
|
export async function runPlugin(plugin) {
|
|
15
|
-
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
// Stage 1: identify the protocol and requested privileges before receiving secrets.
|
|
19
|
-
emitHello(manifest);
|
|
20
|
-
const launch = await readLaunchConfig(manifest);
|
|
51
|
+
// 1. Parse CLI arguments
|
|
52
|
+
const args = parseArgs(process.argv.slice(2));
|
|
53
|
+
// Ensure data directory exists
|
|
21
54
|
mkdirSync(args.dataDir, { recursive: true });
|
|
22
|
-
|
|
23
|
-
|
|
55
|
+
const manifest = plugin.manifest();
|
|
56
|
+
validateHealthPath(manifest.health_path, manifest.name);
|
|
57
|
+
// 2. Emit manifest (handshake phase 1)
|
|
58
|
+
emitManifest(manifest);
|
|
59
|
+
const launch = await readLaunchConfig(Bun.stdin.stream(), manifest.name);
|
|
60
|
+
// Ensure socket directory exists and clean up stale socket
|
|
61
|
+
const socketDir = dirname(args.socketPath);
|
|
62
|
+
mkdirSync(socketDir, { recursive: true });
|
|
63
|
+
if (existsSync(args.socketPath)) {
|
|
64
|
+
unlinkSync(args.socketPath);
|
|
65
|
+
}
|
|
66
|
+
// Channel connection promise -- resolved when the host connects
|
|
24
67
|
let resolveChannel;
|
|
25
|
-
|
|
26
|
-
const channelReady = new Promise((resolve, reject) => {
|
|
68
|
+
const channelReady = new Promise((resolve) => {
|
|
27
69
|
resolveChannel = resolve;
|
|
28
|
-
rejectChannel = reject;
|
|
29
70
|
});
|
|
30
|
-
|
|
31
|
-
const closeListeners = new Map();
|
|
32
|
-
const errorListeners = new Map();
|
|
33
|
-
let channelClaimed = false;
|
|
71
|
+
// Track state
|
|
34
72
|
let currentContext;
|
|
35
|
-
let
|
|
36
|
-
let
|
|
73
|
+
let pluginReady = false;
|
|
74
|
+
let channelAccepted = false;
|
|
75
|
+
// Embedded UI
|
|
37
76
|
const embeddedAssets = plugin.embeddedUiAssets?.();
|
|
38
|
-
const
|
|
77
|
+
const hasUi = embeddedAssets !== undefined || plugin.uiDistPath?.() !== undefined;
|
|
78
|
+
// Build embedded UI handler if available
|
|
39
79
|
const embeddedUiHandler = embeddedAssets
|
|
40
80
|
? createEmbeddedUiHandler(embeddedAssets)
|
|
41
81
|
: undefined;
|
|
42
|
-
|
|
43
|
-
|
|
82
|
+
// Active plugin fetch handler -- set once plugin is initialized
|
|
83
|
+
let pluginFetch;
|
|
84
|
+
// Bun WebSocket adapter plumbing
|
|
85
|
+
const wsMessageListeners = new Map();
|
|
86
|
+
const wsCloseListeners = new Map();
|
|
87
|
+
// 3. Start Bun.serve on Unix socket
|
|
44
88
|
const server = Bun.serve({
|
|
45
89
|
unix: args.socketPath,
|
|
46
|
-
|
|
47
|
-
const url = new URL(
|
|
90
|
+
fetch(req, server) {
|
|
91
|
+
const url = new URL(req.url);
|
|
92
|
+
// Health discloses no caller data. Every other route, including public
|
|
93
|
+
// plugin routes forwarded by Temps, must carry the host assertion.
|
|
94
|
+
if (requiresHostAuthentication(url.pathname, manifest.health_path) &&
|
|
95
|
+
!authenticatedHostRequest(req.headers, launch.auth_secret)) {
|
|
96
|
+
return new Response("Unauthorized", { status: 401 });
|
|
97
|
+
}
|
|
98
|
+
// WebSocket upgrade for platform channel
|
|
48
99
|
if (url.pathname === PLUGIN_CHANNEL_PATH) {
|
|
49
|
-
|
|
50
|
-
if (!verification.verified) {
|
|
51
|
-
log("warn", "Rejected unauthenticated platform channel attempt", {
|
|
52
|
-
plugin: manifest.name,
|
|
53
|
-
});
|
|
54
|
-
return new Response("Unauthorized", { status: 401 });
|
|
55
|
-
}
|
|
56
|
-
if (channelClaimed)
|
|
100
|
+
if (channelAccepted)
|
|
57
101
|
return new Response("Channel already connected", { status: 409 });
|
|
58
|
-
|
|
59
|
-
|
|
102
|
+
if (server.upgrade(req)) {
|
|
103
|
+
channelAccepted = true;
|
|
60
104
|
return undefined;
|
|
61
|
-
|
|
105
|
+
}
|
|
62
106
|
return new Response("WebSocket upgrade failed", { status: 500 });
|
|
63
107
|
}
|
|
64
|
-
// Health
|
|
65
|
-
if (url.pathname === manifest.health_path) {
|
|
108
|
+
// Health endpoint -- always available
|
|
109
|
+
if (url.pathname === manifest.health_path || url.pathname === "/health") {
|
|
66
110
|
return Response.json({ status: "ok", plugin: manifest.name });
|
|
67
111
|
}
|
|
68
|
-
|
|
112
|
+
// Event delivery endpoint
|
|
113
|
+
if (url.pathname === "/_events" && req.method === "POST") {
|
|
114
|
+
return handleEventDelivery(req, plugin, currentContext);
|
|
115
|
+
}
|
|
116
|
+
// Not initialized yet
|
|
117
|
+
if (!pluginReady || !pluginFetch) {
|
|
69
118
|
return new Response("Plugin initializing", { status: 503 });
|
|
70
119
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
return authenticationRequired();
|
|
77
|
-
return handleEventDelivery(request, plugin, currentContext);
|
|
120
|
+
// Try embedded UI
|
|
121
|
+
if (embeddedUiHandler) {
|
|
122
|
+
const uiResponse = handleEmbeddedUi(url, embeddedAssets);
|
|
123
|
+
if (uiResponse)
|
|
124
|
+
return uiResponse;
|
|
78
125
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return authenticationRequired();
|
|
82
|
-
return pluginFetch(request, verification.caller);
|
|
126
|
+
// Delegate to plugin
|
|
127
|
+
return pluginFetch(req);
|
|
83
128
|
},
|
|
84
129
|
websocket: {
|
|
85
|
-
open(
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
resolveChannel
|
|
91
|
-
rejectChannel = undefined;
|
|
130
|
+
open(ws) {
|
|
131
|
+
wsMessageListeners.set(ws, new Set());
|
|
132
|
+
wsCloseListeners.set(ws, new Set());
|
|
133
|
+
const adapter = createWsAdapter(ws, wsMessageListeners, wsCloseListeners);
|
|
134
|
+
const client = new TempsClient(adapter);
|
|
135
|
+
resolveChannel?.(client);
|
|
92
136
|
},
|
|
93
|
-
message(
|
|
94
|
-
|
|
95
|
-
|
|
137
|
+
message(ws, message) {
|
|
138
|
+
const msgStr = typeof message === "string" ? message : message.toString();
|
|
139
|
+
const listeners = wsMessageListeners.get(ws);
|
|
140
|
+
if (listeners) {
|
|
141
|
+
for (const fn of listeners)
|
|
142
|
+
fn(msgStr);
|
|
143
|
+
}
|
|
96
144
|
},
|
|
97
|
-
close(
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
145
|
+
close(ws) {
|
|
146
|
+
const listeners = wsCloseListeners.get(ws);
|
|
147
|
+
if (listeners) {
|
|
148
|
+
for (const fn of listeners)
|
|
149
|
+
fn();
|
|
150
|
+
}
|
|
151
|
+
wsMessageListeners.delete(ws);
|
|
152
|
+
wsCloseListeners.delete(ws);
|
|
103
153
|
},
|
|
104
154
|
},
|
|
105
155
|
});
|
|
156
|
+
// 4. Emit ready (handshake phase 2)
|
|
157
|
+
emitReady(hasUi, plugin.openapi?.());
|
|
158
|
+
// 5. Wait for the host to connect via WebSocket channel (with timeout)
|
|
159
|
+
const channelTimeoutMs = 30_000;
|
|
160
|
+
let client;
|
|
106
161
|
try {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
client
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
plugin: manifest.name,
|
|
128
|
-
event_type: event.event_type,
|
|
129
|
-
reason: errorMessage(error),
|
|
130
|
-
});
|
|
131
|
-
}
|
|
162
|
+
client = await Promise.race([
|
|
163
|
+
channelReady,
|
|
164
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error("Channel connection timeout")), channelTimeoutMs)),
|
|
165
|
+
]);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
console.error("[temps-plugin] Warning: platform channel not connected, running without platform data access");
|
|
169
|
+
client = null;
|
|
170
|
+
}
|
|
171
|
+
// 6. Create PluginContext
|
|
172
|
+
const ctx = new PluginContext({
|
|
173
|
+
pluginName: manifest.name,
|
|
174
|
+
dataDir: args.dataDir,
|
|
175
|
+
authSecret: launch.auth_secret,
|
|
176
|
+
client,
|
|
177
|
+
});
|
|
178
|
+
currentContext = ctx;
|
|
179
|
+
if (client) {
|
|
180
|
+
client.onEvent((event) => {
|
|
181
|
+
plugin.onEvent?.(ctx, event);
|
|
132
182
|
});
|
|
183
|
+
}
|
|
184
|
+
// 7. Call plugin.onStart()
|
|
185
|
+
try {
|
|
186
|
+
await plugin.onStart?.(ctx);
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
throw new InitializationError(manifest.name, err instanceof Error ? err.message : String(err));
|
|
190
|
+
}
|
|
191
|
+
// 8. Mount the plugin handler
|
|
192
|
+
const nodeHandler = await plugin.handler(ctx);
|
|
193
|
+
// Wrap the Node-style (req, res) handler into a Bun fetch handler
|
|
194
|
+
pluginFetch = (req) => nodeRequestBridge(req, nodeHandler);
|
|
195
|
+
pluginReady = true;
|
|
196
|
+
// 9. Graceful shutdown
|
|
197
|
+
const shutdown = async () => {
|
|
198
|
+
console.error(`[temps-plugin] Shutting down ${manifest.name}...`);
|
|
133
199
|
try {
|
|
134
|
-
await plugin.
|
|
200
|
+
await plugin.onShutdown?.();
|
|
135
201
|
}
|
|
136
|
-
catch (
|
|
137
|
-
|
|
202
|
+
catch (err) {
|
|
203
|
+
console.error("[temps-plugin] Error during shutdown:", err);
|
|
138
204
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
filesystemUiHandler,
|
|
143
|
-
]);
|
|
144
|
-
const shutdown = async (signal) => {
|
|
145
|
-
if (shuttingDown)
|
|
146
|
-
return;
|
|
147
|
-
shuttingDown = true;
|
|
148
|
-
log("info", "Shutting down plugin", { plugin: manifest.name, signal });
|
|
205
|
+
client?.close();
|
|
206
|
+
server.stop();
|
|
207
|
+
if (existsSync(args.socketPath)) {
|
|
149
208
|
try {
|
|
150
|
-
|
|
209
|
+
unlinkSync(args.socketPath);
|
|
151
210
|
}
|
|
152
|
-
catch
|
|
153
|
-
|
|
154
|
-
plugin: manifest.name,
|
|
155
|
-
reason: errorMessage(error),
|
|
156
|
-
});
|
|
211
|
+
catch {
|
|
212
|
+
/* ignore */
|
|
157
213
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
214
|
+
}
|
|
215
|
+
process.exit(0);
|
|
216
|
+
};
|
|
217
|
+
process.on("SIGTERM", shutdown);
|
|
218
|
+
process.on("SIGINT", shutdown);
|
|
219
|
+
console.error(`[temps-plugin] ${manifest.display_name ?? manifest.name} v${manifest.version} running on ${args.socketPath}`);
|
|
220
|
+
}
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
// Embedded UI serving (pure Bun Response)
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
function handleEmbeddedUi(url, assets) {
|
|
225
|
+
const pathname = url.pathname;
|
|
226
|
+
// Redirect /ui to /ui/
|
|
227
|
+
if (pathname === "/ui") {
|
|
228
|
+
return new Response(null, {
|
|
229
|
+
status: 302,
|
|
230
|
+
headers: { Location: "/ui/" },
|
|
168
231
|
});
|
|
169
232
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
server.stop(true);
|
|
173
|
-
removeSocket(args.socketPath);
|
|
174
|
-
throw error;
|
|
233
|
+
if (!pathname.startsWith("/ui/")) {
|
|
234
|
+
return undefined;
|
|
175
235
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
236
|
+
const relativePath = pathname.slice("/ui/".length) || "index.html";
|
|
237
|
+
if (relativePath.includes("..")) {
|
|
238
|
+
return new Response("Forbidden", { status: 403 });
|
|
239
|
+
}
|
|
240
|
+
// Exact match
|
|
241
|
+
const file = assets.get(relativePath);
|
|
242
|
+
if (file) {
|
|
243
|
+
return new Response(new Uint8Array(file.content), {
|
|
244
|
+
headers: {
|
|
245
|
+
"Content-Type": file.contentType,
|
|
246
|
+
"Content-Length": String(file.content.byteLength),
|
|
247
|
+
"Cache-Control": file.immutable
|
|
248
|
+
? "public, max-age=31536000, immutable"
|
|
249
|
+
: "no-cache, no-store, must-revalidate",
|
|
250
|
+
},
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
// SPA fallback for paths without file extensions
|
|
254
|
+
const hasExt = (relativePath.split("/").pop() ?? "").includes(".");
|
|
255
|
+
if (!hasExt) {
|
|
256
|
+
const index = assets.get("index.html");
|
|
257
|
+
if (index) {
|
|
258
|
+
return new Response(new Uint8Array(index.content), {
|
|
259
|
+
headers: {
|
|
260
|
+
"Content-Type": index.contentType,
|
|
261
|
+
"Content-Length": String(index.content.byteLength),
|
|
262
|
+
"Cache-Control": "no-cache, no-store, must-revalidate",
|
|
263
|
+
},
|
|
264
|
+
});
|
|
188
265
|
}
|
|
189
|
-
values.set(flag, value);
|
|
190
266
|
}
|
|
191
|
-
|
|
192
|
-
const dataDir = values.get("--data-dir");
|
|
193
|
-
if (!socketPath)
|
|
194
|
-
throw new ArgsError("--socket-path is required");
|
|
195
|
-
if (!dataDir)
|
|
196
|
-
throw new ArgsError("--data-dir is required");
|
|
197
|
-
return {
|
|
198
|
-
socketPath,
|
|
199
|
-
dataDir,
|
|
200
|
-
...(values.has("--host-api-url")
|
|
201
|
-
? { hostApiUrl: values.get("--host-api-url") }
|
|
202
|
-
: {}),
|
|
203
|
-
};
|
|
267
|
+
return new Response("Not Found", { status: 404 });
|
|
204
268
|
}
|
|
205
|
-
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
// Bun WebSocket -> WsLike adapter
|
|
271
|
+
// ---------------------------------------------------------------------------
|
|
272
|
+
function createWsAdapter(ws, messageListeners, closeListeners) {
|
|
206
273
|
return {
|
|
207
|
-
on(event,
|
|
274
|
+
on(event, fn) {
|
|
208
275
|
if (event === "message") {
|
|
209
|
-
messageListeners.get(
|
|
276
|
+
messageListeners.get(ws)?.add(fn);
|
|
210
277
|
}
|
|
211
|
-
if (event === "close") {
|
|
212
|
-
closeListeners.get(
|
|
213
|
-
}
|
|
214
|
-
if (event === "error") {
|
|
215
|
-
errorListeners.get(socket)?.add(listener);
|
|
278
|
+
else if (event === "close") {
|
|
279
|
+
closeListeners.get(ws)?.add(fn);
|
|
216
280
|
}
|
|
217
281
|
},
|
|
218
|
-
send(data,
|
|
282
|
+
send(data, cb) {
|
|
219
283
|
try {
|
|
220
|
-
|
|
221
|
-
|
|
284
|
+
ws.send(data);
|
|
285
|
+
cb?.();
|
|
222
286
|
}
|
|
223
|
-
catch (
|
|
224
|
-
|
|
287
|
+
catch (err) {
|
|
288
|
+
cb?.(err);
|
|
225
289
|
}
|
|
226
290
|
},
|
|
227
291
|
close() {
|
|
228
|
-
|
|
292
|
+
ws.close();
|
|
229
293
|
},
|
|
230
294
|
};
|
|
231
295
|
}
|
|
232
|
-
async function nodeRequestBridge(
|
|
233
|
-
const url = new URL(
|
|
234
|
-
let body;
|
|
235
|
-
try {
|
|
236
|
-
body = await readRequestBody(request);
|
|
237
|
-
}
|
|
238
|
-
catch (error) {
|
|
239
|
-
if (error instanceof RequestBodyTooLargeError)
|
|
240
|
-
return payloadTooLarge(error);
|
|
241
|
-
throw error;
|
|
242
|
-
}
|
|
296
|
+
async function nodeRequestBridge(req, handler) {
|
|
297
|
+
const url = new URL(req.url);
|
|
243
298
|
return new Promise((resolve) => {
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
request.headers.forEach((value, name) => {
|
|
249
|
-
incomingHeaders[name] = value;
|
|
250
|
-
});
|
|
251
|
-
incoming.headers = incomingHeaders;
|
|
252
|
-
attachVerifiedCaller(incoming, caller);
|
|
253
|
-
const dataListeners = [];
|
|
254
|
-
const endListeners = [];
|
|
255
|
-
incoming.on = ((event, listener) => {
|
|
256
|
-
if (event === "data")
|
|
257
|
-
dataListeners.push(listener);
|
|
258
|
-
if (event === "end")
|
|
259
|
-
endListeners.push(listener);
|
|
260
|
-
return incoming;
|
|
261
|
-
});
|
|
262
|
-
let status = 200;
|
|
263
|
-
let ended = false;
|
|
264
|
-
const headers = {};
|
|
265
|
-
const responseBody = new ResponseBodyAccumulator();
|
|
266
|
-
const response = Object.create(null);
|
|
267
|
-
const failOversizedResponse = (error) => {
|
|
268
|
-
if (ended)
|
|
299
|
+
// A real readable supports both event-based plugins and async iteration.
|
|
300
|
+
const fakeReq = Readable.from((async function* () {
|
|
301
|
+
const reader = req.body?.getReader();
|
|
302
|
+
if (!reader)
|
|
269
303
|
return;
|
|
270
|
-
ended = true;
|
|
271
|
-
log("error", "Plugin response exceeded the runtime body limit", {
|
|
272
|
-
plugin: pluginName,
|
|
273
|
-
actual_bytes: error.actualBytes,
|
|
274
|
-
maximum_bytes: error.maximumBytes,
|
|
275
|
-
});
|
|
276
|
-
resolve(responseTooLarge(error));
|
|
277
|
-
};
|
|
278
|
-
Object.defineProperty(response, "statusCode", {
|
|
279
|
-
get: () => status,
|
|
280
|
-
set: (value) => {
|
|
281
|
-
status = value;
|
|
282
|
-
},
|
|
283
|
-
});
|
|
284
|
-
response.setHeader = ((name, value) => {
|
|
285
|
-
headers[name] = Array.isArray(value) ? value.join(", ") : String(value);
|
|
286
|
-
return response;
|
|
287
|
-
});
|
|
288
|
-
response.getHeader = ((name) => headers[name]);
|
|
289
|
-
response.writeHead = ((code, values) => {
|
|
290
|
-
status = code;
|
|
291
|
-
if (values)
|
|
292
|
-
Object.assign(headers, values);
|
|
293
|
-
return response;
|
|
294
|
-
});
|
|
295
|
-
response.write = ((value) => {
|
|
296
|
-
if (ended)
|
|
297
|
-
return false;
|
|
298
304
|
try {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
failOversizedResponse(error);
|
|
305
|
-
return false;
|
|
305
|
+
while (true) {
|
|
306
|
+
const { done, value } = await reader.read();
|
|
307
|
+
if (done)
|
|
308
|
+
break;
|
|
309
|
+
yield Buffer.from(value);
|
|
306
310
|
}
|
|
307
|
-
throw error;
|
|
308
311
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
if (ended)
|
|
312
|
-
return response;
|
|
313
|
-
try {
|
|
314
|
-
if (value)
|
|
315
|
-
responseBody.append(value);
|
|
316
|
-
}
|
|
317
|
-
catch (error) {
|
|
318
|
-
if (error instanceof ResponseBodyTooLargeError) {
|
|
319
|
-
failOversizedResponse(error);
|
|
320
|
-
return response;
|
|
321
|
-
}
|
|
322
|
-
throw error;
|
|
312
|
+
finally {
|
|
313
|
+
reader.releaseLock();
|
|
323
314
|
}
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
315
|
+
})());
|
|
316
|
+
fakeReq.url = url.pathname + url.search;
|
|
317
|
+
fakeReq.method = req.method;
|
|
318
|
+
fakeReq.headers = {};
|
|
319
|
+
req.headers.forEach((value, name) => {
|
|
320
|
+
fakeReq.headers[name] = value;
|
|
321
|
+
});
|
|
322
|
+
fakeReq.on("error", () => resolve(new Response("Plugin request failed", { status: 500 })));
|
|
323
|
+
// Response collector shim
|
|
324
|
+
let statusCode = 200;
|
|
325
|
+
const resHeaders = {};
|
|
326
|
+
const chunks = [];
|
|
327
|
+
const fakeRes = Object.create(null);
|
|
328
|
+
fakeRes.writeHead = ((code, h) => {
|
|
329
|
+
statusCode = code;
|
|
330
|
+
if (h)
|
|
331
|
+
Object.assign(resHeaders, h);
|
|
332
|
+
return fakeRes;
|
|
333
|
+
});
|
|
334
|
+
fakeRes.end = ((data) => {
|
|
335
|
+
if (data)
|
|
336
|
+
chunks.push(typeof data === "string" ? Buffer.from(data) : data);
|
|
337
|
+
const body = Buffer.concat(chunks);
|
|
338
|
+
resolve(new Response(body.length > 0 ? body : null, {
|
|
339
|
+
status: statusCode,
|
|
340
|
+
headers: resHeaders,
|
|
329
341
|
}));
|
|
330
|
-
return response;
|
|
331
342
|
});
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
status = 500;
|
|
342
|
-
headers["Content-Type"] = "application/problem+json";
|
|
343
|
-
response.end(JSON.stringify({
|
|
344
|
-
type: "https://temps.sh/problems/plugin-handler-failed",
|
|
345
|
-
title: "Plugin Handler Failed",
|
|
346
|
-
status: 500,
|
|
347
|
-
detail: "The plugin could not complete this request.",
|
|
348
|
-
}));
|
|
349
|
-
});
|
|
350
|
-
}
|
|
351
|
-
queueMicrotask(() => {
|
|
352
|
-
if (body.length > 0)
|
|
353
|
-
for (const listener of dataListeners)
|
|
354
|
-
listener(body);
|
|
355
|
-
for (const listener of endListeners)
|
|
356
|
-
listener();
|
|
343
|
+
fakeRes.write = ((data) => {
|
|
344
|
+
chunks.push(typeof data === "string" ? Buffer.from(data) : data);
|
|
345
|
+
return true;
|
|
346
|
+
});
|
|
347
|
+
// Catch asynchronous plugin failures as well as synchronous exceptions.
|
|
348
|
+
Promise.resolve()
|
|
349
|
+
.then(() => handler(fakeReq, fakeRes))
|
|
350
|
+
.catch(() => {
|
|
351
|
+
resolve(new Response("Plugin handler failed", { status: 500 }));
|
|
357
352
|
});
|
|
358
353
|
});
|
|
359
354
|
}
|
|
360
|
-
|
|
361
|
-
|
|
355
|
+
// ---------------------------------------------------------------------------
|
|
356
|
+
// Event delivery handler (POST /_events)
|
|
357
|
+
// ---------------------------------------------------------------------------
|
|
358
|
+
async function handleEventDelivery(req, plugin, ctx) {
|
|
362
359
|
try {
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
typeof event.event_type !== "string" ||
|
|
367
|
-
typeof event.timestamp !== "string" ||
|
|
368
|
-
typeof event.data !== "object" ||
|
|
369
|
-
event.data === null) {
|
|
370
|
-
throw new Error("event is missing required fields");
|
|
360
|
+
const event = (await req.json());
|
|
361
|
+
if (ctx) {
|
|
362
|
+
plugin.onEvent?.(ctx, event);
|
|
371
363
|
}
|
|
364
|
+
return Response.json({ ok: true });
|
|
372
365
|
}
|
|
373
|
-
catch (
|
|
374
|
-
if (error instanceof RequestBodyTooLargeError)
|
|
375
|
-
return payloadTooLarge(error);
|
|
366
|
+
catch (err) {
|
|
376
367
|
return Response.json({
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
status: 400,
|
|
380
|
-
detail: "The event payload is not valid.",
|
|
368
|
+
error: "Invalid event payload",
|
|
369
|
+
detail: err instanceof Error ? err.message : String(err),
|
|
381
370
|
}, { status: 400 });
|
|
382
371
|
}
|
|
383
|
-
try {
|
|
384
|
-
await plugin.onEvent?.(context, event);
|
|
385
|
-
return new Response(null, { status: 200 });
|
|
386
|
-
}
|
|
387
|
-
catch (error) {
|
|
388
|
-
log("error", "Plugin event handler failed", {
|
|
389
|
-
plugin: context.pluginName,
|
|
390
|
-
event_type: event.event_type,
|
|
391
|
-
reason: errorMessage(error),
|
|
392
|
-
});
|
|
393
|
-
return Response.json({
|
|
394
|
-
type: "https://temps.sh/problems/plugin-event-handler-failed",
|
|
395
|
-
title: "Plugin Event Handler Failed",
|
|
396
|
-
status: 500,
|
|
397
|
-
detail: "The plugin could not process this event.",
|
|
398
|
-
}, { status: 500 });
|
|
399
|
-
}
|
|
400
372
|
}
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
373
|
+
// ---------------------------------------------------------------------------
|
|
374
|
+
// CLI argument parsing
|
|
375
|
+
// ---------------------------------------------------------------------------
|
|
376
|
+
function parseArgs(argv) {
|
|
377
|
+
const args = {};
|
|
378
|
+
for (let i = 0; i < argv.length; i++) {
|
|
379
|
+
const arg = argv[i];
|
|
380
|
+
const next = argv[i + 1];
|
|
381
|
+
switch (arg) {
|
|
382
|
+
case "--socket-path":
|
|
383
|
+
args.socketPath = next;
|
|
384
|
+
i++;
|
|
385
|
+
break;
|
|
386
|
+
case "--database-url":
|
|
387
|
+
case "--auth-secret":
|
|
388
|
+
throw new ArgsError("Privileged launch values must arrive over the protocol 2 stdin handshake; update Temps");
|
|
389
|
+
case "--data-dir":
|
|
390
|
+
args.dataDir = next;
|
|
391
|
+
i++;
|
|
392
|
+
break;
|
|
408
393
|
}
|
|
409
394
|
}
|
|
410
|
-
if (!
|
|
411
|
-
|
|
412
|
-
const reader = request.body.getReader();
|
|
413
|
-
const chunks = [];
|
|
414
|
-
let totalBytes = 0;
|
|
415
|
-
while (true) {
|
|
416
|
-
const { done, value } = await reader.read();
|
|
417
|
-
if (done)
|
|
418
|
-
break;
|
|
419
|
-
totalBytes += value.byteLength;
|
|
420
|
-
if (totalBytes > maximumBytes) {
|
|
421
|
-
await reader.cancel("plugin request body limit exceeded");
|
|
422
|
-
throw new RequestBodyTooLargeError(totalBytes, maximumBytes);
|
|
423
|
-
}
|
|
424
|
-
chunks.push(Buffer.from(value));
|
|
425
|
-
}
|
|
426
|
-
return Buffer.concat(chunks, totalBytes);
|
|
427
|
-
}
|
|
428
|
-
/** @internal Bounded response collector used by the Node-compatible bridge. */
|
|
429
|
-
export class ResponseBodyAccumulator {
|
|
430
|
-
#maximumBytes;
|
|
431
|
-
#chunks = [];
|
|
432
|
-
#totalBytes = 0;
|
|
433
|
-
constructor(maximumBytes = MAX_PLUGIN_RESPONSE_BODY_BYTES) {
|
|
434
|
-
this.#maximumBytes = maximumBytes;
|
|
435
|
-
}
|
|
436
|
-
append(value) {
|
|
437
|
-
const chunk = typeof value === "string" ? Buffer.from(value) : value;
|
|
438
|
-
const nextTotal = this.#totalBytes + chunk.byteLength;
|
|
439
|
-
if (nextTotal > this.#maximumBytes) {
|
|
440
|
-
throw new ResponseBodyTooLargeError(nextTotal, this.#maximumBytes);
|
|
441
|
-
}
|
|
442
|
-
this.#chunks.push(chunk);
|
|
443
|
-
this.#totalBytes = nextTotal;
|
|
444
|
-
}
|
|
445
|
-
toBuffer() {
|
|
446
|
-
return Buffer.concat(this.#chunks, this.#totalBytes);
|
|
447
|
-
}
|
|
448
|
-
}
|
|
449
|
-
function authenticationRequired() {
|
|
450
|
-
return Response.json({
|
|
451
|
-
type: "https://temps.sh/problems/plugin-authentication-required",
|
|
452
|
-
title: "Authentication Required",
|
|
453
|
-
status: 401,
|
|
454
|
-
detail: "This plugin route requires a request asserted by Temps.",
|
|
455
|
-
}, { status: 401, headers: { "Content-Type": "application/problem+json" } });
|
|
456
|
-
}
|
|
457
|
-
function payloadTooLarge(error) {
|
|
458
|
-
return Response.json({
|
|
459
|
-
type: "https://temps.sh/problems/plugin-request-body-too-large",
|
|
460
|
-
title: "Plugin Request Body Too Large",
|
|
461
|
-
status: 413,
|
|
462
|
-
detail: error.message,
|
|
463
|
-
maximum_bytes: error.maximumBytes,
|
|
464
|
-
}, { status: 413, headers: { "Content-Type": "application/problem+json" } });
|
|
465
|
-
}
|
|
466
|
-
function responseTooLarge(error) {
|
|
467
|
-
return Response.json({
|
|
468
|
-
type: "https://temps.sh/problems/plugin-response-body-too-large",
|
|
469
|
-
title: "Plugin Response Body Too Large",
|
|
470
|
-
status: 502,
|
|
471
|
-
detail: "The plugin produced a response larger than the runtime limit.",
|
|
472
|
-
maximum_bytes: error.maximumBytes,
|
|
473
|
-
}, { status: 502, headers: { "Content-Type": "application/problem+json" } });
|
|
474
|
-
}
|
|
475
|
-
function validateManifest(name, healthPath) {
|
|
476
|
-
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
|
|
477
|
-
throw new InitializationError(name, "Plugin name must be lowercase kebab-case");
|
|
478
|
-
}
|
|
479
|
-
if (!healthPath.startsWith("/") || healthPath.includes("..")) {
|
|
480
|
-
throw new InitializationError(name, `Invalid health path: ${healthPath}`);
|
|
481
|
-
}
|
|
482
|
-
}
|
|
483
|
-
function withTimeout(promise, milliseconds, error) {
|
|
484
|
-
return new Promise((resolve, reject) => {
|
|
485
|
-
const timer = setTimeout(() => reject(error), milliseconds);
|
|
486
|
-
promise.then((value) => {
|
|
487
|
-
clearTimeout(timer);
|
|
488
|
-
resolve(value);
|
|
489
|
-
}, (reason) => {
|
|
490
|
-
clearTimeout(timer);
|
|
491
|
-
reject(reason);
|
|
492
|
-
});
|
|
493
|
-
});
|
|
494
|
-
}
|
|
495
|
-
function removeSocket(path) {
|
|
496
|
-
if (!existsSync(path))
|
|
497
|
-
return;
|
|
498
|
-
try {
|
|
499
|
-
unlinkSync(path);
|
|
395
|
+
if (!args.socketPath) {
|
|
396
|
+
throw new ArgsError("--socket-path is required");
|
|
500
397
|
}
|
|
501
|
-
|
|
502
|
-
throw new
|
|
398
|
+
if (!args.dataDir) {
|
|
399
|
+
throw new ArgsError("--data-dir is required");
|
|
503
400
|
}
|
|
504
|
-
}
|
|
505
|
-
function log(level, message, fields) {
|
|
506
|
-
process.stderr.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level, message, ...fields })}\n`);
|
|
507
|
-
}
|
|
508
|
-
function errorMessage(error) {
|
|
509
|
-
return error instanceof Error ? error.message : String(error);
|
|
401
|
+
return { socketPath: args.socketPath, dataDir: args.dataDir };
|
|
510
402
|
}
|
|
511
403
|
//# sourceMappingURL=runtime.js.map
|