Update Site source
This commit is contained in:
commit
9a4ce930c7
126 files changed
+25723
No files matched your search
@@ -0,0 +1,198 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { access, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import getRawBody from "raw-body";
|
||||
|
||||
const moduleId = "virtual:sites-connector-preview";
|
||||
const resolvedId = `\0${moduleId}`;
|
||||
const endpoint = "/__sites_connector_preview/invoke";
|
||||
const contextEndpoint = "/__sites_connector_preview/context";
|
||||
const unavailable = {
|
||||
status: "binding_unavailable",
|
||||
message:
|
||||
"Connected apps need an active agent preview session in this preview.",
|
||||
};
|
||||
const uncertain = {
|
||||
status: "upstream_error",
|
||||
message:
|
||||
"The app did not return a confirmed result. The action may have completed; check before trying again.",
|
||||
};
|
||||
|
||||
// A development-only adapter. The shared project directory connects the preview
|
||||
// process to its owning agent even when they use different network namespaces.
|
||||
export function connectorPreview() {
|
||||
const bridgeToken = randomUUID();
|
||||
let root;
|
||||
let server;
|
||||
async function readSession() {
|
||||
const session = JSON.parse(
|
||||
await readFile(path.join(root, "session.json"), "utf8"),
|
||||
);
|
||||
if (
|
||||
!/^[0-9a-f-]{36}$/.test(session.id) ||
|
||||
(session.expiresAt !== null && !(session.expiresAt > Date.now()))
|
||||
)
|
||||
throw new Error("Session ended");
|
||||
if (
|
||||
!Number.isInteger(session.timeoutMs) ||
|
||||
session.timeoutMs <= 0 ||
|
||||
session.timeoutMs > 2 ** 31 - 1
|
||||
)
|
||||
throw new Error("Invalid session deadline");
|
||||
return session;
|
||||
}
|
||||
return {
|
||||
name: "sites-connector-preview",
|
||||
apply: "serve",
|
||||
config(config) {
|
||||
return {
|
||||
server: {
|
||||
host: config.server?.host ?? "127.0.0.1",
|
||||
strictPort: true,
|
||||
fs: {
|
||||
deny: [
|
||||
".env",
|
||||
".env.*",
|
||||
"*.{crt,pem}",
|
||||
"**/.git/**",
|
||||
"**/.sites-runtime/**",
|
||||
],
|
||||
},
|
||||
watch: { ignored: ["**/.sites-runtime/**"] },
|
||||
},
|
||||
};
|
||||
},
|
||||
configResolved(config) {
|
||||
root = path.join(config.root, ".sites-runtime", "connector-preview");
|
||||
},
|
||||
resolveId(id) {
|
||||
if (id === moduleId) return resolvedId;
|
||||
},
|
||||
load(id, options) {
|
||||
if (id !== resolvedId) return;
|
||||
if (
|
||||
this.environment?.name === "client" ||
|
||||
(!this.environment && !options?.ssr)
|
||||
) {
|
||||
throw new Error(
|
||||
"Connected apps are only available in Site server routes.",
|
||||
);
|
||||
}
|
||||
// Auxiliary Workers load before Vite starts listening. strictPort keeps
|
||||
// this configured address stable when the server opens its socket.
|
||||
const url = `http://127.0.0.1:${server.config.server.port}${endpoint}`;
|
||||
const contextUrl = `http://127.0.0.1:${server.config.server.port}${contextEndpoint}`;
|
||||
return `export default { async getContext() {
|
||||
try {
|
||||
const response = await fetch(${JSON.stringify(contextUrl)}, {
|
||||
headers: { "X-Sites-Preview": ${JSON.stringify(bridgeToken)} }
|
||||
});
|
||||
return response.json();
|
||||
} catch { return { status: "upstream_error" }; }
|
||||
}, async invoke(connectorId, actionName, args) {
|
||||
const response = await fetch(${JSON.stringify(url)}, {
|
||||
method: "POST", headers: { "Content-Type": "application/json", "X-Sites-Preview": ${JSON.stringify(bridgeToken)} },
|
||||
body: JSON.stringify({connectorId, actionName, arguments: args})
|
||||
});
|
||||
return response.json();
|
||||
} };`;
|
||||
},
|
||||
configureServer(vite) {
|
||||
server = vite;
|
||||
vite.middlewares.use(contextEndpoint, async (req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
if (
|
||||
req.method !== "GET" ||
|
||||
req.headers["x-sites-preview"] !== bridgeToken
|
||||
) {
|
||||
res.statusCode = 403;
|
||||
res.end(JSON.stringify(unavailable));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const session = await readSession();
|
||||
// Preview grants do not establish hosted catalog visibility.
|
||||
if (
|
||||
!Array.isArray(session.connectorIds) ||
|
||||
!session.connectorIds.every((id) => typeof id === "string")
|
||||
)
|
||||
throw new Error("Missing selected connectors");
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
status: "success",
|
||||
connectors: session.connectorIds.map((connectorId) => ({
|
||||
connectorId,
|
||||
policy: "enabled",
|
||||
tools: null,
|
||||
})),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
res.end(JSON.stringify({ status: "binding_unavailable" }));
|
||||
}
|
||||
});
|
||||
vite.middlewares.use(endpoint, async (req, res) => {
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
if (
|
||||
req.method !== "POST" ||
|
||||
req.headers["x-sites-preview"] !== bridgeToken
|
||||
) {
|
||||
res.statusCode = 403;
|
||||
res.end(JSON.stringify(unavailable));
|
||||
return;
|
||||
}
|
||||
let requestPath;
|
||||
let responsePath;
|
||||
let submitted = false;
|
||||
try {
|
||||
const session = await readSession();
|
||||
const raw = await getRawBody(req, { limit: 65536 });
|
||||
const call = JSON.parse(
|
||||
new TextDecoder("utf-8", { fatal: true }).decode(raw),
|
||||
);
|
||||
const body = JSON.stringify(call);
|
||||
const directory = path.join(root, session.id);
|
||||
const id = randomUUID();
|
||||
requestPath = path.join(directory, `${id}.request`);
|
||||
responsePath = path.join(directory, `${id}.response`);
|
||||
await writeFile(`${requestPath}.tmp`, body, { mode: 0o600 });
|
||||
await rename(`${requestPath}.tmp`, requestPath);
|
||||
submitted = true;
|
||||
// Read the owner's deadline per call, so a restarted session can use
|
||||
// longer provider waits without rebuilding or restarting the Site.
|
||||
const deadline = Math.min(
|
||||
session.expiresAt ?? Infinity,
|
||||
Date.now() + session.timeoutMs + 2000,
|
||||
);
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
res.end(await readFile(responsePath));
|
||||
return;
|
||||
} catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
// Session shutdown removes the mailbox. Stop promptly even when
|
||||
// the configured provider deadline is several minutes away.
|
||||
await access(directory);
|
||||
}
|
||||
await delay(50);
|
||||
}
|
||||
res.end(JSON.stringify(uncertain));
|
||||
} catch {
|
||||
// raw-body pauses oversized requests; drain the remainder so the HTTP
|
||||
// connection can finish without retaining an unread request stream.
|
||||
req.resume();
|
||||
res.end(JSON.stringify(submitted ? uncertain : unavailable));
|
||||
} finally {
|
||||
await Promise.all(
|
||||
[requestPath, requestPath && `${requestPath}.tmp`, responsePath]
|
||||
.filter(Boolean)
|
||||
.map((file) => rm(file, { force: true })),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { WorkerEntrypoint } from "cloudflare:workers";
|
||||
import binding from "virtual:sites-connector-preview";
|
||||
|
||||
// Local-only RPC target. The Site entrypoint scopes it to each request; the Node
|
||||
// adapter relays each call to the owning agent.
|
||||
export class ConnectorPreview extends WorkerEntrypoint {
|
||||
async getContext() {
|
||||
return binding.getContext?.() ?? { status: "binding_unavailable" };
|
||||
}
|
||||
|
||||
async invoke(connectorId, actionName, args) {
|
||||
return binding.invoke(connectorId, actionName, args);
|
||||
}
|
||||
}
|
||||
export default { fetch() { return new Response("Not found", { status: 404 }); } };
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 OpenAI
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,230 @@
|
||||
// Vendored from @openai/sites-vite-plugin 0.2.0 (openai/sites#9).
|
||||
// See sites-vite-plugin.LICENSE for the upstream MIT license.
|
||||
import { access, cp, mkdir, rm } from "node:fs/promises";
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { resolve } from "node:path";
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
const localUserId = "local_seedy";
|
||||
const localEmail = "seedy@sites.test";
|
||||
const localFullName = "Seedy";
|
||||
const localCookieName = "__sites_local_auth";
|
||||
const localHosts = new Set(["localhost", "127.0.0.1", "::1"]);
|
||||
const localAddresses = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
||||
const authPaths = new Set([
|
||||
"/signin-with-chatgpt",
|
||||
"/signout-with-chatgpt",
|
||||
"/callback",
|
||||
]);
|
||||
|
||||
async function exists(path: string): Promise<boolean> {
|
||||
try {
|
||||
await access(path);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function sites({ mockAuth = true } = {}): Plugin {
|
||||
let root = process.cwd();
|
||||
let command: "build" | "serve" = "build";
|
||||
|
||||
return {
|
||||
name: "sites",
|
||||
configResolved(config) {
|
||||
root = config.root;
|
||||
command = config.command;
|
||||
},
|
||||
configureServer(server) {
|
||||
if (!mockAuth) return;
|
||||
const secure = Boolean(server.config.server.https);
|
||||
|
||||
server.config.logger.info(`Sites local sign-in: ${localEmail}`);
|
||||
server.middlewares.use((request, response, next) => {
|
||||
for (const name of Object.keys(request.headers)) {
|
||||
if (name.startsWith("oai-authenticated-user-")) {
|
||||
removeHeader(request, name);
|
||||
}
|
||||
}
|
||||
|
||||
let authority: URL;
|
||||
let url: URL;
|
||||
try {
|
||||
authority = new URL(
|
||||
`${secure ? "https" : "http"}://${request.headers.host}`,
|
||||
);
|
||||
url = new URL(request.url ?? "/", authority);
|
||||
} catch {
|
||||
if (authPaths.has((request.url ?? "/").split("?")[0])) {
|
||||
respond(response, 403);
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const hostname = authority.hostname
|
||||
.replace(/^\[|\]$/g, "")
|
||||
.toLowerCase();
|
||||
if (
|
||||
!localHosts.has(hostname) ||
|
||||
!localAddresses.has(request.socket.remoteAddress ?? "") ||
|
||||
url.origin !== authority.origin
|
||||
) {
|
||||
if (authPaths.has(url.pathname)) respond(response, 403);
|
||||
else next();
|
||||
return;
|
||||
}
|
||||
|
||||
const cookies = (request.headers.cookie ?? "")
|
||||
.split(";")
|
||||
.map((cookie) => cookie.trim())
|
||||
.filter(Boolean);
|
||||
const signInCookies = cookies
|
||||
.filter((cookie) => cookie.startsWith(`${localCookieName}=`))
|
||||
.map((cookie) => cookie.slice(localCookieName.length + 1));
|
||||
const applicationCookies = cookies.filter(
|
||||
(cookie) => !cookie.startsWith(`${localCookieName}=`),
|
||||
);
|
||||
if (applicationCookies.length !== cookies.length) {
|
||||
removeHeader(request, "cookie");
|
||||
if (applicationCookies.length) {
|
||||
setHeader(request, "cookie", applicationCookies.join("; "));
|
||||
}
|
||||
}
|
||||
|
||||
if (url.pathname === "/callback") {
|
||||
respond(response, 501);
|
||||
return;
|
||||
}
|
||||
|
||||
const signIn = url.pathname === "/signin-with-chatgpt";
|
||||
const signOut = url.pathname === "/signout-with-chatgpt";
|
||||
if (!signIn && !signOut) {
|
||||
if (signInCookies.length === 1 && signInCookies[0] === "1") {
|
||||
setHeader(request, "oai-authenticated-user-id", localUserId);
|
||||
setHeader(request, "oai-authenticated-user-email", localEmail);
|
||||
setHeader(
|
||||
request,
|
||||
"oai-authenticated-user-full-name",
|
||||
localFullName,
|
||||
);
|
||||
setHeader(
|
||||
request,
|
||||
"oai-authenticated-user-full-name-encoding",
|
||||
"percent-encoded-utf-8",
|
||||
);
|
||||
}
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
(request.headers.origin && request.headers.origin !== url.origin) ||
|
||||
request.headers["sec-fetch-site"] === "cross-site"
|
||||
) {
|
||||
respond(response, 403);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
request.headers["next-router-prefetch"] !== undefined ||
|
||||
request.headers["x-middleware-prefetch"] === "1" ||
|
||||
[request.headers.purpose, request.headers["sec-purpose"]].some(
|
||||
(value) =>
|
||||
typeof value === "string" &&
|
||||
value
|
||||
.split(/[;,]/)
|
||||
.some((part) => part.trim().toLowerCase() === "prefetch"),
|
||||
)
|
||||
) {
|
||||
respond(response, 204);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
request.method !== "GET" &&
|
||||
(!signOut || request.method !== "POST")
|
||||
) {
|
||||
response.setHeader("Allow", signIn ? "GET" : "GET, POST");
|
||||
respond(response, 405);
|
||||
return;
|
||||
}
|
||||
|
||||
response.statusCode = request.method === "POST" ? 303 : 302;
|
||||
response.setHeader("Cache-Control", "private, no-store");
|
||||
response.setHeader(
|
||||
"Location",
|
||||
safeReturn(url.searchParams.get("return_to")),
|
||||
);
|
||||
response.setHeader(
|
||||
"Set-Cookie",
|
||||
`${localCookieName}=${signIn ? "1" : ""}; Path=/; ${
|
||||
signOut ? "Max-Age=0; " : ""
|
||||
}HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`,
|
||||
);
|
||||
response.end();
|
||||
});
|
||||
},
|
||||
async closeBundle() {
|
||||
if (command !== "build") return;
|
||||
|
||||
const outputDirectory = resolve(root, "dist", ".openai");
|
||||
const hostingConfig = resolve(root, ".openai", "hosting.json");
|
||||
const drizzleSource = resolve(root, "drizzle");
|
||||
|
||||
await rm(outputDirectory, { recursive: true, force: true });
|
||||
await mkdir(outputDirectory, { recursive: true });
|
||||
|
||||
await cp(hostingConfig, resolve(outputDirectory, "hosting.json"));
|
||||
if (await exists(drizzleSource)) {
|
||||
await cp(drizzleSource, resolve(outputDirectory, "drizzle"), {
|
||||
recursive: true,
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function removeHeader(request: IncomingMessage, name: string): void {
|
||||
delete request.headers[name];
|
||||
for (let index = request.rawHeaders.length - 2; index >= 0; index -= 2) {
|
||||
if (request.rawHeaders[index]?.toLowerCase() === name) {
|
||||
request.rawHeaders.splice(index, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setHeader(
|
||||
request: IncomingMessage,
|
||||
name: string,
|
||||
value: string,
|
||||
): void {
|
||||
removeHeader(request, name);
|
||||
request.headers[name] = value;
|
||||
request.rawHeaders.push(name, value);
|
||||
}
|
||||
|
||||
function respond(response: ServerResponse, status: number): void {
|
||||
response.statusCode = status;
|
||||
response.setHeader("Cache-Control", "private, no-store");
|
||||
response.end();
|
||||
}
|
||||
|
||||
function safeReturn(value: string | null): string {
|
||||
if (!value?.startsWith("/") || value.startsWith("//")) return "/";
|
||||
|
||||
try {
|
||||
const url = new URL(value, "http://localhost");
|
||||
if (url.origin !== "http://localhost" || authPaths.has(url.pathname)) {
|
||||
return "/";
|
||||
}
|
||||
return `${url.pathname}${url.search}${url.hash}`;
|
||||
} catch {
|
||||
return "/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import handler from "vinext/server/fetch-handler";
|
||||
import { runWithConnectorBinding } from "../lib/connector-context";
|
||||
import type { ConnectorBinding } from "../lib/connector-contract.mjs";
|
||||
|
||||
export default {
|
||||
fetch(request: Request, env: Cloudflare.Env, ctx: ExecutionContext<{ CONNECTORS?: ConnectorBinding }>) {
|
||||
let binding = ctx.props?.CONNECTORS;
|
||||
// Local preview emulates the same request-scoped capability. This branch and
|
||||
// the auxiliary service binding are absent from production builds.
|
||||
if (import.meta.env.DEV && !binding && env.CONNECTORS) {
|
||||
const preview = env.CONNECTORS;
|
||||
const expiresAt = Date.now() + 60_000;
|
||||
binding = {
|
||||
async getContext() {
|
||||
if (Date.now() >= expiresAt) return { status: "request_context_expired" };
|
||||
return preview.getContext?.() ?? { status: "binding_unavailable" };
|
||||
},
|
||||
async invoke(connectorId, actionName, args) {
|
||||
if (Date.now() >= expiresAt) {
|
||||
return { status: "request_context_expired", message: "This request has expired. Please try again." };
|
||||
}
|
||||
return preview.invoke(connectorId, actionName, args);
|
||||
},
|
||||
};
|
||||
}
|
||||
return runWithConnectorBinding(binding, () => handler.fetch(request, env, ctx));
|
||||
},
|
||||
};
|
||||
Reference in new issue
Block a user