@howaboua/pi-chatgpt-sites 0.0.0-stage → 0.0.2
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 +11 -0
- package/LICENSE +22 -0
- package/README.md +20 -2
- package/changelog.ts +337 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +113 -0
- package/dist/src/auth.d.ts +5 -0
- package/dist/src/auth.js +27 -0
- package/dist/src/client.d.ts +36 -0
- package/dist/src/client.js +264 -0
- package/dist/src/docs/access.md +9 -0
- package/dist/src/docs/analytics.md +17 -0
- package/dist/src/docs/building.md +11 -0
- package/dist/src/docs/database.md +5 -0
- package/dist/src/docs/deployment.md +31 -0
- package/dist/src/docs/diagnostics.md +5 -0
- package/dist/src/docs/domains.md +19 -0
- package/dist/src/docs/environment.md +31 -0
- package/dist/src/docs/index.md +20 -0
- package/dist/src/docs/mcp.md +13 -0
- package/dist/src/docs/schedules.md +13 -0
- package/dist/src/docs/site.md +11 -0
- package/dist/src/docs/version.md +11 -0
- package/dist/src/docs/workflow.md +15 -0
- package/dist/src/facade.d.ts +7 -0
- package/dist/src/facade.js +219 -0
- package/dist/src/git-askpass.d.ts +2 -0
- package/dist/src/git-askpass.js +9 -0
- package/dist/src/local-project.d.ts +19 -0
- package/dist/src/local-project.js +180 -0
- package/dist/src/operations.d.ts +19 -0
- package/dist/src/operations.js +92 -0
- package/dist/src/redact.d.ts +2 -0
- package/dist/src/redact.js +67 -0
- package/package.json +60 -5
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { acquireHostingLock, inspectCleanCommit, persistProjectId, projectContext, pushCommit, readHosting, resolveProjectId, } from "./local-project.js";
|
|
5
|
+
import { facadeError, operationForTopic, resolveOperation, } from "./operations.js";
|
|
6
|
+
import { redact } from "./redact.js";
|
|
7
|
+
const docsDir = join(dirname(fileURLToPath(import.meta.url)), "docs");
|
|
8
|
+
export async function call(request, client, cwd, signal) {
|
|
9
|
+
if (!isRecord(request)) {
|
|
10
|
+
throw facadeError("invalid_request", "sites expects one JSON object", "index");
|
|
11
|
+
}
|
|
12
|
+
const operation = resolveOperation(request["resource"], request["action"]);
|
|
13
|
+
const params = request["params"] === undefined ? {} : request["params"];
|
|
14
|
+
if (!isRecord(params)) {
|
|
15
|
+
throw facadeError("invalid_params", "params must be an object", operation.topic);
|
|
16
|
+
}
|
|
17
|
+
rejectKeys(params, ["publish_on_push"], "publish_on_push is not supported; use explicit save/deploy");
|
|
18
|
+
const prepared = await prepare(operation, { ...params }, client, cwd, signal);
|
|
19
|
+
try {
|
|
20
|
+
validateAgainstSchema(prepared.args, await client.schema(prepared.tool), prepared.allowedExtra);
|
|
21
|
+
const raw = await client.call(prepared.tool, prepared.args);
|
|
22
|
+
const completed = await prepared.after(raw);
|
|
23
|
+
return {
|
|
24
|
+
ok: true,
|
|
25
|
+
operation: operation.key,
|
|
26
|
+
result: redact(selectResult(operation, completed)),
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
await prepared.cleanup();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
async function prepare(operation, params, client, cwd, signal) {
|
|
34
|
+
const project = await projectContext(params["project_dir"], cwd);
|
|
35
|
+
delete params["project_dir"];
|
|
36
|
+
let tool = operation.tool;
|
|
37
|
+
let after = async (value) => value;
|
|
38
|
+
let cleanup = async () => { };
|
|
39
|
+
const allowedExtra = [];
|
|
40
|
+
if (operation.local === "create") {
|
|
41
|
+
cleanup = await acquireHostingLock(project);
|
|
42
|
+
try {
|
|
43
|
+
const manifest = await readHosting(project);
|
|
44
|
+
if (manifest["project_id"]) {
|
|
45
|
+
throw facadeError("site_already_linked", ".openai/hosting.json already has project_id; reuse that site", "site");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
await cleanup();
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
after = async (value) => {
|
|
53
|
+
const projectId = recordResult(value)?.["id"];
|
|
54
|
+
if (typeof projectId !== "string" || !projectId) {
|
|
55
|
+
throw new Error("Sites created a site but returned no project ID");
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
await persistProjectId(project, projectId);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
throw facadeError("manifest_persist_failed", `Site was created as ${projectId}, but ${project.manifestPath} could not be updated: ${error instanceof Error ? error.message : String(error)}`, "site", { project_id: projectId, manifest_path: project.manifestPath });
|
|
62
|
+
}
|
|
63
|
+
return value;
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
else if (operation.local === "save") {
|
|
67
|
+
rejectKeys(params, ["commit_sha", "archive"], "Source save derives commit_sha and does not accept archives");
|
|
68
|
+
const manifest = await readHosting(project);
|
|
69
|
+
if (typeof manifest["project_id"] !== "string" || !manifest["project_id"]) {
|
|
70
|
+
throw facadeError("unbound_repository", "Source save requires project_id in the repository's .openai/hosting.json", "version");
|
|
71
|
+
}
|
|
72
|
+
params["project_id"] = await resolveProjectId(params, project);
|
|
73
|
+
const { root, commitSha } = await inspectCleanCommit(project, signal);
|
|
74
|
+
params["commit_sha"] = commitSha;
|
|
75
|
+
// Reject invalid inputs before a source push. Both save routes share this owner.
|
|
76
|
+
validateAgainstSchema(params, await client.schema(tool));
|
|
77
|
+
const credentialResponse = await client.call("create_source_repository_write_credential", {
|
|
78
|
+
project_id: params["project_id"],
|
|
79
|
+
});
|
|
80
|
+
const credential = unwrapResult(credentialResponse);
|
|
81
|
+
if (recordResult(credential)?.["publish_on_push_accepted"] === true) {
|
|
82
|
+
throw facadeError("automatic_publication_unsupported", "Sites returned an auto-publishing credential; source was not pushed", "version");
|
|
83
|
+
}
|
|
84
|
+
await pushCommit({ root, commitSha, credential, signal });
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
const schema = await client.schema(tool);
|
|
88
|
+
if (schema?.properties?.["project_id"] && !params["project_id"]) {
|
|
89
|
+
params["project_id"] = await resolveProjectId(params, project);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (operation.local === "deploy") {
|
|
93
|
+
const visibility = params["visibility"];
|
|
94
|
+
if (visibility !== "private" && visibility !== "shared") {
|
|
95
|
+
throw facadeError("visibility_required", 'deployment.deploy requires params.visibility as "private" or "shared"', "deployment");
|
|
96
|
+
}
|
|
97
|
+
tool =
|
|
98
|
+
visibility === "private"
|
|
99
|
+
? "deploy_private_site_version"
|
|
100
|
+
: "deploy_site_version";
|
|
101
|
+
delete params["visibility"];
|
|
102
|
+
}
|
|
103
|
+
if (operation.tool === "list_sites" && params["limit"] === undefined)
|
|
104
|
+
params["limit"] = 20;
|
|
105
|
+
if (operation.tool === "list_site_versions" && params["limit"] === undefined)
|
|
106
|
+
params["limit"] = 20;
|
|
107
|
+
return { tool, args: params, after, cleanup, allowedExtra };
|
|
108
|
+
}
|
|
109
|
+
function rejectKeys(params, keys, message) {
|
|
110
|
+
if (keys.some((key) => key in params))
|
|
111
|
+
throw new Error(message);
|
|
112
|
+
}
|
|
113
|
+
function validateAgainstSchema(params, schema, allowedExtra = []) {
|
|
114
|
+
const properties = schema?.properties ?? {};
|
|
115
|
+
const unknown = Object.keys(params).filter((key) => !Object.hasOwn(properties, key) && !allowedExtra.includes(key));
|
|
116
|
+
if (unknown.length > 0) {
|
|
117
|
+
throw new Error(`Unknown parameter${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
|
|
118
|
+
}
|
|
119
|
+
const missing = (schema?.required ?? []).filter((key) => params[key] === undefined);
|
|
120
|
+
if (missing.length > 0) {
|
|
121
|
+
throw new Error(`Missing required parameter${missing.length === 1 ? "" : "s"}: ${missing.join(", ")}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function selectResult(operation, value) {
|
|
125
|
+
if (operation.select !== "access")
|
|
126
|
+
return value;
|
|
127
|
+
const site = recordResult(value);
|
|
128
|
+
return {
|
|
129
|
+
result: {
|
|
130
|
+
id: site?.["id"],
|
|
131
|
+
title: site?.["title"],
|
|
132
|
+
current_live_url: site?.["current_live_url"],
|
|
133
|
+
access_mode: site?.["access_mode"],
|
|
134
|
+
access_policy: site?.["access_policy"],
|
|
135
|
+
available_access_modes: site?.["available_access_modes"],
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function unwrapResult(value) {
|
|
140
|
+
return isRecord(value) ? (value["result"] ?? value) : value;
|
|
141
|
+
}
|
|
142
|
+
function recordResult(value) {
|
|
143
|
+
const result = unwrapResult(value);
|
|
144
|
+
return isRecord(result) ? result : undefined;
|
|
145
|
+
}
|
|
146
|
+
function isRecord(value) {
|
|
147
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
148
|
+
}
|
|
149
|
+
export async function documentation(input = "index", client) {
|
|
150
|
+
const requested = input.trim() || "index";
|
|
151
|
+
const topic = requested.replace(/^['"]|['"]$/g, "");
|
|
152
|
+
const operation = operationForTopic(topic);
|
|
153
|
+
if (operation) {
|
|
154
|
+
const guide = await readTopic(operation.topic);
|
|
155
|
+
const schemas = operation.local === "deploy"
|
|
156
|
+
? {
|
|
157
|
+
private: documentationSchema(await client.schema("deploy_private_site_version"), operation),
|
|
158
|
+
shared: documentationSchema(await client.schema("deploy_site_version"), operation),
|
|
159
|
+
}
|
|
160
|
+
: documentationSchema(await client.schema(operation.tool), operation);
|
|
161
|
+
return boundedDocumentation(`${guide}\n\n## Current params schema for ${operation.key}\n\n` +
|
|
162
|
+
`${operationSchemaNote(operation)}\n\n\`\`\`json\n${JSON.stringify(schemas, null, 2)}\n\`\`\`\n`);
|
|
163
|
+
}
|
|
164
|
+
const known = new Set([
|
|
165
|
+
"index",
|
|
166
|
+
"workflow",
|
|
167
|
+
"site",
|
|
168
|
+
"version",
|
|
169
|
+
"deployment",
|
|
170
|
+
"access",
|
|
171
|
+
"environment",
|
|
172
|
+
"domains",
|
|
173
|
+
"analytics",
|
|
174
|
+
"mcp",
|
|
175
|
+
"building",
|
|
176
|
+
"diagnostics",
|
|
177
|
+
"database",
|
|
178
|
+
"schedules",
|
|
179
|
+
]);
|
|
180
|
+
return readTopic(known.has(topic) ? topic : "index");
|
|
181
|
+
}
|
|
182
|
+
function operationSchemaNote(operation) {
|
|
183
|
+
if (operation.local === "save") {
|
|
184
|
+
return "The facade derives and pushes `commit_sha`; archives are unsupported. `project_dir` selects the clean bound repository.";
|
|
185
|
+
}
|
|
186
|
+
if (operation.local === "deploy") {
|
|
187
|
+
return 'The facade additionally requires `visibility: "private" | "shared"`; this facade field is stripped before the backend call.';
|
|
188
|
+
}
|
|
189
|
+
return "Pass the backend fields inside `params`. `project_id` may be omitted when `.openai/hosting.json` supplies it.";
|
|
190
|
+
}
|
|
191
|
+
function documentationSchema(schema, operation) {
|
|
192
|
+
const projected = JSON.parse(JSON.stringify(schema, (key, value) => (key === "description" || key === "title") && typeof value === "string"
|
|
193
|
+
? undefined
|
|
194
|
+
: value));
|
|
195
|
+
const blocked = [
|
|
196
|
+
"publish_on_push",
|
|
197
|
+
...(operation.local === "save" ? ["commit_sha", "archive"] : []),
|
|
198
|
+
];
|
|
199
|
+
for (const key of blocked)
|
|
200
|
+
delete projected.properties?.[key];
|
|
201
|
+
if (projected.required)
|
|
202
|
+
projected.required = projected.required.filter((key) => !blocked.includes(key));
|
|
203
|
+
return projected;
|
|
204
|
+
}
|
|
205
|
+
async function readTopic(topic) {
|
|
206
|
+
const text = await readFile(join(docsDir, `${topic}.md`), "utf8");
|
|
207
|
+
return boundedDocumentation(text);
|
|
208
|
+
}
|
|
209
|
+
function boundedDocumentation(text) {
|
|
210
|
+
const max = 16_000;
|
|
211
|
+
if (Buffer.byteLength(text) <= max)
|
|
212
|
+
return text;
|
|
213
|
+
const suffix = "\n\n[Documentation truncated; request the narrower topic.]\n";
|
|
214
|
+
const budget = max - Buffer.byteLength(suffix);
|
|
215
|
+
let prefix = Buffer.from(text).subarray(0, budget).toString("utf8");
|
|
216
|
+
while (Buffer.byteLength(prefix) > budget)
|
|
217
|
+
prefix = prefix.slice(0, -1);
|
|
218
|
+
return `${prefix}${suffix}`;
|
|
219
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const prompt = process.argv.slice(2).join(" ").toLowerCase();
|
|
3
|
+
if (prompt.includes("username")) {
|
|
4
|
+
process.stdout.write(process.env["SITES_GIT_USERNAME"] || "x-access-token");
|
|
5
|
+
}
|
|
6
|
+
else {
|
|
7
|
+
process.stdout.write(process.env["SITES_GIT_TOKEN"] || "");
|
|
8
|
+
}
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface ProjectContext {
|
|
2
|
+
root: string;
|
|
3
|
+
manifestPath: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function projectContext(projectDir: unknown, cwd?: string): Promise<ProjectContext>;
|
|
6
|
+
export declare function acquireHostingLock(context: ProjectContext): Promise<() => Promise<void>>;
|
|
7
|
+
export declare function readHosting(context: ProjectContext): Promise<Record<string, unknown>>;
|
|
8
|
+
export declare function persistProjectId(context: ProjectContext, projectId: string): Promise<void>;
|
|
9
|
+
export declare function resolveProjectId(params: Record<string, unknown>, context: ProjectContext): Promise<{}>;
|
|
10
|
+
export declare function inspectCleanCommit(context: ProjectContext, signal?: AbortSignal): Promise<{
|
|
11
|
+
root: string;
|
|
12
|
+
commitSha: string;
|
|
13
|
+
}>;
|
|
14
|
+
export declare function pushCommit({ root, commitSha, credential, signal, }: {
|
|
15
|
+
root: string;
|
|
16
|
+
commitSha: string;
|
|
17
|
+
credential: unknown;
|
|
18
|
+
signal: AbortSignal | undefined;
|
|
19
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdir, open, readFile, rename, rm, stat, writeFile, } from "node:fs/promises";
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
const runFile = promisify(execFile);
|
|
7
|
+
const askPass = join(dirname(fileURLToPath(import.meta.url)), "git-askpass.js");
|
|
8
|
+
export async function projectContext(projectDir, cwd = process.cwd()) {
|
|
9
|
+
if (projectDir && typeof projectDir !== "string")
|
|
10
|
+
throw new Error("project_dir must name a directory");
|
|
11
|
+
const requested = typeof projectDir === "string" && projectDir
|
|
12
|
+
? resolve(cwd, projectDir)
|
|
13
|
+
: cwd;
|
|
14
|
+
const requestedStat = await stat(requested);
|
|
15
|
+
if (!requestedStat.isDirectory())
|
|
16
|
+
throw new Error("project_dir must name a directory");
|
|
17
|
+
let gitRoot;
|
|
18
|
+
try {
|
|
19
|
+
gitRoot = (await git(requested, ["rev-parse", "--show-toplevel"])).trim();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// Site creation can precede Git initialization.
|
|
23
|
+
}
|
|
24
|
+
if (projectDir && gitRoot && resolve(gitRoot) !== requested) {
|
|
25
|
+
throw new Error("project_dir must be the Git repository root, not a nested directory");
|
|
26
|
+
}
|
|
27
|
+
const root = gitRoot || requested;
|
|
28
|
+
return { root, manifestPath: join(root, ".openai", "hosting.json") };
|
|
29
|
+
}
|
|
30
|
+
export async function acquireHostingLock(context) {
|
|
31
|
+
await mkdir(dirname(context.manifestPath), { recursive: true });
|
|
32
|
+
const lockPath = join(dirname(context.manifestPath), "hosting.lock");
|
|
33
|
+
let handle;
|
|
34
|
+
try {
|
|
35
|
+
handle = await open(lockPath, "wx", 0o600);
|
|
36
|
+
await handle.writeFile(`${process.pid}\n`);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
await handle?.close();
|
|
40
|
+
if (error instanceof Error && "code" in error && error.code === "EEXIST") {
|
|
41
|
+
throw new Error(`Another Sites operation holds ${lockPath}`);
|
|
42
|
+
}
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
const acquired = handle;
|
|
46
|
+
let released = false;
|
|
47
|
+
return async () => {
|
|
48
|
+
if (released)
|
|
49
|
+
return;
|
|
50
|
+
released = true;
|
|
51
|
+
await acquired.close();
|
|
52
|
+
await rm(lockPath, { force: true });
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export async function readHosting(context) {
|
|
56
|
+
try {
|
|
57
|
+
const value = JSON.parse(await readFile(context.manifestPath, "utf8"));
|
|
58
|
+
if (!isRecord(value)) {
|
|
59
|
+
throw new Error("manifest must contain a JSON object");
|
|
60
|
+
}
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
65
|
+
return {};
|
|
66
|
+
throw new Error(`${context.manifestPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export async function persistProjectId(context, projectId) {
|
|
70
|
+
const manifest = await readHosting(context);
|
|
71
|
+
if (manifest["project_id"] && manifest["project_id"] !== projectId) {
|
|
72
|
+
throw new Error(`${context.manifestPath} already contains a different project_id`);
|
|
73
|
+
}
|
|
74
|
+
manifest["project_id"] = projectId;
|
|
75
|
+
await mkdir(dirname(context.manifestPath), { recursive: true });
|
|
76
|
+
const temporary = `${context.manifestPath}.${process.pid}.tmp`;
|
|
77
|
+
await writeFile(temporary, `${JSON.stringify(manifest, null, 2)}\n`, {
|
|
78
|
+
mode: 0o600,
|
|
79
|
+
});
|
|
80
|
+
await rename(temporary, context.manifestPath);
|
|
81
|
+
}
|
|
82
|
+
export async function resolveProjectId(params, context) {
|
|
83
|
+
const manifest = await readHosting(context);
|
|
84
|
+
const supplied = params["project_id"];
|
|
85
|
+
if (supplied !== undefined && typeof supplied !== "string") {
|
|
86
|
+
throw new Error("project_id must be a string");
|
|
87
|
+
}
|
|
88
|
+
if (supplied &&
|
|
89
|
+
manifest["project_id"] &&
|
|
90
|
+
supplied !== manifest["project_id"]) {
|
|
91
|
+
throw new Error("project_id does not match .openai/hosting.json");
|
|
92
|
+
}
|
|
93
|
+
const projectId = supplied || manifest["project_id"];
|
|
94
|
+
if (!projectId) {
|
|
95
|
+
throw new Error("No project_id supplied and .openai/hosting.json has none");
|
|
96
|
+
}
|
|
97
|
+
return projectId;
|
|
98
|
+
}
|
|
99
|
+
export async function inspectCleanCommit(context, signal) {
|
|
100
|
+
const root = (await git(context.root, ["rev-parse", "--show-toplevel"], process.env, signal)).trim();
|
|
101
|
+
const status = await git(root, ["status", "--porcelain=v1", "--untracked-files=all"], process.env, signal);
|
|
102
|
+
if (status.trim())
|
|
103
|
+
throw new Error("Source save requires a clean Git worktree");
|
|
104
|
+
const manifestRelative = ".openai/hosting.json";
|
|
105
|
+
await git(root, ["ls-files", "--error-unmatch", manifestRelative], process.env, signal);
|
|
106
|
+
const commitSha = (await git(root, ["rev-parse", "HEAD"], process.env, signal)).trim();
|
|
107
|
+
if (!/^[0-9a-f]{40,64}$/i.test(commitSha))
|
|
108
|
+
throw new Error("Could not resolve the current Git commit");
|
|
109
|
+
return { root, commitSha };
|
|
110
|
+
}
|
|
111
|
+
export async function pushCommit({ root, commitSha, credential, signal, }) {
|
|
112
|
+
const values = isRecord(credential) ? credential : {};
|
|
113
|
+
const remoteUrl = values["remote_url"];
|
|
114
|
+
const branch = values["branch"];
|
|
115
|
+
const token = values["token"];
|
|
116
|
+
const authMode = String(values["auth_mode"] ?? "").toLowerCase();
|
|
117
|
+
if (typeof remoteUrl !== "string" ||
|
|
118
|
+
!remoteUrl ||
|
|
119
|
+
typeof branch !== "string" ||
|
|
120
|
+
!branch ||
|
|
121
|
+
typeof token !== "string" ||
|
|
122
|
+
!token) {
|
|
123
|
+
throw new Error("Sites returned an incomplete source repository credential");
|
|
124
|
+
}
|
|
125
|
+
const url = new URL(remoteUrl);
|
|
126
|
+
if (url.protocol !== "https:" || url.username || url.password) {
|
|
127
|
+
throw new Error("Sites source repository URL must be credential-free HTTPS");
|
|
128
|
+
}
|
|
129
|
+
await git(root, ["check-ref-format", `refs/heads/${branch}`]);
|
|
130
|
+
const env = {
|
|
131
|
+
...process.env,
|
|
132
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
133
|
+
};
|
|
134
|
+
if (authMode.includes("bearer")) {
|
|
135
|
+
env["GIT_CONFIG_COUNT"] = "1";
|
|
136
|
+
env["GIT_CONFIG_KEY_0"] = "http.extraHeader";
|
|
137
|
+
env["GIT_CONFIG_VALUE_0"] = `Authorization: Bearer ${token}`;
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
env["GIT_ASKPASS"] = askPass;
|
|
141
|
+
env["SITES_GIT_TOKEN"] = token;
|
|
142
|
+
env["SITES_GIT_USERNAME"] = "x-access-token";
|
|
143
|
+
}
|
|
144
|
+
await git(root, [
|
|
145
|
+
"-c",
|
|
146
|
+
"credential.helper=",
|
|
147
|
+
"-c",
|
|
148
|
+
"core.hooksPath=/dev/null",
|
|
149
|
+
"push",
|
|
150
|
+
"--no-verify",
|
|
151
|
+
"--porcelain",
|
|
152
|
+
remoteUrl,
|
|
153
|
+
`${commitSha}:refs/heads/${branch}`,
|
|
154
|
+
], env, signal);
|
|
155
|
+
}
|
|
156
|
+
async function git(cwd, args, env = process.env, signal) {
|
|
157
|
+
if (!isAbsolute(cwd))
|
|
158
|
+
throw new Error("Git working directory must be absolute");
|
|
159
|
+
try {
|
|
160
|
+
const result = await runFile("git", args, {
|
|
161
|
+
cwd,
|
|
162
|
+
env,
|
|
163
|
+
encoding: "utf8",
|
|
164
|
+
maxBuffer: 1024 * 1024,
|
|
165
|
+
timeout: 120_000,
|
|
166
|
+
signal,
|
|
167
|
+
});
|
|
168
|
+
return result.stdout;
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
const stderr = error instanceof Error && "stderr" in error ? error.stderr : undefined;
|
|
172
|
+
const detail = String(stderr || (error instanceof Error ? error.message : "Git command failed"))
|
|
173
|
+
.replaceAll(env["SITES_GIT_TOKEN"] || "\0", "[redacted]")
|
|
174
|
+
.trim();
|
|
175
|
+
throw new Error(detail.slice(0, 2_000));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
function isRecord(value) {
|
|
179
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
180
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
interface Operation {
|
|
2
|
+
tool: string;
|
|
3
|
+
topic: string;
|
|
4
|
+
local?: "create" | "save" | "deploy";
|
|
5
|
+
select?: "access";
|
|
6
|
+
}
|
|
7
|
+
export interface ResolvedOperation extends Operation {
|
|
8
|
+
resource: string;
|
|
9
|
+
action: string;
|
|
10
|
+
key: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function resolveOperation(resource: unknown, action: unknown): ResolvedOperation;
|
|
13
|
+
export declare function facadeError(code: string, message: string, topic: string, details?: unknown): Error & {
|
|
14
|
+
code: string;
|
|
15
|
+
topic: string;
|
|
16
|
+
details: unknown;
|
|
17
|
+
};
|
|
18
|
+
export declare function operationForTopic(topic: string): ResolvedOperation | undefined;
|
|
19
|
+
export {};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
const OPERATIONS = Object.freeze({
|
|
2
|
+
site: Object.freeze({
|
|
3
|
+
list: operation("list_sites", "site"),
|
|
4
|
+
get: operation("get_site", "site"),
|
|
5
|
+
create: operation("create_site", "site", { local: "create" }),
|
|
6
|
+
update: operation("update_site_metadata", "site"),
|
|
7
|
+
slug: operation("change_site_slug", "site"),
|
|
8
|
+
}),
|
|
9
|
+
version: Object.freeze({
|
|
10
|
+
list: operation("list_site_versions", "version"),
|
|
11
|
+
get: operation("get_site_version", "version"),
|
|
12
|
+
save: operation("save_site_version", "version", { local: "save" }),
|
|
13
|
+
publish_private: operation("save_version_and_deploy_private", "version", {
|
|
14
|
+
local: "save",
|
|
15
|
+
}),
|
|
16
|
+
}),
|
|
17
|
+
deployment: Object.freeze({
|
|
18
|
+
deploy: operation("deploy_site_version", "deployment", { local: "deploy" }),
|
|
19
|
+
status: operation("get_deployment_status", "deployment"),
|
|
20
|
+
}),
|
|
21
|
+
access: Object.freeze({
|
|
22
|
+
get: operation("get_site", "access", { select: "access" }),
|
|
23
|
+
update: operation("update_site_access", "access"),
|
|
24
|
+
}),
|
|
25
|
+
environment: Object.freeze({
|
|
26
|
+
get: operation("get_environment_variables", "environment"),
|
|
27
|
+
update: operation("update_environment_variables", "environment"),
|
|
28
|
+
}),
|
|
29
|
+
domain: Object.freeze({
|
|
30
|
+
list: operation("list_custom_domains", "domains"),
|
|
31
|
+
add: operation("add_custom_domain", "domains"),
|
|
32
|
+
refresh: operation("refresh_custom_domain_status", "domains"),
|
|
33
|
+
remove: operation("remove_custom_domain", "domains"),
|
|
34
|
+
}),
|
|
35
|
+
analytics: Object.freeze({
|
|
36
|
+
overview: operation("get_site_analytics_overview", "analytics"),
|
|
37
|
+
events: operation("list_site_analytics_events", "analytics"),
|
|
38
|
+
query: operation("query_site_analytics_event", "analytics"),
|
|
39
|
+
}),
|
|
40
|
+
diagnostics: Object.freeze({
|
|
41
|
+
logs: operation("get_site_worker_logs", "diagnostics"),
|
|
42
|
+
}),
|
|
43
|
+
database: Object.freeze({
|
|
44
|
+
overview: operation("read_database_overview", "database"),
|
|
45
|
+
rows: operation("read_database_table_rows", "database"),
|
|
46
|
+
}),
|
|
47
|
+
schedule: Object.freeze({
|
|
48
|
+
create: operation("create_schedule", "schedules"),
|
|
49
|
+
validate: operation("validate_suggested_schedule", "schedules"),
|
|
50
|
+
}),
|
|
51
|
+
});
|
|
52
|
+
function operation(tool, topic, options = {}) {
|
|
53
|
+
return Object.freeze({ tool, topic, ...options });
|
|
54
|
+
}
|
|
55
|
+
export function resolveOperation(resource, action) {
|
|
56
|
+
if (typeof resource !== "string" || typeof action !== "string") {
|
|
57
|
+
throw facadeError("invalid_operation", "resource and action must both be strings", "index");
|
|
58
|
+
}
|
|
59
|
+
const resourceOperations = Object.hasOwn(OPERATIONS, resource)
|
|
60
|
+
? OPERATIONS[resource]
|
|
61
|
+
: undefined;
|
|
62
|
+
const resolved = resourceOperations && Object.hasOwn(resourceOperations, action)
|
|
63
|
+
? resourceOperations[action]
|
|
64
|
+
: undefined;
|
|
65
|
+
if (!resolved) {
|
|
66
|
+
const topic = resource === "domain"
|
|
67
|
+
? "domains"
|
|
68
|
+
: resource === "schedule"
|
|
69
|
+
? "schedules"
|
|
70
|
+
: resourceOperations
|
|
71
|
+
? resource
|
|
72
|
+
: "index";
|
|
73
|
+
throw facadeError("unknown_operation", `Unknown Sites operation ${resource}.${action}; read sites_documentation({topic: "${topic}"})`, topic);
|
|
74
|
+
}
|
|
75
|
+
return { resource, action, key: `${resource}.${action}`, ...resolved };
|
|
76
|
+
}
|
|
77
|
+
export function facadeError(code, message, topic, details) {
|
|
78
|
+
return Object.assign(new Error(message), { code, topic, details });
|
|
79
|
+
}
|
|
80
|
+
export function operationForTopic(topic) {
|
|
81
|
+
if (typeof topic !== "string" || !topic.includes("."))
|
|
82
|
+
return undefined;
|
|
83
|
+
const [resource, action, ...rest] = topic.split(".");
|
|
84
|
+
if (rest.length > 0)
|
|
85
|
+
return undefined;
|
|
86
|
+
try {
|
|
87
|
+
return resolveOperation(resource, action);
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
const SENSITIVE_KEYS = new Set([
|
|
2
|
+
"token",
|
|
3
|
+
"access_token",
|
|
4
|
+
"api_key",
|
|
5
|
+
"client_secret",
|
|
6
|
+
"credential",
|
|
7
|
+
"credentials",
|
|
8
|
+
"private_key",
|
|
9
|
+
"refresh",
|
|
10
|
+
"refresh_token",
|
|
11
|
+
"password",
|
|
12
|
+
"secret",
|
|
13
|
+
"authorization",
|
|
14
|
+
"siwc_bypass_bearer_token",
|
|
15
|
+
"source_repository_credential",
|
|
16
|
+
]);
|
|
17
|
+
export function redact(value) {
|
|
18
|
+
return redactValue(value, new WeakSet());
|
|
19
|
+
}
|
|
20
|
+
function redactValue(value, seen) {
|
|
21
|
+
if (typeof value === "string")
|
|
22
|
+
return redactString(value);
|
|
23
|
+
if (value === null || typeof value !== "object")
|
|
24
|
+
return value;
|
|
25
|
+
if (seen.has(value))
|
|
26
|
+
return "[circular]";
|
|
27
|
+
seen.add(value);
|
|
28
|
+
if (Array.isArray(value))
|
|
29
|
+
return value.map((entry) => redactValue(entry, seen));
|
|
30
|
+
const output = {};
|
|
31
|
+
const secretEnvironmentEntry = "is_secret" in value && value.is_secret === true;
|
|
32
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
33
|
+
if (SENSITIVE_KEYS.has(key.toLowerCase()) ||
|
|
34
|
+
(secretEnvironmentEntry && key === "value")) {
|
|
35
|
+
output[key] = "[redacted]";
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
output[key] = redactValue(entry, seen);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return output;
|
|
42
|
+
}
|
|
43
|
+
function redactString(value) {
|
|
44
|
+
return value
|
|
45
|
+
.replace(/(https?:\/\/)[^/@\s:]+:[^/@\s]+@/gi, "$1[redacted]@")
|
|
46
|
+
.replace(/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/-]+=*/gi, "$1 [redacted]")
|
|
47
|
+
.replace(/([?&](?:token|access_token|key|signature|sig)=)[^&#\s]+/gi, "$1[redacted]");
|
|
48
|
+
}
|
|
49
|
+
export function boundedJson(value, maxBytes = 32_000) {
|
|
50
|
+
const serialized = JSON.stringify(redact(value), null, 2);
|
|
51
|
+
if (serialized === undefined) {
|
|
52
|
+
// Preserve the Buffer.byteLength rejection for non-JSON top-level values.
|
|
53
|
+
throw Object.assign(new TypeError('The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received undefined'), {
|
|
54
|
+
code: "ERR_INVALID_ARG_TYPE",
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
if (Buffer.byteLength(serialized) <= maxBytes)
|
|
58
|
+
return serialized;
|
|
59
|
+
return JSON.stringify({
|
|
60
|
+
ok: false,
|
|
61
|
+
error: {
|
|
62
|
+
code: "output_too_large",
|
|
63
|
+
message: "Sites output was truncated; use narrower filters or pagination",
|
|
64
|
+
original_bytes: Buffer.byteLength(serialized),
|
|
65
|
+
},
|
|
66
|
+
}, null, 2);
|
|
67
|
+
}
|