@backifydev/cli 0.3.19 → 0.3.20
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 +6 -0
- package/dist/index.js +991 -789
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -16508,8 +16508,8 @@ var require_CronFileParser = __commonJS({
|
|
|
16508
16508
|
* @throws If file cannot be read
|
|
16509
16509
|
*/
|
|
16510
16510
|
static parseFileSync(filePath) {
|
|
16511
|
-
const { readFileSync:
|
|
16512
|
-
const data =
|
|
16511
|
+
const { readFileSync: readFileSync30 } = __require("fs");
|
|
16512
|
+
const data = readFileSync30(filePath, "utf8");
|
|
16513
16513
|
return _CronFileParser.#parseContent(data);
|
|
16514
16514
|
}
|
|
16515
16515
|
/**
|
|
@@ -34104,22 +34104,22 @@ __export(mcp_exports, {
|
|
|
34104
34104
|
createCodingMcpServer: () => createCodingMcpServer,
|
|
34105
34105
|
runCodingMcpServer: () => runCodingMcpServer
|
|
34106
34106
|
});
|
|
34107
|
-
import { readFileSync as
|
|
34107
|
+
import { readFileSync as readFileSync27 } from "node:fs";
|
|
34108
34108
|
import { homedir as homedir2 } from "node:os";
|
|
34109
|
-
import { join as
|
|
34109
|
+
import { join as join21 } from "node:path";
|
|
34110
34110
|
import { createHash as createHash16 } from "node:crypto";
|
|
34111
34111
|
function createCodingMcpServer(options = {}) {
|
|
34112
34112
|
const endpoint2 = new URL(options.endpoint ?? process.env.BACKIFY_MCP_URL ?? "https://mcp.backify.dev");
|
|
34113
34113
|
if (endpoint2.username || endpoint2.password || endpoint2.search || endpoint2.hash || endpoint2.protocol !== "https:" && !(endpoint2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint2.hostname)))
|
|
34114
34114
|
throw new Error("Backify MCP requires HTTPS (HTTP is allowed only on loopback for development).");
|
|
34115
|
-
const configPath2 = options.configPath ??
|
|
34115
|
+
const configPath2 = options.configPath ?? join21(homedir2(), ".backify.json");
|
|
34116
34116
|
let boundOrganizationId = options.organizationId;
|
|
34117
34117
|
let delegated;
|
|
34118
34118
|
const server = new Server({ name: "backify", version: "0.2.0" }, { capabilities: { tools: {} }, instructions: "This is a transport bridge to the single Backify MCP at https://mcp.backify.dev. Organization permissions and all tool policies are enforced there. Sign-in is an explicit terminal action, never an MCP tool." });
|
|
34119
34119
|
async function remote(action) {
|
|
34120
34120
|
let config2;
|
|
34121
34121
|
try {
|
|
34122
|
-
config2 = JSON.parse(
|
|
34122
|
+
config2 = JSON.parse(readFileSync27(configPath2, "utf8"));
|
|
34123
34123
|
} catch {
|
|
34124
34124
|
throw new McpError(ErrorCode.InvalidRequest, signIn);
|
|
34125
34125
|
}
|
|
@@ -34180,9 +34180,9 @@ __export(coding_tools_exports, {
|
|
|
34180
34180
|
codingTools: () => codingTools,
|
|
34181
34181
|
configureCodingTool: () => configureCodingTool
|
|
34182
34182
|
});
|
|
34183
|
-
import { existsSync as
|
|
34184
|
-
import { basename as basename4, dirname as dirname17, join as
|
|
34185
|
-
import { randomUUID as
|
|
34183
|
+
import { existsSync as existsSync17, lstatSync as lstatSync20, mkdirSync as mkdirSync10, readFileSync as readFileSync28, renameSync as renameSync5, unlinkSync as unlinkSync6, writeFileSync as writeFileSync16 } from "node:fs";
|
|
34184
|
+
import { basename as basename4, dirname as dirname17, join as join22, resolve as resolve24 } from "node:path";
|
|
34185
|
+
import { randomUUID as randomUUID12 } from "node:crypto";
|
|
34186
34186
|
function object6(value) {
|
|
34187
34187
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
34188
34188
|
}
|
|
@@ -34201,11 +34201,11 @@ function configureCodingTool(options) {
|
|
|
34201
34201
|
if (!relative11) throw new Error("Open this tool's MCP configuration and supply its exact path with --config. Backify will not guess or modify an editor's global storage.");
|
|
34202
34202
|
const path = resolve24(options.root ?? process.cwd(), relative11);
|
|
34203
34203
|
for (let current = path; ; current = dirname17(current)) {
|
|
34204
|
-
if (
|
|
34204
|
+
if (existsSync17(current) && (lstatSync20(current).isSymbolicLink() || current === path && !lstatSync20(current).isFile())) throw new Error("MCP configuration cannot traverse symlinks or replace a directory.");
|
|
34205
34205
|
if (dirname17(current) === current) break;
|
|
34206
34206
|
}
|
|
34207
34207
|
if (options.dryRun) return { agent, transport, path, entry: codingToolEntry(agent, transport), changed: void 0 };
|
|
34208
|
-
const previous =
|
|
34208
|
+
const previous = existsSync17(path) ? readFileSync28(path, "utf8") : void 0;
|
|
34209
34209
|
let config2;
|
|
34210
34210
|
try {
|
|
34211
34211
|
config2 = previous === void 0 ? {} : JSON.parse(previous);
|
|
@@ -34222,13 +34222,13 @@ function configureCodingTool(options) {
|
|
|
34222
34222
|
const result = { agent, transport, path, entry, changed };
|
|
34223
34223
|
if (options.dryRun || !changed) return result;
|
|
34224
34224
|
mkdirSync10(dirname17(path), { recursive: true });
|
|
34225
|
-
const temporary = path + "." +
|
|
34225
|
+
const temporary = path + "." + randomUUID12() + ".tmp";
|
|
34226
34226
|
try {
|
|
34227
|
-
|
|
34228
|
-
if ((
|
|
34227
|
+
writeFileSync16(temporary, JSON.stringify({ ...config2, [key]: { ...servers, backify: entry } }, null, 2) + "\n", { flag: "wx", mode: existsSync17(path) ? lstatSync20(path).mode & 511 : 384 });
|
|
34228
|
+
if ((existsSync17(path) ? readFileSync28(path, "utf8") : void 0) !== previous) throw new Error("MCP configuration changed during setup. Retry after reviewing it.");
|
|
34229
34229
|
renameSync5(temporary, path);
|
|
34230
34230
|
} finally {
|
|
34231
|
-
if (
|
|
34231
|
+
if (existsSync17(temporary)) unlinkSync6(temporary);
|
|
34232
34232
|
}
|
|
34233
34233
|
return result;
|
|
34234
34234
|
}
|
|
@@ -34239,13 +34239,66 @@ var init_coding_tools = __esm({
|
|
|
34239
34239
|
codingTools = ["copilot", "cursor", "gemini", "cline", "windsurf"];
|
|
34240
34240
|
endpoint = "https://mcp.backify.dev";
|
|
34241
34241
|
defaultPaths = {
|
|
34242
|
-
copilot:
|
|
34243
|
-
cursor:
|
|
34244
|
-
gemini:
|
|
34242
|
+
copilot: join22(".vscode", "mcp.json"),
|
|
34243
|
+
cursor: join22(".cursor", "mcp.json"),
|
|
34244
|
+
gemini: join22(".gemini", "settings.json")
|
|
34245
34245
|
};
|
|
34246
34246
|
}
|
|
34247
34247
|
});
|
|
34248
34248
|
|
|
34249
|
+
// src/upgrade.ts
|
|
34250
|
+
import { existsSync, readFileSync, writeFileSync, lstatSync } from "node:fs";
|
|
34251
|
+
import { join } from "node:path";
|
|
34252
|
+
import { spawnSync } from "node:child_process";
|
|
34253
|
+
var stable = (value) => /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(value)?.slice(1).map(Number);
|
|
34254
|
+
function compatibleUpgrade(current, candidate) {
|
|
34255
|
+
const before = stable(current), after = stable(candidate);
|
|
34256
|
+
return !!before && !!after && after[0] === before[0] && (before[0] !== 0 || after[1] === before[1]) && (after[0] > before[0] || after[0] === before[0] && (after[1] > before[1] || after[1] === before[1] && after[2] > before[2]));
|
|
34257
|
+
}
|
|
34258
|
+
function newestCompatible(current, versions) {
|
|
34259
|
+
return versions.filter((value) => compatibleUpgrade(current, value)).sort((a, b) => {
|
|
34260
|
+
const left = stable(a), right = stable(b);
|
|
34261
|
+
return right[0] - left[0] || right[1] - left[1] || right[2] - left[2];
|
|
34262
|
+
})[0];
|
|
34263
|
+
}
|
|
34264
|
+
function upgradeSdk(root = process.cwd(), suppliedRunner) {
|
|
34265
|
+
const run = suppliedRunner ?? ((command3, args2) => {
|
|
34266
|
+
const result = spawnSync(command3, args2, { cwd: root, encoding: "utf8", shell: process.platform === "win32", windowsHide: true, timeout: 6e5, maxBuffer: 4 * 1024 * 1024 });
|
|
34267
|
+
if (result.error || result.status !== 0) throw new Error("Upgrade check failed: " + command3 + " " + args2.join(" "));
|
|
34268
|
+
return result.stdout ?? "";
|
|
34269
|
+
});
|
|
34270
|
+
for (const file of ["package.json", "package-lock.json"]) if (!existsSync(join(root, file)) || !lstatSync(join(root, file)).isFile() || lstatSync(join(root, file)).isSymbolicLink()) throw new Error("Validated SDK upgrades require regular package.json and package-lock.json files.");
|
|
34271
|
+
if (run("git", ["status", "--porcelain"]).trim()) throw new Error("Commit or preserve local changes before upgrading. No files were changed.");
|
|
34272
|
+
const manifestPath = join(root, "package.json"), lockPath = join(root, "package-lock.json");
|
|
34273
|
+
const originalManifest = readFileSync(manifestPath), originalLock = readFileSync(lockPath);
|
|
34274
|
+
const manifest = JSON.parse(originalManifest.toString("utf8"));
|
|
34275
|
+
if (manifest.workspaces) throw new Error("Upgrade SDK dependencies in their owning workspace; automatic root-workspace rewrites are not supported.");
|
|
34276
|
+
if (!manifest.dependencies?.["@backifydev/sdk"] && !manifest.devDependencies?.["@backifydev/sdk"]) throw new Error("This application has no SDK dependency.");
|
|
34277
|
+
const lock = JSON.parse(originalLock.toString("utf8"));
|
|
34278
|
+
const current = lock.packages?.["node_modules/@backifydev/sdk"]?.version;
|
|
34279
|
+
if (typeof current !== "string" || !stable(current)) throw new Error("The SDK lockfile version must be a stable semantic version.");
|
|
34280
|
+
const available = JSON.parse(run("npm", ["view", "@backifydev/sdk", "versions", "--json"]));
|
|
34281
|
+
if (!Array.isArray(available) || available.some((value) => typeof value !== "string")) throw new Error("The SDK registry returned invalid version metadata.");
|
|
34282
|
+
const candidate = newestCompatible(current, available);
|
|
34283
|
+
if (!candidate) return { status: "current", previousVersion: current, version: current, checks: [] };
|
|
34284
|
+
const checks = ["typecheck", "lint", "test", "build"].filter((name2) => typeof manifest.scripts?.[name2] === "string");
|
|
34285
|
+
if (!checks.includes("build") || !checks.some((name2) => name2 === "typecheck" || name2 === "test")) throw new Error("Add a build script and a typecheck or test script before validated upgrades.");
|
|
34286
|
+
try {
|
|
34287
|
+
run("npm", ["install", "--ignore-scripts", "--save-exact", "@backifydev/sdk@" + candidate]);
|
|
34288
|
+
for (const check2 of checks) run("npm", ["run", check2]);
|
|
34289
|
+
return { status: "upgraded", previousVersion: current, version: candidate, checks };
|
|
34290
|
+
} catch (error2) {
|
|
34291
|
+
writeFileSync(manifestPath, originalManifest);
|
|
34292
|
+
writeFileSync(lockPath, originalLock);
|
|
34293
|
+
try {
|
|
34294
|
+
run("npm", ["ci", "--ignore-scripts"]);
|
|
34295
|
+
} catch {
|
|
34296
|
+
throw new Error("SDK upgrade failed. Original manifests were restored, but dependency recovery failed. Run npm ci before starting the app.");
|
|
34297
|
+
}
|
|
34298
|
+
throw new Error("SDK upgrade failed validation. Original manifests and locked dependencies were restored.", { cause: error2 });
|
|
34299
|
+
}
|
|
34300
|
+
}
|
|
34301
|
+
|
|
34249
34302
|
// src/functions.ts
|
|
34250
34303
|
import { build } from "esbuild";
|
|
34251
34304
|
|
|
@@ -35238,7 +35291,7 @@ function unzipSync(data, opts) {
|
|
|
35238
35291
|
// src/functions.ts
|
|
35239
35292
|
import { createRequire as createRequire2 } from "node:module";
|
|
35240
35293
|
import { dirname, resolve } from "node:path";
|
|
35241
|
-
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
35294
|
+
import { existsSync as existsSync2, mkdirSync, writeFileSync as writeFileSync2 } from "node:fs";
|
|
35242
35295
|
async function deployFunctions(call2, appId, environmentId, packageBytes, options = {}) {
|
|
35243
35296
|
const result = await call2("/apps/" + appId + "/functions/environments/" + environmentId + "/deploy?confirm=true", { method: "POST", headers: { "content-type": "application/zip" }, body: packageBytes });
|
|
35244
35297
|
if (result.status === "succeeded") return;
|
|
@@ -35263,7 +35316,7 @@ async function deployFunctions(call2, appId, environmentId, packageBytes, option
|
|
|
35263
35316
|
}
|
|
35264
35317
|
async function packageFunctions(entry, output) {
|
|
35265
35318
|
const entryPath = resolve(entry);
|
|
35266
|
-
if (!
|
|
35319
|
+
if (!existsSync2(entryPath)) throw new Error("Function entrypoint does not exist: " + entryPath);
|
|
35267
35320
|
const require3 = createRequire2(import.meta.url);
|
|
35268
35321
|
const azureFunctions = require3.resolve("@azure/functions");
|
|
35269
35322
|
const result = await build({
|
|
@@ -35302,16 +35355,16 @@ async function packageFunctions(entry, output) {
|
|
|
35302
35355
|
});
|
|
35303
35356
|
const outputPath = resolve(output);
|
|
35304
35357
|
mkdirSync(dirname(outputPath), { recursive: true });
|
|
35305
|
-
|
|
35358
|
+
writeFileSync2(outputPath, archive);
|
|
35306
35359
|
return outputPath;
|
|
35307
35360
|
}
|
|
35308
35361
|
|
|
35309
35362
|
// src/environment.ts
|
|
35310
|
-
import { spawnSync } from "node:child_process";
|
|
35363
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
35311
35364
|
import { randomUUID } from "node:crypto";
|
|
35312
|
-
import { readFileSync, unlinkSync, writeFileSync as
|
|
35365
|
+
import { readFileSync as readFileSync2, unlinkSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
35313
35366
|
import { createServer } from "node:http";
|
|
35314
|
-
import { join, resolve as resolve2 } from "node:path";
|
|
35367
|
+
import { join as join2, resolve as resolve2 } from "node:path";
|
|
35315
35368
|
|
|
35316
35369
|
// ../platform/dist/manifest.js
|
|
35317
35370
|
var import_yaml = __toESM(require_dist(), 1);
|
|
@@ -35414,12 +35467,12 @@ function manifestDiagnostics(manifest, used, authentication) {
|
|
|
35414
35467
|
// ../platform/dist/delivery.js
|
|
35415
35468
|
var deliveryInstructions = `# Backify application delivery and prompt history
|
|
35416
35469
|
|
|
35417
|
-
Instruction version:
|
|
35418
|
-
Versioned guide: https://agent.backify.dev/
|
|
35470
|
+
Instruction version: 14
|
|
35471
|
+
Versioned guide: https://agent.backify.dev/v14/delivery.md
|
|
35419
35472
|
|
|
35420
35473
|
## Environment and documentation prerequisites
|
|
35421
35474
|
|
|
35422
|
-
Before installation or connection, read https://agent.backify.dev/
|
|
35475
|
+
Before installation or connection, read https://agent.backify.dev/v14 for execution capability checks, required endpoints (including https://docs.backify.dev), native permission requests, verified retries and fallback guidance. Follow the current tool's supported approval mechanism; never bypass restrictions. Read relevant capability documentation before implementation. Local validation must not depend on cloud deployment.
|
|
35423
35476
|
|
|
35424
35477
|
Before application implementation, all required setup checks and connected status must be verified OK. If any required check fails or remains unverified after supported recovery, stop setup and implementation; do not build a local website, minimal shell, placeholder, dependency-free fallback, or downloadable application archive. Report the blockers and recommend running the setup prompt in an AI coding tool such as Codex, Claude Code, or VS Code with GitHub Copilot agent mode, with terminal access, a persistent writable workspace, package installation, outbound HTTPS/DNS, and test execution enabled. Tool names alone do not guarantee readiness. Do not ask the application requirements question while setup is blocked. Later preview approval or deployment failures do not invalidate an already verified setup gate.
|
|
35425
35478
|
|
|
@@ -35445,7 +35498,7 @@ Initialize using App Id from the copied prompt and the current tool selection:
|
|
|
35445
35498
|
|
|
35446
35499
|
npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
|
|
35447
35500
|
|
|
35448
|
-
For a tool without a built-in preset, replace --agent <current-tool> with --instruction-file <relative-path>. Read BACKIFY.md and the instruction file used by the current AI coding tool before changing application code. Create or update only instruction files used by that tool; never create files for other coding tools. Use --agent for a built-in tool preset or --instruction-file <relative-path> for the current tool's native instruction file, as described in the setup guide. Initialization installs this workflow alongside the persistent SDK instructions. Follow https://agent.backify.dev/
|
|
35501
|
+
For a tool without a built-in preset, replace --agent <current-tool> with --instruction-file <relative-path>. Read BACKIFY.md and the instruction file used by the current AI coding tool before changing application code. Create or update only instruction files used by that tool; never create files for other coding tools. Use --agent for a built-in tool preset or --instruction-file <relative-path> for the current tool's native instruction file, as described in the setup guide. Initialization installs this workflow alongside the persistent SDK instructions. Follow https://agent.backify.dev/v14 for instruction version 13; use the guide matching backify.json in an existing application. Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
|
|
35449
35502
|
|
|
35450
35503
|
Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
|
|
35451
35504
|
|
|
@@ -35527,7 +35580,7 @@ These instructions are an explicit agent workflow, not a universal chat intercep
|
|
|
35527
35580
|
`;
|
|
35528
35581
|
|
|
35529
35582
|
// ../platform/dist/index.js
|
|
35530
|
-
var INSTRUCTION_VERSION =
|
|
35583
|
+
var INSTRUCTION_VERSION = 14;
|
|
35531
35584
|
var SDK_PACKAGE = "@backifydev/sdk";
|
|
35532
35585
|
var DOCS_URL = "https://docs.backify.dev";
|
|
35533
35586
|
var MAIL_LIMITS = Object.freeze({
|
|
@@ -35596,6 +35649,11 @@ Keep secrets server-side. Never commit or log credentials, expose secrets to bro
|
|
|
35596
35649
|
Scope cookies to the exact application hostname by omitting the \`Domain\` attribute. Never use a parent-domain cookie unless explicitly required.
|
|
35597
35650
|
Require explicit confirmation before destructive data operations or removing stateful resources. Removing a capability declaration does not authorize deleting its data.
|
|
35598
35651
|
|
|
35652
|
+
## Application defaults
|
|
35653
|
+
|
|
35654
|
+
When authentication is required, use email magic links by default and ask the builder which implemented additional providers to enable. Provider-specific setup and secure configuration remain available in the application Authentication page and portal. Preserve existing providers and email defaults; explicitly request method magic-link in newly built embedded email forms. Use reviewed local identities and the private CLI inbox to verify magic links locally; do not infer roles from email or fabricate provider support.
|
|
35655
|
+
Read the authenticated developer status branding snapshot before building a new application. Use supplied branding as flexible visual defaults; complete missing design elements as needed and never restrict application functionality because branding is incomplete. Existing applications keep their own branding unless a change is requested.
|
|
35656
|
+
|
|
35599
35657
|
## Implementation workflow
|
|
35600
35658
|
|
|
35601
35659
|
Inspect the framework, lockfile, scripts, configuration, and applicable repository instructions before editing. Preserve the existing framework and unrelated work. Implement the requested application rather than stopping at SDK setup; ask what to build if requirements are missing.
|
|
@@ -35718,13 +35776,13 @@ async function probeEndpoint(url2, transport = fetch) {
|
|
|
35718
35776
|
}
|
|
35719
35777
|
function workspaceProbe(root) {
|
|
35720
35778
|
const directory2 = resolve2(root);
|
|
35721
|
-
const filename2 =
|
|
35779
|
+
const filename2 = join2(directory2, ".backify-environment-" + randomUUID());
|
|
35722
35780
|
const content = randomUUID();
|
|
35723
35781
|
let created = false;
|
|
35724
35782
|
try {
|
|
35725
|
-
|
|
35783
|
+
writeFileSync3(filename2, content, { flag: "wx" });
|
|
35726
35784
|
created = true;
|
|
35727
|
-
if (
|
|
35785
|
+
if (readFileSync2(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
|
|
35728
35786
|
} finally {
|
|
35729
35787
|
if (created) unlinkSync(filename2);
|
|
35730
35788
|
}
|
|
@@ -35754,7 +35812,7 @@ function environmentProbes(root) {
|
|
|
35754
35812
|
const windowsNpm = name2 === "npm" && process.platform === "win32";
|
|
35755
35813
|
const executable = windowsNpm ? process.env.ComSpec ?? "cmd.exe" : name2;
|
|
35756
35814
|
const argumentsList = windowsNpm ? ["/d", "/s", "/c", "npm.cmd --version"] : ["--version"];
|
|
35757
|
-
const result =
|
|
35815
|
+
const result = spawnSync2(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
|
|
35758
35816
|
if (result.error) throw result.error;
|
|
35759
35817
|
if (result.status !== 0) throw Object.assign(new Error("Prerequisite command failed."), { code: result.status === 127 || result.status === 9009 ? "ENOENT" : void 0 });
|
|
35760
35818
|
},
|
|
@@ -35852,7 +35910,7 @@ import { hostname, platform, release, arch } from "node:os";
|
|
|
35852
35910
|
// package.json
|
|
35853
35911
|
var package_default = {
|
|
35854
35912
|
name: "@backifydev/cli",
|
|
35855
|
-
version: "0.3.
|
|
35913
|
+
version: "0.3.20",
|
|
35856
35914
|
description: "Command-line setup and diagnostics for Backify applications",
|
|
35857
35915
|
type: "module",
|
|
35858
35916
|
bin: {
|
|
@@ -35887,7 +35945,7 @@ var package_default = {
|
|
|
35887
35945
|
dependencies: {
|
|
35888
35946
|
"@modelcontextprotocol/sdk": "^1.31.0",
|
|
35889
35947
|
"@azure/functions": "^4.7.2",
|
|
35890
|
-
"@backifydev/sdk": "^0.1.
|
|
35948
|
+
"@backifydev/sdk": "^0.1.13",
|
|
35891
35949
|
esbuild: "^0.25.10",
|
|
35892
35950
|
fflate: "^0.8.2",
|
|
35893
35951
|
typescript: "^5.9.2"
|
|
@@ -35917,60 +35975,60 @@ import { randomBytes } from "node:crypto";
|
|
|
35917
35975
|
import { createServer as createServer2 } from "node:http";
|
|
35918
35976
|
|
|
35919
35977
|
// src/development.ts
|
|
35920
|
-
import { existsSync as
|
|
35921
|
-
import { dirname as dirname4, join as
|
|
35922
|
-
import { spawnSync as
|
|
35978
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7, readdirSync as readdirSync2, writeFileSync as writeFileSync6, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync3, cpSync } from "node:fs";
|
|
35979
|
+
import { dirname as dirname4, join as join7, resolve as resolve4 } from "node:path";
|
|
35980
|
+
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
35923
35981
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
35924
35982
|
|
|
35925
35983
|
// src/setup.ts
|
|
35926
|
-
import { existsSync as
|
|
35927
|
-
import { basename, dirname as dirname3, join as
|
|
35928
|
-
import { spawnSync as
|
|
35984
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5, mkdirSync as mkdirSync2, readdirSync, lstatSync as lstatSync2 } from "node:fs";
|
|
35985
|
+
import { basename, dirname as dirname3, join as join5, resolve as resolve3, isAbsolute } from "node:path";
|
|
35986
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
35929
35987
|
|
|
35930
35988
|
// src/delivery.ts
|
|
35931
|
-
import { existsSync as
|
|
35932
|
-
import { dirname as dirname2, join as
|
|
35989
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";
|
|
35990
|
+
import { dirname as dirname2, join as join3, relative as relativePath } from "node:path";
|
|
35933
35991
|
import { createHash } from "node:crypto";
|
|
35934
35992
|
var previousGeneratedWorkflowHashes = /* @__PURE__ */ new Set(["33e962274e8493f7cbac2afbac05a4e96afeec49ee08cf2bf82f8add9081b28b", "578dfb4c771c623fd04454e8a604efd701d5563d11e11191324862369bd24718", "6eb280ae7bdb14c390011686c41400f59c023304c3015d8440b7e80aaafa1c11", "545e03a1d5b996ade179e0e60ed5c86accdadc1982c1c25efd094e34f72f47ee"]);
|
|
35935
35993
|
function validateDeliveryInstructions(root) {
|
|
35936
35994
|
for (const filename2 of ["BACKIFY.md", "BACKIFY-WORKFLOW.md"]) {
|
|
35937
|
-
const path =
|
|
35938
|
-
if (
|
|
35939
|
-
const existing =
|
|
35995
|
+
const path = join3(root, filename2);
|
|
35996
|
+
if (existsSync3(path)) {
|
|
35997
|
+
const existing = readFileSync3(path, "utf8").replace(/\r\n/g, "\n");
|
|
35940
35998
|
if (existing !== deliveryInstructions && !previousGeneratedWorkflowHashes.has(createHash("sha256").update(existing).digest("hex"))) throw new Error(filename2 + " contains different instructions. Review it before initializing; it will not be overwritten.");
|
|
35941
35999
|
}
|
|
35942
36000
|
}
|
|
35943
36001
|
}
|
|
35944
36002
|
function installDeliveryInstructions(root, instructionFiles2) {
|
|
35945
36003
|
validateDeliveryInstructions(root);
|
|
35946
|
-
|
|
36004
|
+
writeFileSync4(join3(root, "BACKIFY.md"), deliveryInstructions);
|
|
35947
36005
|
for (const relative11 of instructionFiles2) {
|
|
35948
|
-
const instructionPath =
|
|
35949
|
-
const link = relativePath(dirname2(instructionPath),
|
|
35950
|
-
const legacyLink = relativePath(dirname2(instructionPath),
|
|
36006
|
+
const instructionPath = join3(root, relative11), content = readFileSync3(instructionPath, "utf8");
|
|
36007
|
+
const link = relativePath(dirname2(instructionPath), join3(root, "BACKIFY.md")).replaceAll("\\", "/");
|
|
36008
|
+
const legacyLink = relativePath(dirname2(instructionPath), join3(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
|
|
35951
36009
|
const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
|
|
35952
36010
|
const guidance = "For application delivery and recording each user request, follow [BACKIFY.md](" + link + ").";
|
|
35953
|
-
if (content.includes(legacy))
|
|
35954
|
-
else if (!content.includes("## Backify delivery"))
|
|
36011
|
+
if (content.includes(legacy)) writeFileSync4(instructionPath, content.replace(legacy, guidance));
|
|
36012
|
+
else if (!content.includes("## Backify delivery")) writeFileSync4(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
|
|
35955
36013
|
}
|
|
35956
36014
|
}
|
|
35957
36015
|
|
|
35958
36016
|
// src/application-support.ts
|
|
35959
|
-
import { existsSync as
|
|
35960
|
-
import { join as
|
|
36017
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
|
|
36018
|
+
import { join as join4 } from "node:path";
|
|
35961
36019
|
function applicationSupport(root) {
|
|
35962
|
-
const manifestPath =
|
|
35963
|
-
const manifest =
|
|
36020
|
+
const manifestPath = join4(root, "package.json");
|
|
36021
|
+
const manifest = existsSync4(manifestPath) ? JSON.parse(readFileSync4(manifestPath, "utf8")) : {};
|
|
35964
36022
|
const dependencies = { ...manifest.devDependencies, ...manifest.dependencies };
|
|
35965
36023
|
const framework = ["next", "astro", "@sveltejs/kit", "nuxt", "express", "vite", "react"].find((name2) => dependencies[name2]) ?? "unknown";
|
|
35966
|
-
if (
|
|
36024
|
+
if (existsSync4(join4(root, "Dockerfile"))) {
|
|
35967
36025
|
return { tier: "advanced", framework, guidance: "Custom-container hosting is an advanced path, not a guarantee of Backify SDK integration or framework support. Preserve the Dockerfile and verify capability integration separately." };
|
|
35968
36026
|
}
|
|
35969
36027
|
if (framework === "vite" && dependencies.react) {
|
|
35970
36028
|
return { tier: "recommended", framework, guidance: "React with Vite is the recommended frontend baseline. Prefer TypeScript for new code and use an explicit Backify TypeScript backend for server capabilities. This assessment does not verify deployment or authorization." };
|
|
35971
36029
|
}
|
|
35972
36030
|
return {
|
|
35973
|
-
tier:
|
|
36031
|
+
tier: existsSync4(manifestPath) ? "compatible" : "unassessed",
|
|
35974
36032
|
framework,
|
|
35975
36033
|
guidance: "Backify is TypeScript-first. For new apps, prefer React with Vite and an explicit Backify TypeScript backend. Preserve existing JavaScript/TypeScript frameworks; assess SSR, build, identity and capability integration before claiming support. Browser-only apps do not require Node.js in production."
|
|
35976
36034
|
};
|
|
@@ -35978,9 +36036,9 @@ function applicationSupport(root) {
|
|
|
35978
36036
|
|
|
35979
36037
|
// src/setup.ts
|
|
35980
36038
|
var instructionFiles = ["AGENTS.md"];
|
|
35981
|
-
var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot:
|
|
36039
|
+
var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot: join5(".github", "copilot-instructions.md"), gemini: "GEMINI.md", cursor: "AGENTS.md", cline: join5(".clinerules", "backify.md"), windsurf: "AGENTS.md" };
|
|
35982
36040
|
function instructionSelection(root, agent, instructionFile) {
|
|
35983
|
-
const configPath2 =
|
|
36041
|
+
const configPath2 = join5(root, "backify.json"), configured = existsSync5(configPath2) ? JSON.parse(readFileSync5(configPath2, "utf8")) : {};
|
|
35984
36042
|
const custom2 = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
|
|
35985
36043
|
const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
|
|
35986
36044
|
if (typeof selected !== "string" || selected !== "custom" && !Object.hasOwn(agentInstructionFiles, selected)) throw new Error("Select the current tool with --agent or --instruction-file <relative-path>.");
|
|
@@ -35989,9 +36047,9 @@ function instructionSelection(root, agent, instructionFile) {
|
|
|
35989
36047
|
const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
|
|
35990
36048
|
if (isAbsolute(filename2) || /^[A-Za-z]:/.test(filename2) || parts.some((part) => !part || part === "." || part === ".." || part.toLowerCase() === ".git") || ["backify.md", "backify-workflow.md", "backify.json", "package.json", "package-lock.json"].includes(normalized.toLowerCase())) throw new Error("Instruction file must be a relative tool-instruction path inside the project, not Git metadata or a Backify configuration file.");
|
|
35991
36049
|
for (let index = 1; index <= parts.length; index++) {
|
|
35992
|
-
const entry =
|
|
36050
|
+
const entry = join5(root, ...parts.slice(0, index));
|
|
35993
36051
|
try {
|
|
35994
|
-
const metadata =
|
|
36052
|
+
const metadata = lstatSync2(entry);
|
|
35995
36053
|
if (metadata.isSymbolicLink() || index < parts.length && !metadata.isDirectory() || index === parts.length && !metadata.isFile()) throw new Error("Instruction file path cannot traverse symlinks or replace a directory.");
|
|
35996
36054
|
} catch (reason) {
|
|
35997
36055
|
if (reason.code !== "ENOENT") throw reason;
|
|
@@ -36004,26 +36062,26 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
|
|
|
36004
36062
|
}
|
|
36005
36063
|
function isToolWorkspaceEntry(entry, root = process.cwd()) {
|
|
36006
36064
|
if (entry.name.toLowerCase() === ".git" || entry.name.toLowerCase() === ".env" || entry.name.toLowerCase().startsWith(".env.")) return false;
|
|
36007
|
-
return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(
|
|
36065
|
+
return entry.isDirectory() && (entry.name.startsWith(".") || ["work", "outputs"].includes(entry.name) || readdirSync(join5(root, entry.name)).length === 0) || entry.isFile() && (entry.name.startsWith(".") || /\.(md|mdc)$/i.test(entry.name));
|
|
36008
36066
|
}
|
|
36009
36067
|
function detectPackageManager(root = process.cwd()) {
|
|
36010
|
-
for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (
|
|
36068
|
+
for (const [file, name2] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["bun.lockb", "bun"], ["bun.lock", "bun"], ["package-lock.json", "npm"]]) if (existsSync5(join5(root, file))) return name2;
|
|
36011
36069
|
return "npm";
|
|
36012
36070
|
}
|
|
36013
36071
|
function updateInstructions(root = process.cwd(), agent, instructionFile) {
|
|
36014
36072
|
const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
|
|
36015
|
-
const path =
|
|
36016
|
-
return { path, content: updateManagedInstructions(
|
|
36073
|
+
const path = join5(root, relative11);
|
|
36074
|
+
return { path, content: updateManagedInstructions(existsSync5(path) ? readFileSync5(path, "utf8") : "") };
|
|
36017
36075
|
});
|
|
36018
36076
|
for (const { path, content } of updates) {
|
|
36019
36077
|
mkdirSync2(dirname3(path), { recursive: true });
|
|
36020
|
-
|
|
36078
|
+
writeFileSync5(path, content);
|
|
36021
36079
|
}
|
|
36022
36080
|
}
|
|
36023
36081
|
function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
36024
|
-
const path =
|
|
36025
|
-
if (!
|
|
36026
|
-
const value = JSON.parse(
|
|
36082
|
+
const path = join5(root, "backify.json");
|
|
36083
|
+
if (!existsSync5(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
|
|
36084
|
+
const value = JSON.parse(readFileSync5(path, "utf8")), issues = validateConfig(value);
|
|
36027
36085
|
if (issues.length) throw new Error(issues.join("; "));
|
|
36028
36086
|
if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
|
|
36029
36087
|
const selected = instructionSelection(root, agent, instructionFile);
|
|
@@ -36033,11 +36091,11 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
|
36033
36091
|
value.agent = selected.agent;
|
|
36034
36092
|
value.instructionFile = selected.instructionFile;
|
|
36035
36093
|
value.instructionVersion = INSTRUCTION_VERSION;
|
|
36036
|
-
|
|
36094
|
+
writeFileSync5(path, JSON.stringify(value, null, 2) + "\n");
|
|
36037
36095
|
}
|
|
36038
36096
|
function sdkInstalled(root = process.cwd()) {
|
|
36039
36097
|
try {
|
|
36040
|
-
const pkg = JSON.parse(
|
|
36098
|
+
const pkg = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
|
|
36041
36099
|
return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
|
|
36042
36100
|
} catch {
|
|
36043
36101
|
return false;
|
|
@@ -36045,29 +36103,29 @@ function sdkInstalled(root = process.cwd()) {
|
|
|
36045
36103
|
}
|
|
36046
36104
|
function installSdk(root = process.cwd()) {
|
|
36047
36105
|
if (sdkInstalled(root)) return;
|
|
36048
|
-
const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result =
|
|
36106
|
+
const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result = spawnSync3(manager, args2, { cwd: root, stdio: "inherit", shell: process.platform === "win32" });
|
|
36049
36107
|
if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
|
|
36050
36108
|
}
|
|
36051
36109
|
function ensurePackageManifest(root) {
|
|
36052
|
-
const path =
|
|
36053
|
-
if (
|
|
36110
|
+
const path = join5(root, "package.json");
|
|
36111
|
+
if (existsSync5(path)) return;
|
|
36054
36112
|
const setupFiles = /* @__PURE__ */ new Set([".git", ".gitignore", ".github", "AGENTS.md", "CLAUDE.md", "GEMINI.md", "BACKIFY.md", "BACKIFY-WORKFLOW.md", "README.md", "LICENSE", "backify.json"]);
|
|
36055
36113
|
if (readdirSync(root, { withFileTypes: true }).some((entry) => !setupFiles.has(entry.name) && !isToolWorkspaceEntry(entry, root))) throw new Error("package.json is missing. Run backify init from the existing application's JavaScript/TypeScript package directory, or start in an empty folder. See https://agent.backify.dev/");
|
|
36056
36114
|
const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
|
|
36057
|
-
|
|
36115
|
+
writeFileSync5(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
|
|
36058
36116
|
}
|
|
36059
36117
|
function initialize(appId, root = process.cwd(), install = true, agent, instructionFile) {
|
|
36060
36118
|
if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
|
|
36061
36119
|
const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
|
|
36062
36120
|
validateDeliveryInstructions(root);
|
|
36063
|
-
for (const relative11 of files) if (
|
|
36064
|
-
const customContainer = !
|
|
36121
|
+
for (const relative11 of files) if (existsSync5(join5(root, relative11))) updateManagedInstructions(readFileSync5(join5(root, relative11), "utf8"));
|
|
36122
|
+
const customContainer = !existsSync5(join5(root, "package.json")) && existsSync5(join5(root, "Dockerfile"));
|
|
36065
36123
|
if (!customContainer) {
|
|
36066
36124
|
ensurePackageManifest(root);
|
|
36067
36125
|
if (install) installSdk(root);
|
|
36068
36126
|
}
|
|
36069
|
-
const configPath2 =
|
|
36070
|
-
|
|
36127
|
+
const configPath2 = join5(root, "backify.json"), existing = existsSync5(configPath2) ? JSON.parse(readFileSync5(configPath2, "utf8")) : {};
|
|
36128
|
+
writeFileSync5(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
|
|
36071
36129
|
updateInstructions(root, selected.agent, selected.instructionFile);
|
|
36072
36130
|
installDeliveryInstructions(root, files);
|
|
36073
36131
|
}
|
|
@@ -36081,17 +36139,17 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
36081
36139
|
issues.push("package.json is invalid JSON");
|
|
36082
36140
|
}
|
|
36083
36141
|
if (!sdkInstalled(root)) {
|
|
36084
|
-
if (!
|
|
36142
|
+
if (!existsSync5(join5(root, "package.json")) && existsSync5(join5(root, "Dockerfile"))) warnings.push("Custom container: JavaScript SDK capabilities are not validated. Use only supported Backify integrations for this language.");
|
|
36085
36143
|
else issues.push(`${SDK_PACKAGE} is not installed`);
|
|
36086
36144
|
}
|
|
36087
36145
|
let config2;
|
|
36088
36146
|
try {
|
|
36089
|
-
config2 = JSON.parse(
|
|
36147
|
+
config2 = JSON.parse(readFileSync5(join5(root, "backify.json"), "utf8"));
|
|
36090
36148
|
issues.push(...validateConfig(config2));
|
|
36091
36149
|
} catch {
|
|
36092
36150
|
issues.push("backify.json is missing or invalid JSON");
|
|
36093
36151
|
}
|
|
36094
|
-
if (config2 && config2.instructionVersion
|
|
36152
|
+
if (config2 && config2.instructionVersion > INSTRUCTION_VERSION) issues.push(`Repository instruction version ${config2.instructionVersion}; CLI version ${INSTRUCTION_VERSION}. Use the matching CLI or run backify sync to upgrade.`);
|
|
36095
36153
|
let files = instructionFiles;
|
|
36096
36154
|
try {
|
|
36097
36155
|
files = selectedInstructionFiles(root, agent, instructionFile);
|
|
@@ -36099,16 +36157,24 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
36099
36157
|
issues.push(reason instanceof Error ? reason.message : String(reason));
|
|
36100
36158
|
}
|
|
36101
36159
|
for (const relative11 of files) {
|
|
36102
|
-
const path =
|
|
36103
|
-
if (!
|
|
36160
|
+
const path = join5(root, relative11);
|
|
36161
|
+
if (!existsSync5(path)) {
|
|
36104
36162
|
issues.push(`${relative11} is missing`);
|
|
36105
36163
|
continue;
|
|
36106
36164
|
}
|
|
36107
|
-
|
|
36165
|
+
const content = readFileSync5(path, "utf8");
|
|
36166
|
+
const managed = managedInstructionIssues(content);
|
|
36167
|
+
if (config2 && config2.instructionVersion < INSTRUCTION_VERSION) {
|
|
36168
|
+
const declared = content.match(/Instruction version:\s*(\d+)/)?.[1];
|
|
36169
|
+
const structural = managed.filter((issue2) => !issue2.includes("stale or inconsistent"));
|
|
36170
|
+
issues.push(...structural.map((issue2) => relative11 + " " + issue2));
|
|
36171
|
+
if (Number(declared) !== config2.instructionVersion || !content.includes("https://agent.backify.dev/v" + config2.instructionVersion)) issues.push(relative11 + " does not match the repository instruction version");
|
|
36172
|
+
else warnings.push(relative11 + " uses supported older instructions; follow the versioned guide. Run backify sync only when intentionally upgrading instructions.");
|
|
36173
|
+
} else issues.push(...managed.map((issue2) => relative11 + " " + issue2));
|
|
36108
36174
|
}
|
|
36109
36175
|
let version2 = "unknown";
|
|
36110
36176
|
try {
|
|
36111
|
-
const pkg = JSON.parse(
|
|
36177
|
+
const pkg = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
|
|
36112
36178
|
version2 = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
|
|
36113
36179
|
} catch {
|
|
36114
36180
|
}
|
|
@@ -36116,14 +36182,14 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
36116
36182
|
}
|
|
36117
36183
|
|
|
36118
36184
|
// src/container-build.ts
|
|
36119
|
-
import { existsSync as
|
|
36120
|
-
import { join as
|
|
36185
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
|
|
36186
|
+
import { join as join6 } from "node:path";
|
|
36121
36187
|
function containerBuildSupport(root) {
|
|
36122
|
-
if (
|
|
36123
|
-
if (!
|
|
36124
|
-
const manifest = JSON.parse(
|
|
36125
|
-
if (!
|
|
36126
|
-
if (typeof manifest.scripts?.start !== "string" || !manifest.scripts.start || manifest.workspaces || ["pnpm-lock.yaml", "yarn.lock"].some((name2) =>
|
|
36188
|
+
if (existsSync6(join6(root, "Dockerfile"))) return { adapter: "custom-container", issue: null };
|
|
36189
|
+
if (!existsSync6(join6(root, "package.json"))) return { adapter: null, issue: "Provide a repository-root Dockerfile serving HTTP on port 8080 for this language. Local Docker is not required." };
|
|
36190
|
+
const manifest = JSON.parse(readFileSync6(join6(root, "package.json"), "utf8"));
|
|
36191
|
+
if (!existsSync6(join6(root, "package-lock.json"))) return { adapter: null, issue: "Managed Node builds require package-lock.json. Generate and commit the npm lockfile, or provide a custom Dockerfile." };
|
|
36192
|
+
if (typeof manifest.scripts?.start !== "string" || !manifest.scripts.start || manifest.workspaces || ["pnpm-lock.yaml", "yarn.lock"].some((name2) => existsSync6(join6(root, name2)))) {
|
|
36127
36193
|
return { adapter: null, issue: "Managed Node builds require an npm application with a start script at the repository root. Workspaces and other package managers require a custom Dockerfile." };
|
|
36128
36194
|
}
|
|
36129
36195
|
return { adapter: "node-npm", issue: null };
|
|
@@ -36141,10 +36207,10 @@ function promptContext(root = process.cwd()) {
|
|
|
36141
36207
|
function installedSdkVersion(root) {
|
|
36142
36208
|
let directory2 = resolve4(root);
|
|
36143
36209
|
while (true) {
|
|
36144
|
-
const manifest =
|
|
36145
|
-
if (
|
|
36210
|
+
const manifest = join7(directory2, "node_modules", "@backifydev", "sdk", "package.json");
|
|
36211
|
+
if (existsSync7(manifest)) {
|
|
36146
36212
|
try {
|
|
36147
|
-
const sdk = JSON.parse(
|
|
36213
|
+
const sdk = JSON.parse(readFileSync7(manifest, "utf8"));
|
|
36148
36214
|
return sdk.name === "@backifydev/sdk" && typeof sdk.version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(sdk.version) ? sdk.version : null;
|
|
36149
36215
|
} catch {
|
|
36150
36216
|
return null;
|
|
@@ -36186,8 +36252,8 @@ function applicationGuid(appId) {
|
|
|
36186
36252
|
return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
|
|
36187
36253
|
}
|
|
36188
36254
|
function projectApplication(root = process.cwd()) {
|
|
36189
|
-
if (!
|
|
36190
|
-
return JSON.parse(
|
|
36255
|
+
if (!existsSync7(join7(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
|
|
36256
|
+
return JSON.parse(readFileSync7(join7(root, "backify.json"), "utf8")).appId;
|
|
36191
36257
|
}
|
|
36192
36258
|
function apiAddress(value) {
|
|
36193
36259
|
const address = new URL(value);
|
|
@@ -36222,11 +36288,11 @@ function apiClient(session, transport = fetch) {
|
|
|
36222
36288
|
function saveUserConfig(path, config2) {
|
|
36223
36289
|
const temporary = path + "." + randomUUID2() + ".tmp";
|
|
36224
36290
|
try {
|
|
36225
|
-
|
|
36291
|
+
writeFileSync6(temporary, JSON.stringify(config2, null, 2) + "\n", { mode: 384, flag: "wx" });
|
|
36226
36292
|
if (process.platform === "win32") {
|
|
36227
36293
|
const account = [process.env.USERDOMAIN, process.env.USERNAME].filter(Boolean).join("\\");
|
|
36228
36294
|
if (!account) throw new Error("Cannot identify the account to protect CLI credentials.");
|
|
36229
|
-
const secured =
|
|
36295
|
+
const secured = spawnSync4("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
|
|
36230
36296
|
if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
|
|
36231
36297
|
}
|
|
36232
36298
|
renameSync(temporary, path);
|
|
@@ -36240,7 +36306,7 @@ function repositoryName(remote) {
|
|
|
36240
36306
|
return match[1].toLowerCase();
|
|
36241
36307
|
}
|
|
36242
36308
|
function git(args2, root = process.cwd(), environment = process.env) {
|
|
36243
|
-
const result =
|
|
36309
|
+
const result = spawnSync4("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
|
|
36244
36310
|
if (result.status !== 0) throw new Error("Git " + args2[0] + " failed. Check repository access, branch protection, and local changes.");
|
|
36245
36311
|
return result.stdout.trim();
|
|
36246
36312
|
}
|
|
@@ -36250,15 +36316,15 @@ function gitEnvironment(repository, token) {
|
|
|
36250
36316
|
}
|
|
36251
36317
|
function validateCloneMerge(source, target) {
|
|
36252
36318
|
for (const entry of readdirSync2(source, { withFileTypes: true })) {
|
|
36253
|
-
const destination =
|
|
36319
|
+
const destination = join7(target, entry.name);
|
|
36254
36320
|
let existing;
|
|
36255
36321
|
try {
|
|
36256
|
-
existing =
|
|
36322
|
+
existing = lstatSync3(destination);
|
|
36257
36323
|
} catch (reason) {
|
|
36258
36324
|
if (reason.code === "ENOENT") continue;
|
|
36259
36325
|
throw reason;
|
|
36260
36326
|
}
|
|
36261
|
-
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(
|
|
36327
|
+
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join7(source, entry.name), destination);
|
|
36262
36328
|
else throw new Error("Clone conflicts with existing workspace entry: " + destination + ". Existing files are never overwritten; reconcile the conflict or use a new folder.");
|
|
36263
36329
|
}
|
|
36264
36330
|
}
|
|
@@ -36268,18 +36334,18 @@ async function cloneProject(call2, appId, root = process.cwd()) {
|
|
|
36268
36334
|
if (readdirSync2(root, { withFileTypes: true }).some((entry) => !isToolWorkspaceEntry(entry, root))) throw new Error("--clone requires an empty directory or a workspace containing only AI tool metadata and default work/outputs directories. Existing application files and Git repositories are never overwritten.");
|
|
36269
36335
|
const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
|
|
36270
36336
|
if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
|
|
36271
|
-
const staging = mkdtempSync(
|
|
36337
|
+
const staging = mkdtempSync(join7(dirname4(resolve4(root)), ".backify-clone-"));
|
|
36272
36338
|
try {
|
|
36273
36339
|
git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
|
|
36274
36340
|
validateCloneMerge(staging, root);
|
|
36275
|
-
for (const entry of readdirSync2(staging)) cpSync(
|
|
36341
|
+
for (const entry of readdirSync2(staging)) cpSync(join7(staging, entry), join7(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
|
|
36276
36342
|
} finally {
|
|
36277
|
-
if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(
|
|
36343
|
+
if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(join7(dirname4(resolve4(root)), ".backify-clone-"))) throw new Error("Refusing to clean up an unexpected clone staging path.");
|
|
36278
36344
|
rmSync(staging, { recursive: true, force: true });
|
|
36279
36345
|
}
|
|
36280
36346
|
}
|
|
36281
36347
|
async function pullProject(call2, appId, root = process.cwd()) {
|
|
36282
|
-
if (
|
|
36348
|
+
if (existsSync7(join7(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
|
|
36283
36349
|
const prefix = "/apps/" + applicationGuid(appId);
|
|
36284
36350
|
const status = await call2(prefix + "/developer");
|
|
36285
36351
|
if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
|
|
@@ -36322,15 +36388,15 @@ function attachmentNames(values) {
|
|
|
36322
36388
|
}))];
|
|
36323
36389
|
}
|
|
36324
36390
|
function localReport(runChecks, root = process.cwd()) {
|
|
36325
|
-
const pkg =
|
|
36391
|
+
const pkg = existsSync7(join7(root, "package.json")) ? JSON.parse(readFileSync7(join7(root, "package.json"), "utf8")) : {};
|
|
36326
36392
|
const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
|
|
36327
|
-
const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (
|
|
36393
|
+
const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (existsSync7(join7(root, "Dockerfile")) ? "custom-container" : "unknown");
|
|
36328
36394
|
const setup = doctor(root);
|
|
36329
36395
|
const checks = [{ name: "backify doctor", status: setup.valid ? "passed" : "failed" }];
|
|
36330
36396
|
const manager = detectPackageManager(root);
|
|
36331
36397
|
for (const name2 of ["typecheck", "lint", "test", "build"]) {
|
|
36332
36398
|
if (!pkg.scripts?.[name2]) continue;
|
|
36333
|
-
const result = runChecks ?
|
|
36399
|
+
const result = runChecks ? spawnSync4(manager, ["run", name2], { cwd: root, stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, CI: "true" }, shell: process.platform === "win32", windowsHide: true, timeout: 10 * 6e4 }) : void 0;
|
|
36334
36400
|
checks.push({ name: name2, status: result ? result.status === 0 ? "passed" : "failed" : "not-run" });
|
|
36335
36401
|
}
|
|
36336
36402
|
let branch = null, commitSha = null, dirty = true;
|
|
@@ -36340,8 +36406,8 @@ function localReport(runChecks, root = process.cwd()) {
|
|
|
36340
36406
|
dirty = Boolean(git(["status", "--porcelain"], root));
|
|
36341
36407
|
} catch {
|
|
36342
36408
|
}
|
|
36343
|
-
const outputDirectory = ["dist", "build", "out", "."].find((directory2) =>
|
|
36344
|
-
return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile:
|
|
36409
|
+
const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync7(join7(root, directory2, "index.html"))) ?? null;
|
|
36410
|
+
return { framework, sdkVersion: dependencies["@backifydev/sdk"] ?? null, branch, commitSha, dirty, buildCommand: pkg.scripts?.build ? manager + " run build" : null, outputDirectory, hasDockerfile: existsSync7(join7(root, "Dockerfile")), checks, support: setup.support, warnings: setup.warnings };
|
|
36345
36411
|
}
|
|
36346
36412
|
function matchesSource(release2, commit) {
|
|
36347
36413
|
return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
|
|
@@ -36558,10 +36624,10 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
|
|
|
36558
36624
|
|
|
36559
36625
|
// src/local-runtime.ts
|
|
36560
36626
|
import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
|
|
36561
|
-
import { chmodSync, existsSync as
|
|
36562
|
-
import { dirname as dirname5, join as
|
|
36627
|
+
import { chmodSync, existsSync as existsSync8, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync8, readdirSync as readdirSync3, writeFileSync as writeFileSync7 } from "node:fs";
|
|
36628
|
+
import { dirname as dirname5, join as join8, resolve as resolve5, sep } from "node:path";
|
|
36563
36629
|
import { homedir } from "node:os";
|
|
36564
|
-
import { spawnSync as
|
|
36630
|
+
import { spawnSync as spawnSync5 } from "node:child_process";
|
|
36565
36631
|
|
|
36566
36632
|
// src/local-state.ts
|
|
36567
36633
|
import { renameSync as renameSync2 } from "node:fs";
|
|
@@ -36594,7 +36660,7 @@ function checkedPath(root, filename2) {
|
|
|
36594
36660
|
if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
|
|
36595
36661
|
let current = target;
|
|
36596
36662
|
while (true) {
|
|
36597
|
-
if (
|
|
36663
|
+
if (existsSync8(current) && lstatSync4(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
|
|
36598
36664
|
if (dirname5(current) === current) break;
|
|
36599
36665
|
current = dirname5(current);
|
|
36600
36666
|
}
|
|
@@ -36602,25 +36668,25 @@ function checkedPath(root, filename2) {
|
|
|
36602
36668
|
}
|
|
36603
36669
|
function verifyInstallationFiles(root, expected, directory2 = root) {
|
|
36604
36670
|
for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
|
|
36605
|
-
const path = checkedPath(root,
|
|
36671
|
+
const path = checkedPath(root, join8(directory2, entry.name));
|
|
36606
36672
|
if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
|
|
36607
36673
|
else if (!entry.isFile() || !Object.hasOwn(expected, path.slice(root.length + 1).split(sep).join("/"))) throw new Error("Installed runtime contains unexpected files; reinstall a reviewed version");
|
|
36608
36674
|
}
|
|
36609
36675
|
}
|
|
36610
|
-
function installedLocalRuntime(base =
|
|
36676
|
+
function installedLocalRuntime(base = join8(homedir(), ".backify")) {
|
|
36611
36677
|
const pointer = checkedPath(base, "runtime.json");
|
|
36612
|
-
if (!
|
|
36613
|
-
const installed = JSON.parse(
|
|
36678
|
+
if (!existsSync8(pointer)) return void 0;
|
|
36679
|
+
const installed = JSON.parse(readFileSync8(pointer, "utf8"));
|
|
36614
36680
|
if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(installed.version) || installed.rid !== runtimeIdentifier() || !installed.files || Object.keys(installed.files).length > 3e3) throw new Error("Invalid local runtime installation receipt");
|
|
36615
|
-
const root = checkedPath(base,
|
|
36681
|
+
const root = checkedPath(base, join8("runtimes", installed.version, installed.rid));
|
|
36616
36682
|
verifyInstallationFiles(root, installed.files);
|
|
36617
36683
|
for (const [filename2, digest4] of Object.entries(installed.files)) {
|
|
36618
36684
|
const path = checkedPath(root, filename2);
|
|
36619
|
-
if (!/^[a-f0-9]{64}$/.test(digest4) || !
|
|
36685
|
+
if (!/^[a-f0-9]{64}$/.test(digest4) || !lstatSync4(path).isFile() || lstatSync4(path).size > maxArchiveBytes || hash(readFileSync8(path)) !== digest4) throw new Error("Installed runtime bytes changed; reinstall a reviewed version");
|
|
36620
36686
|
}
|
|
36621
36687
|
const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
36622
36688
|
if (!installed.files["Backify.Hcr.dll"] || !installed.files[executableName]) throw new Error("Runtime archive requires the self-contained HCR executable and DLL");
|
|
36623
|
-
return { path:
|
|
36689
|
+
return { path: join8(root, "Backify.Hcr.dll"), executable: join8(root, executableName), version: installed.version, rid: installed.rid };
|
|
36624
36690
|
}
|
|
36625
36691
|
function installLocalRuntime(archive, options) {
|
|
36626
36692
|
if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(options.version) || !/^[a-f0-9]{64}$/.test(options.sha256)) throw new Error("Provide a release version vX.Y.Z and an independently reviewed SHA-256");
|
|
@@ -36634,28 +36700,28 @@ function installLocalRuntime(archive, options) {
|
|
|
36634
36700
|
const rid = runtimeIdentifier();
|
|
36635
36701
|
const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
36636
36702
|
if (!files["Backify.Hcr.dll"] || !files[executable] || !files["sql/events-v1.sql"] || !files["sql/jobs-v1.sql"]) throw new Error("Runtime archive is missing required host assets");
|
|
36637
|
-
const base = options.base ??
|
|
36638
|
-
const parent = checkedPath(base,
|
|
36703
|
+
const base = options.base ?? join8(homedir(), ".backify");
|
|
36704
|
+
const parent = checkedPath(base, join8("runtimes", options.version));
|
|
36639
36705
|
mkdirSync3(parent, { recursive: true, mode: 448 });
|
|
36640
36706
|
const destination = checkedPath(parent, rid);
|
|
36641
36707
|
const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
|
|
36642
|
-
if (!
|
|
36708
|
+
if (!existsSync8(destination)) {
|
|
36643
36709
|
const staging = checkedPath(parent, ".install-" + randomUUID3());
|
|
36644
36710
|
mkdirSync3(staging, { mode: 448 });
|
|
36645
36711
|
for (const [name2, bytes] of Object.entries(files)) {
|
|
36646
36712
|
const filename2 = checkedPath(staging, name2);
|
|
36647
36713
|
mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
|
|
36648
|
-
|
|
36714
|
+
writeFileSync7(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
|
|
36649
36715
|
}
|
|
36650
|
-
if (process.platform !== "win32") chmodSync(
|
|
36716
|
+
if (process.platform !== "win32") chmodSync(join8(staging, executable), 448);
|
|
36651
36717
|
renameLocalFile(staging, destination);
|
|
36652
36718
|
} else {
|
|
36653
36719
|
verifyInstallationFiles(destination, receipt.files);
|
|
36654
|
-
for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(
|
|
36720
|
+
for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(readFileSync8(checkedPath(destination, name2))) !== digest4) throw new Error("Runtime version already exists with different bytes; never overwrite an installation");
|
|
36655
36721
|
}
|
|
36656
36722
|
const pointer = checkedPath(base, "runtime.json");
|
|
36657
36723
|
const temporary = checkedPath(base, ".runtime-" + randomUUID3() + ".json");
|
|
36658
|
-
|
|
36724
|
+
writeFileSync7(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
|
|
36659
36725
|
renameLocalFile(temporary, pointer);
|
|
36660
36726
|
return installedLocalRuntime(base);
|
|
36661
36727
|
}
|
|
@@ -36683,10 +36749,10 @@ async function downloadLocalRuntime(version2) {
|
|
|
36683
36749
|
}
|
|
36684
36750
|
function localPrerequisites() {
|
|
36685
36751
|
const runtime = installedLocalRuntime();
|
|
36686
|
-
const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
36752
|
+
const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join8(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
|
|
36687
36753
|
const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
|
|
36688
|
-
const executable = directory2 ?
|
|
36689
|
-
const result =
|
|
36754
|
+
const executable = directory2 ? join8(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
36755
|
+
const result = spawnSync5(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
|
|
36690
36756
|
return { name: name2, available: result.status === 0 };
|
|
36691
36757
|
});
|
|
36692
36758
|
return { rid: runtimeIdentifier(), runtime: runtime ? { installed: true, version: runtime.version } : { installed: false }, postgres: checks, ready: !!runtime && checks.every((check2) => check2.available) };
|
|
@@ -36695,20 +36761,20 @@ function localPrerequisites() {
|
|
|
36695
36761
|
// src/workload.ts
|
|
36696
36762
|
import { build as build2 } from "esbuild";
|
|
36697
36763
|
import { createHash as createHash14 } from "node:crypto";
|
|
36698
|
-
import { existsSync as
|
|
36699
|
-
import { dirname as dirname13, isAbsolute as isAbsolute14, join as
|
|
36764
|
+
import { existsSync as existsSync15, mkdirSync as mkdirSync7, readFileSync as readFileSync23, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync13 } from "node:fs";
|
|
36765
|
+
import { dirname as dirname13, isAbsolute as isAbsolute14, join as join17, relative as relative8, resolve as resolve19 } from "node:path";
|
|
36700
36766
|
|
|
36701
36767
|
// src/local-development.ts
|
|
36702
36768
|
import { context as context2, formatMessagesSync } from "esbuild";
|
|
36703
36769
|
import { spawn as spawn4 } from "node:child_process";
|
|
36704
|
-
import { randomBytes as randomBytes6, randomUUID as
|
|
36705
|
-
import { existsSync as
|
|
36706
|
-
import { resolve as resolve18, join as
|
|
36770
|
+
import { randomBytes as randomBytes6, randomUUID as randomUUID11, createHash as createHash13 } from "node:crypto";
|
|
36771
|
+
import { existsSync as existsSync14, lstatSync as lstatSync16, mkdirSync as mkdirSync6, readFileSync as readFileSync22, realpathSync as realpathSync5, writeFileSync as writeFileSync12, unlinkSync as unlinkSync5 } from "node:fs";
|
|
36772
|
+
import { resolve as resolve18, join as join16, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
|
|
36707
36773
|
|
|
36708
36774
|
// ../analyzer/dist/index.js
|
|
36709
36775
|
import ts3 from "typescript";
|
|
36710
|
-
import { readFileSync as
|
|
36711
|
-
import { join as
|
|
36776
|
+
import { readFileSync as readFileSync9, readdirSync as readdirSync4, existsSync as existsSync9 } from "node:fs";
|
|
36777
|
+
import { join as join9, extname } from "node:path";
|
|
36712
36778
|
|
|
36713
36779
|
// ../analyzer/dist/authentication.js
|
|
36714
36780
|
import ts from "typescript";
|
|
@@ -37125,230 +37191,18 @@ function repositorySources(root) {
|
|
|
37125
37191
|
for (const entry of readdirSync4(dir, { withFileTypes: true })) {
|
|
37126
37192
|
if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
|
|
37127
37193
|
continue;
|
|
37128
|
-
const path =
|
|
37194
|
+
const path = join9(dir, entry.name);
|
|
37129
37195
|
if (entry.isDirectory())
|
|
37130
37196
|
walk(path);
|
|
37131
37197
|
else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
|
|
37132
|
-
result.push({ path, content:
|
|
37198
|
+
result.push({ path, content: readFileSync9(path, "utf8") });
|
|
37133
37199
|
}
|
|
37134
37200
|
};
|
|
37135
|
-
if (
|
|
37201
|
+
if (existsSync9(root))
|
|
37136
37202
|
walk(root);
|
|
37137
37203
|
return result;
|
|
37138
37204
|
}
|
|
37139
37205
|
|
|
37140
|
-
// src/local-inspection.ts
|
|
37141
|
-
function createLocalDataInspector(runtime, options) {
|
|
37142
|
-
const tableName = (value) => typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(value) && !/^__backify/i.test(value);
|
|
37143
|
-
const bucketName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(value);
|
|
37144
|
-
if (typeof window !== "undefined" || options.buckets.length > 100 || options.buckets.some((name2) => !bucketName(name2)) || new Set(options.buckets).size !== options.buckets.length) throw new Error("invalid_local_inspection");
|
|
37145
|
-
const fail = () => {
|
|
37146
|
-
throw new Error("invalid_local_inspection");
|
|
37147
|
-
};
|
|
37148
|
-
const unavailable4 = () => {
|
|
37149
|
-
throw new Error("local_inspection_unavailable");
|
|
37150
|
-
};
|
|
37151
|
-
const providerRequest = async (operation, missingObject = false) => {
|
|
37152
|
-
try {
|
|
37153
|
-
return await operation();
|
|
37154
|
-
} catch (error2) {
|
|
37155
|
-
const status = error2?.status;
|
|
37156
|
-
if (status === 413) throw new Error("local_inspection_too_large");
|
|
37157
|
-
if (status === 400) fail();
|
|
37158
|
-
if (status === 404 && missingObject) throw new Error("local_inspection_not_found");
|
|
37159
|
-
return unavailable4();
|
|
37160
|
-
}
|
|
37161
|
-
};
|
|
37162
|
-
const object7 = (value, fields5) => {
|
|
37163
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !fields5.includes(name2))) fail();
|
|
37164
|
-
return value;
|
|
37165
|
-
};
|
|
37166
|
-
const page = (input) => {
|
|
37167
|
-
const limit = input.limit ?? 25, offset = input.offset ?? 0;
|
|
37168
|
-
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 50 || typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > 1e4) fail();
|
|
37169
|
-
return { limit, offset };
|
|
37170
|
-
};
|
|
37171
|
-
const bounded = (value) => {
|
|
37172
|
-
if (Buffer.byteLength(JSON.stringify(value)) > 65536) throw new Error("local_inspection_too_large");
|
|
37173
|
-
return value;
|
|
37174
|
-
};
|
|
37175
|
-
const redact = (value, depth = 0) => {
|
|
37176
|
-
if (depth > 20) return "[DEPTH LIMIT]";
|
|
37177
|
-
if (Array.isArray(value)) return value.map((item) => redact(item, depth + 1));
|
|
37178
|
-
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name2, item]) => [name2, /(?:password|secret|token|credential|private.?key|connection.?string)/i.test(name2) ? "[REDACTED]" : redact(item, depth + 1)]));
|
|
37179
|
-
return value;
|
|
37180
|
-
};
|
|
37181
|
-
const requireBucket = (name2) => {
|
|
37182
|
-
if (!options.storageEnabled) unavailable4();
|
|
37183
|
-
const known = [...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)];
|
|
37184
|
-
if (!bucketName(name2) || !known.includes(name2)) fail();
|
|
37185
|
-
return name2;
|
|
37186
|
-
};
|
|
37187
|
-
return {
|
|
37188
|
-
async tables() {
|
|
37189
|
-
if (!options.databaseEnabled) unavailable4();
|
|
37190
|
-
if (runtime.database.listTables) return bounded(await providerRequest(() => runtime.database.listTables()));
|
|
37191
|
-
if (options.nativeDatabase) unavailable4();
|
|
37192
|
-
const names = runtime.inspect().tables.map((table) => table.name).filter(tableName).sort();
|
|
37193
|
-
return { names: names.slice(0, 100), hasMore: names.length > 100 };
|
|
37194
|
-
},
|
|
37195
|
-
async rows(value) {
|
|
37196
|
-
if (!options.databaseEnabled) unavailable4();
|
|
37197
|
-
const input = object7(value, ["table", "limit", "offset"]), pagination = page(input);
|
|
37198
|
-
if (!tableName(input.table)) fail();
|
|
37199
|
-
if (runtime.database.inspectRows) {
|
|
37200
|
-
const result = await providerRequest(() => runtime.database.inspectRows(input.table, pagination));
|
|
37201
|
-
return bounded({ ...result, rows: result.rows.map((row) => redact(row)) });
|
|
37202
|
-
}
|
|
37203
|
-
if (options.nativeDatabase) unavailable4();
|
|
37204
|
-
const rows = await runtime.database.query(input.table, { filters: [], limit: pagination.limit + 1, offset: pagination.offset });
|
|
37205
|
-
return bounded({ rows: rows.slice(0, pagination.limit).map((row) => redact(row)), ...pagination, nextOffset: rows.length > pagination.limit && pagination.offset + pagination.limit <= 1e4 ? pagination.offset + pagination.limit : null });
|
|
37206
|
-
},
|
|
37207
|
-
buckets() {
|
|
37208
|
-
if (!options.storageEnabled) unavailable4();
|
|
37209
|
-
return bounded({ names: [.../* @__PURE__ */ new Set([...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)])].filter(bucketName).sort().slice(0, 100) });
|
|
37210
|
-
},
|
|
37211
|
-
async objects(value) {
|
|
37212
|
-
const input = object7(value, ["bucket", "prefix", "limit", "offset"]), pagination = page(input);
|
|
37213
|
-
const name2 = requireBucket(input.bucket);
|
|
37214
|
-
if (input.prefix !== void 0 && (typeof input.prefix !== "string" || input.prefix.length > 512 || /[\\\x00-\x1f\x7f]/.test(input.prefix) || input.prefix.startsWith("/") || input.prefix.split("/").some((part) => part === "." || part === ".."))) fail();
|
|
37215
|
-
const objects = await providerRequest(() => runtime.storage.list(name2, input.prefix));
|
|
37216
|
-
if (objects.length > 1e3) throw new Error("local_inspection_too_large");
|
|
37217
|
-
objects.sort((first, second) => first.key.localeCompare(second.key));
|
|
37218
|
-
return bounded({ objects: objects.slice(pagination.offset, pagination.offset + pagination.limit), ...pagination, nextOffset: objects.length > pagination.offset + pagination.limit ? pagination.offset + pagination.limit : null });
|
|
37219
|
-
},
|
|
37220
|
-
async preview(value) {
|
|
37221
|
-
const input = object7(value, ["bucket", "key"]), name2 = requireBucket(input.bucket);
|
|
37222
|
-
if (typeof input.key !== "string" || !input.key || input.key.length > 512 || input.key.startsWith("/") || /[\\\x00-\x1f\x7f]/.test(input.key) || input.key.split("/").some((part) => part === "." || part === "..")) fail();
|
|
37223
|
-
if (!options.nativeStorage && !await runtime.storage.exists(name2, input.key)) throw new Error("local_inspection_not_found");
|
|
37224
|
-
const bytes = await providerRequest(() => runtime.storage.download(name2, input.key), true);
|
|
37225
|
-
if (bytes.byteLength > 16384) return { kind: "too-large", size: bytes.byteLength, maximumPreviewBytes: 16384 };
|
|
37226
|
-
try {
|
|
37227
|
-
const text3 = new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
37228
|
-
if (text3.includes("\0")) throw new Error("Binary object");
|
|
37229
|
-
return bounded({ kind: "text", size: bytes.byteLength, text: text3 });
|
|
37230
|
-
} catch (error2) {
|
|
37231
|
-
if (error2 instanceof Error && error2.message === "local_inspection_too_large") throw error2;
|
|
37232
|
-
return { kind: "binary", size: bytes.byteLength, bytes: [...bytes.slice(0, 64)], truncated: bytes.byteLength > 64 };
|
|
37233
|
-
}
|
|
37234
|
-
}
|
|
37235
|
-
};
|
|
37236
|
-
}
|
|
37237
|
-
|
|
37238
|
-
// src/local-dashboard.ts
|
|
37239
|
-
var dashboardHtml = String.raw`<!doctype html>
|
|
37240
|
-
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Backify Local</title>
|
|
37241
|
-
<style>body{font:16px system-ui;max-width:1100px;margin:30px auto;padding:20px;background:#10131a;color:#ecf1ff}button,select,input,textarea{font:inherit;padding:8px;margin:4px;border:1px solid #8ca1bc;border-radius:5px}button{cursor:pointer}button:disabled{cursor:wait;opacity:.6}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid #78baff}nav{display:flex;flex-wrap:wrap;margin-bottom:20px}section{padding:16px;border:1px solid #36465f;border-radius:8px;margin:12px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#171f2b;padding:16px;border-radius:6px}label{display:inline-block;margin:4px}p{line-height:1.5;color:#bdcbe0}#message{min-height:24px;color:#f5c575}[hidden]{display:none!important}textarea{display:block;width:30em;max-width:100%;min-height:80px}</style></head>
|
|
37242
|
-
<body><h1>Backify Local Development</h1><p>Application data stays on this computer. This is a local operator dashboard, not an application user's login or a production portal.</p>
|
|
37243
|
-
<nav aria-label="Inspection panels"><button data-panel="overview">Overview</button><button data-panel="data">Data</button><button data-panel="jobs">Jobs</button><button data-panel="events">Events</button><button data-panel="logs">Logs</button></nav>
|
|
37244
|
-
<p id="message" role="status" aria-live="polite">Open this dashboard using backify dev --open to authenticate.</p>
|
|
37245
|
-
<section id="overview"><h2>Supervisor and endpoints</h2><p>A responding endpoint is not proof of provider health. Database and storage data are inspected explicitly in the Data panel.</p><button id="refresh">Refresh status</button><pre id="state" aria-label="Local status"></pre></section>
|
|
37246
|
-
<section id="data" hidden><h2>Read-only data inspection</h2><p>At most 100 public database table names and 50 rows per page are supported. Common credential-named row fields are redacted; this is not comprehensive secret classification. Object contents require an explicit preview request. No data mutation controls are provided.</p>
|
|
37247
|
-
<h3>Database</h3><button id="load-tables">Load tables</button><label>Table <select id="tables" aria-label="Database table"></select></label><button id="load-rows">Inspect rows</button><button id="next-rows" disabled>Next row page</button><pre id="rows" aria-label="Database rows"></pre>
|
|
37248
|
-
<h3>Private storage</h3><button id="load-buckets">Load buckets</button><label>Bucket <select id="buckets" aria-label="Storage bucket"></select></label><label>Prefix <input id="prefix" maxlength="512"></label><button id="load-objects">List objects</button><button id="next-objects" disabled>Next object page</button><pre id="objects" aria-label="Storage objects"></pre><label>Object <select id="keys" aria-label="Storage object"></select></label><button id="preview">Preview selected object</button><pre id="object-preview" aria-label="Object preview"></pre></section>
|
|
37249
|
-
<section id="jobs" hidden><h2>Declared jobs and retained history</h2><p>These are local operator actions, not application-user permissions. Retries create a new run and may repeat business side effects. Do not enter credentials in job payloads.</p><button id="load-jobs">Refresh jobs</button><label>Job <select id="job-name" aria-label="Declared job"></select></label><label>Payload <textarea id="job-payload" aria-label="Job payload (JSON)" maxlength="32768" placeholder="Optional JSON, otherwise null"></textarea></label><button id="run-job">Run selected job</button><h3>Schedules</h3><label>Schedule <select id="schedule-id" aria-label="Declared schedule"></select></label><button id="pause-schedule" disabled>Pause selected schedule</button><button id="resume-schedule" disabled>Resume selected schedule</button><h3>Run recovery</h3><label>Run <select id="run-id" aria-label="Recoverable run"></select></label><button id="retry-run" disabled>Retry failed run</button><button id="cancel-run" disabled>Cancel selected run</button><pre id="job-state" aria-label="Job history"></pre></section>
|
|
37250
|
-
<section id="logs" hidden><h2>Local logs</h2><button id="load-logs">Refresh logs</button><pre id="log-state" aria-label="Local logs"></pre></section>
|
|
37251
|
-
<section id="events" hidden><h2>Local event activity</h2><p>Latest 100 delivery metadata rows and retained status counts. Payloads, idempotency keys and lease receipts are never shown. Lightweight mode preserves snapshot leases. Full mode uses a native PostgreSQL inbox and drains retained snapshot records without renaming or deleting them. Local hooks and retained drainage are single-worker, not distributed cloud subscriptions. No acknowledgement or destructive controls are exposed.</p><button id="load-events">Refresh events</button><pre id="event-state" aria-label="Local event activity"></pre></section>
|
|
37252
|
-
<script>
|
|
37253
|
-
const token=new URLSearchParams(location.hash.slice(1)).get("session");
|
|
37254
|
-
history.replaceState(null,"",location.pathname);
|
|
37255
|
-
const element=id=>document.getElementById(id);
|
|
37256
|
-
let rowPage=null,objectPage=null,rowTable="",objectBucket="",objectPrefix="",jobsBusy=false,jobView={jobs:[],schedules:[],runs:[]};
|
|
37257
|
-
const jobActions=["run-job","pause-schedule","resume-schedule","retry-run","cancel-run"];
|
|
37258
|
-
function show(id,value){element(id).textContent=JSON.stringify(value,null,2)}
|
|
37259
|
-
function choices(id,names){element(id).replaceChildren();for(const name of names){const option=document.createElement("option");option.value=name;option.textContent=name;element(id).append(option)}}
|
|
37260
|
-
async function request(path,input){if(!token)throw new Error("Local session required; reopen using backify dev --open.");const response=await fetch(path,{method:input===undefined?"GET":"POST",headers:{authorization:"Bearer "+token,"content-type":"application/json"},body:input===undefined?undefined:JSON.stringify(input),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(35000)});const value=await response.json();if(!response.ok)throw new Error("Inspection failed ("+response.status+"): "+(value.error||"unavailable"));return value}
|
|
37261
|
-
function action(id,handler){element(id).onclick=async()=>{if(jobActions.includes(id)){if(jobsBusy)return;jobsBusy=true;jobControls()}element(id).disabled=true;element("message").textContent="Loading...";try{await handler();element("message").textContent="Updated."}catch(error){element("message").textContent=error instanceof Error?error.message:"Local operation unavailable"}finally{if(jobActions.includes(id)){jobsBusy=false;jobControls()}else element(id).disabled=id==="next-rows"?rowPage===null:id==="next-objects"?objectPage===null:false}}}
|
|
37262
|
-
async function status(){show("state",await request("/v1/status"))}
|
|
37263
|
-
async function rows(offset){const table=element("tables").value;if(!table)throw new Error("Choose a table first.");const result=await request("/v1/database/rows",{table,offset,limit:25});rowTable=table;rowPage=result.nextOffset;show("rows",result);element("next-rows").disabled=rowPage===null}
|
|
37264
|
-
async function objects(offset){const bucket=element("buckets").value,prefix=element("prefix").value;if(!bucket)throw new Error("Choose a bucket first.");const result=await request("/v1/storage/objects",{bucket,prefix,offset,limit:25});objectBucket=bucket;objectPrefix=prefix;objectPage=result.nextOffset;show("objects",result);choices("keys",result.objects.map(value=>value.key));element("next-objects").disabled=objectPage===null;element("object-preview").textContent=""}
|
|
37265
|
-
function records(id,values,label){const selected=element(id).value;element(id).replaceChildren();for(const value of values){const option=document.createElement("option");option.value=value.id;option.textContent=label(value);element(id).append(option)}if(values.some(value=>value.id===selected))element(id).value=selected}
|
|
37266
|
-
function jobControls(){const schedule=jobView.schedules.find(value=>value.id===element("schedule-id").value),run=jobView.runs.find(value=>value.id===element("run-id").value);element("run-job").disabled=jobsBusy||!jobView.jobs.length;element("pause-schedule").disabled=jobsBusy||!schedule||!schedule.enabled;element("resume-schedule").disabled=jobsBusy||!schedule||schedule.enabled;element("retry-run").disabled=jobsBusy||!run||run.status!=="failed"||run.canRetry===false;element("cancel-run").disabled=jobsBusy||!run||!["queued","running","retrying"].includes(run.status)||run.canCancel===false}
|
|
37267
|
-
async function jobs(){const result=await request("/v1/jobs");jobView=result;show("job-state",result);choices("job-name",result.jobs.map(value=>value.name));records("schedule-id",result.schedules,value=>value.name+" ("+(value.enabled?"enabled":"paused")+")");records("run-id",result.runs.filter(value=>["failed","queued","running","retrying"].includes(value.status)),value=>value.id+" - "+value.job+" ("+value.status+")");jobControls()}
|
|
37268
|
-
element("schedule-id").onchange=jobControls;element("run-id").onchange=jobControls;
|
|
37269
|
-
for(const button of document.querySelectorAll("[data-panel]")){button.onclick=()=>{for(const name of ["overview","data","jobs","events","logs"])element(name).hidden=name!==button.dataset.panel}}
|
|
37270
|
-
action("refresh",status);
|
|
37271
|
-
action("load-tables",async()=>{const result=await request("/v1/database/tables");choices("tables",result.names);show("rows",{tables:result.names.length,hasMore:result.hasMore});rowPage=null;element("next-rows").disabled=true});
|
|
37272
|
-
action("load-rows",()=>rows(0));
|
|
37273
|
-
action("next-rows",()=>{if(rowPage===null||rowTable!==element("tables").value)throw new Error("Reload rows after changing the table.");return rows(rowPage)});
|
|
37274
|
-
action("load-buckets",async()=>{const result=await request("/v1/storage/buckets");choices("buckets",result.names);show("objects",result);objectPage=null;element("next-objects").disabled=true});
|
|
37275
|
-
action("load-objects",()=>objects(0));
|
|
37276
|
-
action("next-objects",()=>{if(objectPage===null||objectBucket!==element("buckets").value||objectPrefix!==element("prefix").value)throw new Error("Reload objects after changing bucket or prefix.");return objects(objectPage)});
|
|
37277
|
-
action("preview",async()=>{const bucket=element("buckets").value,key=element("keys").value;if(!key||bucket!==objectBucket)throw new Error("List and choose an object first.");show("object-preview",await request("/v1/storage/preview",{bucket,key}))});
|
|
37278
|
-
action("load-jobs",jobs);
|
|
37279
|
-
action("run-job",async()=>{const name=element("job-name").value;if(!name)throw new Error("Choose a declared job first.");const raw=element("job-payload").value;if(new TextEncoder().encode(raw).length>32768)throw new Error("Job payload exceeds 32 KiB.");let payload=null;try{if(raw.trim())payload=JSON.parse(raw)}catch{throw new Error("Enter valid JSON for the job payload.")}const input={name,payload};if(new TextEncoder().encode(JSON.stringify(input)).length>32768)throw new Error("Job payload exceeds 32 KiB.");await request("/v1/jobs/run",input);element("job-payload").value="";await jobs()});
|
|
37280
|
-
action("pause-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:false});await jobs()});
|
|
37281
|
-
action("resume-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:true});await jobs()});
|
|
37282
|
-
action("retry-run",async()=>{await request("/v1/jobs/retry",{id:element("run-id").value});await jobs()});
|
|
37283
|
-
action("cancel-run",async()=>{await request("/v1/jobs/cancel",{id:element("run-id").value});await jobs()});
|
|
37284
|
-
action("load-logs",async()=>show("log-state",await request("/v1/logs")));
|
|
37285
|
-
action("load-events",async()=>show("event-state",await request("/v1/events")));
|
|
37286
|
-
if(token)status().then(()=>{element("message").textContent="Local session connected."}).catch(error=>{element("message").textContent=error.message});
|
|
37287
|
-
</script></body></html>`;
|
|
37288
|
-
|
|
37289
|
-
// src/local-native-events.ts
|
|
37290
|
-
function createLocalNativeEvents(local, native) {
|
|
37291
|
-
const handlers = /* @__PURE__ */ new Map();
|
|
37292
|
-
const validateName2 = (name2) => {
|
|
37293
|
-
if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2)) throw new Error("Invalid event name");
|
|
37294
|
-
};
|
|
37295
|
-
return {
|
|
37296
|
-
track: (name2, data, options) => {
|
|
37297
|
-
if (!local.track) throw new Error("Upgrade the local SDK to enable event tracking");
|
|
37298
|
-
return local.track(name2, data, options);
|
|
37299
|
-
},
|
|
37300
|
-
async emit(name2, payload, options) {
|
|
37301
|
-
validateName2(name2);
|
|
37302
|
-
if (options?.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || !options.idempotencyKey || options.idempotencyKey.length > 128)) throw new Error("Invalid idempotency key");
|
|
37303
|
-
if (options?.idempotencyKey !== void 0 && (local.hasIdempotencyKey ? local.hasIdempotencyKey(options.idempotencyKey) : local.snapshot().deliveries.some((item) => item.idempotencyKey === options.idempotencyKey))) {
|
|
37304
|
-
await local.emit(name2, payload, options);
|
|
37305
|
-
return;
|
|
37306
|
-
}
|
|
37307
|
-
let accepted;
|
|
37308
|
-
try {
|
|
37309
|
-
accepted = JSON.parse(JSON.stringify(payload ?? null));
|
|
37310
|
-
} catch {
|
|
37311
|
-
throw new Error("Event payload must be JSON serializable");
|
|
37312
|
-
}
|
|
37313
|
-
if (await native.emitAccepted(name2, accepted, options)) {
|
|
37314
|
-
for (const handler of handlers.get(name2) ?? []) await handler(structuredClone(accepted));
|
|
37315
|
-
}
|
|
37316
|
-
},
|
|
37317
|
-
on(name2, handler) {
|
|
37318
|
-
if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2) || typeof handler !== "function") throw new Error("Invalid local event subscription");
|
|
37319
|
-
handlers.set(name2, [...handlers.get(name2) ?? [], handler]);
|
|
37320
|
-
return () => handlers.set(name2, (handlers.get(name2) ?? []).filter((value) => value !== handler));
|
|
37321
|
-
},
|
|
37322
|
-
async receive(name2, options) {
|
|
37323
|
-
const retained = await local.receive(name2, options);
|
|
37324
|
-
return retained.length ? retained : native.receive(name2, options);
|
|
37325
|
-
},
|
|
37326
|
-
async complete(id, receipt, retry) {
|
|
37327
|
-
if (retry !== void 0 && typeof retry !== "boolean") throw new Error("Invalid local event retry");
|
|
37328
|
-
if (typeof id === "string" && id.startsWith("event_")) await local.complete(id, receipt, retry);
|
|
37329
|
-
else await native.complete(id, receipt, retry);
|
|
37330
|
-
},
|
|
37331
|
-
async inspect() {
|
|
37332
|
-
const retained = local.inspect(), durable = await native.inspect();
|
|
37333
|
-
const counts = { ...retained.counts };
|
|
37334
|
-
for (const status of Object.keys(counts)) {
|
|
37335
|
-
counts[status] += durable.counts[status];
|
|
37336
|
-
if (!Number.isSafeInteger(counts[status])) throw new Error("Local event inspection count exceeds bounds");
|
|
37337
|
-
}
|
|
37338
|
-
const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
|
|
37339
|
-
if (!Number.isSafeInteger(total)) throw new Error("Local event inspection count exceeds bounds");
|
|
37340
|
-
const deliveries = [...retained.deliveries, ...durable.deliveries].sort((first, second) => Date.parse(second.emittedAt) - Date.parse(first.emittedAt) || (first.id < second.id ? 1 : first.id > second.id ? -1 : 0)).slice(0, 100);
|
|
37341
|
-
return { version: 1, counts, deliveries, hasMore: total > deliveries.length };
|
|
37342
|
-
}
|
|
37343
|
-
};
|
|
37344
|
-
}
|
|
37345
|
-
|
|
37346
|
-
// src/local-job-executor.ts
|
|
37347
|
-
import { spawn as spawn2 } from "node:child_process";
|
|
37348
|
-
import { createHash as createHash10 } from "node:crypto";
|
|
37349
|
-
import { lstatSync as lstatSync11, readFileSync as readFileSync15 } from "node:fs";
|
|
37350
|
-
import { isAbsolute as isAbsolute8, join as join11, relative as relative3, resolve as resolve12 } from "node:path";
|
|
37351
|
-
|
|
37352
37206
|
// ../sdk/dist/schedules.js
|
|
37353
37207
|
var import_cron_parser = __toESM(require_dist2(), 1);
|
|
37354
37208
|
function nextSchedule(input, after, creating = false) {
|
|
@@ -37391,6 +37245,9 @@ function declarationInput(declaration) {
|
|
|
37391
37245
|
return { ...base, kind: "cron", expression: schedule.kind === "hourly" ? "0 * * * *" : schedule.kind === "daily" ? minute + " " + hour + " * * *" : minute + " " + hour + " * * " + day };
|
|
37392
37246
|
}
|
|
37393
37247
|
|
|
37248
|
+
// ../sdk/dist/local-identity.js
|
|
37249
|
+
import { createHash as createHash3, randomBytes as randomBytes2, randomUUID as randomUUID4 } from "node:crypto";
|
|
37250
|
+
|
|
37394
37251
|
// ../sdk/dist/application-auth.js
|
|
37395
37252
|
import { createPublicKey, verify } from "node:crypto";
|
|
37396
37253
|
var ApplicationAuthenticationError = class extends Error {
|
|
@@ -37480,86 +37337,495 @@ function createApplicationAuthProvider(source, options) {
|
|
|
37480
37337
|
unavailable();
|
|
37481
37338
|
return value;
|
|
37482
37339
|
};
|
|
37483
|
-
let current;
|
|
37484
|
-
const load = () => {
|
|
37485
|
-
try {
|
|
37486
|
-
if (typeof window !== "undefined")
|
|
37487
|
-
unavailable();
|
|
37488
|
-
const input = structuredClone(typeof source === "function" ? source() : source);
|
|
37489
|
-
const content = JSON.stringify(input);
|
|
37490
|
-
const time3 = now();
|
|
37491
|
-
if (Buffer.byteLength(content) > 128 * 1024 || !object2(input) || Object.keys(input).some((key) => !["version", "revision", "scope", "issuer", "audience", "validUntil", "keys"].includes(key)) || input.version !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || !scopeValid(input.scope) || !sameScope(input.scope, expectedScope) || !text(input.issuer, 512) || !text(input.audience, 512) || !Number.isSafeInteger(input.validUntil) || input.validUntil <= time3 || input.validUntil > time3 + 86400 || !Array.isArray(input.keys) || input.keys.length < 1 || input.keys.length > 8)
|
|
37492
|
-
unavailable();
|
|
37493
|
-
const issuer = new URL(input.issuer);
|
|
37494
|
-
if (issuer.protocol !== "https:" || issuer.username || issuer.password || issuer.search || issuer.hash)
|
|
37495
|
-
unavailable();
|
|
37496
|
-
if (current && (input.revision < current.trust.revision || input.revision === current.trust.revision && content !== current.content))
|
|
37497
|
-
unavailable();
|
|
37498
|
-
if (current?.content === content) {
|
|
37499
|
-
options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
|
|
37500
|
-
return current;
|
|
37340
|
+
let current;
|
|
37341
|
+
const load = () => {
|
|
37342
|
+
try {
|
|
37343
|
+
if (typeof window !== "undefined")
|
|
37344
|
+
unavailable();
|
|
37345
|
+
const input = structuredClone(typeof source === "function" ? source() : source);
|
|
37346
|
+
const content = JSON.stringify(input);
|
|
37347
|
+
const time3 = now();
|
|
37348
|
+
if (Buffer.byteLength(content) > 128 * 1024 || !object2(input) || Object.keys(input).some((key) => !["version", "revision", "scope", "issuer", "audience", "validUntil", "keys"].includes(key)) || input.version !== 1 || !Number.isSafeInteger(input.revision) || input.revision < 1 || !scopeValid(input.scope) || !sameScope(input.scope, expectedScope) || !text(input.issuer, 512) || !text(input.audience, 512) || !Number.isSafeInteger(input.validUntil) || input.validUntil <= time3 || input.validUntil > time3 + 86400 || !Array.isArray(input.keys) || input.keys.length < 1 || input.keys.length > 8)
|
|
37349
|
+
unavailable();
|
|
37350
|
+
const issuer = new URL(input.issuer);
|
|
37351
|
+
if (issuer.protocol !== "https:" || issuer.username || issuer.password || issuer.search || issuer.hash)
|
|
37352
|
+
unavailable();
|
|
37353
|
+
if (current && (input.revision < current.trust.revision || input.revision === current.trust.revision && content !== current.content))
|
|
37354
|
+
unavailable();
|
|
37355
|
+
if (current?.content === content) {
|
|
37356
|
+
options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
|
|
37357
|
+
return current;
|
|
37358
|
+
}
|
|
37359
|
+
const keys = /* @__PURE__ */ new Map();
|
|
37360
|
+
for (const entry of input.keys) {
|
|
37361
|
+
if (!object2(entry) || Object.keys(entry).some((key2) => !["id", "publicKeyPem"].includes(key2)) || typeof entry.id !== "string" || !/^[a-zA-Z0-9_-]{1,64}$/.test(entry.id) || keys.has(entry.id) || typeof entry.publicKeyPem !== "string" || entry.publicKeyPem.length > 16384 || entry.publicKeyPem.includes("PRIVATE KEY") || !/^-----BEGIN (?:RSA )?PUBLIC KEY-----\r?\n/.test(entry.publicKeyPem))
|
|
37362
|
+
unavailable();
|
|
37363
|
+
const key = createPublicKey(entry.publicKeyPem);
|
|
37364
|
+
const bits2 = key.asymmetricKeyDetails?.modulusLength ?? 0;
|
|
37365
|
+
if (key.asymmetricKeyType !== "rsa" || bits2 < 2048 || bits2 > 8192)
|
|
37366
|
+
unavailable();
|
|
37367
|
+
keys.set(entry.id, key);
|
|
37368
|
+
}
|
|
37369
|
+
options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
|
|
37370
|
+
current = { trust: input, content, keys };
|
|
37371
|
+
return current;
|
|
37372
|
+
} catch {
|
|
37373
|
+
return unavailable();
|
|
37374
|
+
}
|
|
37375
|
+
};
|
|
37376
|
+
load();
|
|
37377
|
+
return {
|
|
37378
|
+
forRequest(request) {
|
|
37379
|
+
const authorization = request.headers.get("authorization");
|
|
37380
|
+
const identity = () => {
|
|
37381
|
+
const { trust, keys } = load();
|
|
37382
|
+
if (authorization === null)
|
|
37383
|
+
return null;
|
|
37384
|
+
if (authorization.length > 16384)
|
|
37385
|
+
invalid();
|
|
37386
|
+
const match = /^Bearer ([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/i.exec(authorization);
|
|
37387
|
+
if (!match)
|
|
37388
|
+
invalid();
|
|
37389
|
+
const header = json(match[1]);
|
|
37390
|
+
fields(header, ["alg", "typ", "kid"]);
|
|
37391
|
+
if (header.alg !== "RS256" || header.typ !== "backify-user+jwt" || typeof header.kid !== "string")
|
|
37392
|
+
invalid();
|
|
37393
|
+
const key = keys.get(header.kid);
|
|
37394
|
+
if (!key)
|
|
37395
|
+
invalid();
|
|
37396
|
+
const signature = Buffer.from(match[3], "base64url");
|
|
37397
|
+
if (signature.toString("base64url") !== match[3] || signature.length !== key.asymmetricKeyDetails.modulusLength / 8 || !verify("RSA-SHA256", Buffer.from(match[1] + "." + match[2]), key, signature))
|
|
37398
|
+
invalid();
|
|
37399
|
+
const payload = json(match[2]);
|
|
37400
|
+
fields(payload, ["ver", "iss", "aud", "sub", "organization_id", "application_id", "environment_id", "iat", "nbf", "exp", "jti", "display_name", "email", "organization_name", "roles"]);
|
|
37401
|
+
const time3 = now();
|
|
37402
|
+
if (payload.ver !== 1 || payload.iss !== trust.issuer || payload.aud !== trust.audience || !uuid(payload.sub) || payload.organization_id !== expectedScope.organizationId || payload.application_id !== expectedScope.applicationId || payload.environment_id !== expectedScope.environmentId || !uuid(payload.jti) || !Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.nbf) || !Number.isSafeInteger(payload.exp))
|
|
37403
|
+
invalid();
|
|
37404
|
+
const issued = payload.iat, notBefore = payload.nbf, expires = payload.exp;
|
|
37405
|
+
if (issued < 0 || issued > time3 || notBefore !== issued || expires <= time3 || expires <= issued || expires - issued > 300 || !text(payload.display_name, 200) || !text(payload.organization_name, 200) || payload.email !== void 0 && !text(payload.email, 320))
|
|
37406
|
+
invalid();
|
|
37407
|
+
return {
|
|
37408
|
+
user: { id: payload.sub, displayName: payload.display_name, ...payload.email === void 0 ? {} : { email: payload.email }, roles: roles(payload.roles), claims: { organizationId: expectedScope.organizationId, applicationId: expectedScope.applicationId, environmentId: expectedScope.environmentId } },
|
|
37409
|
+
organization: { id: expectedScope.organizationId, name: payload.organization_name }
|
|
37410
|
+
};
|
|
37411
|
+
};
|
|
37412
|
+
return { currentUser: async () => identity()?.user ?? null, currentOrganization: async () => identity()?.organization ?? null };
|
|
37413
|
+
}
|
|
37414
|
+
};
|
|
37415
|
+
}
|
|
37416
|
+
|
|
37417
|
+
// ../sdk/dist/local-identity.js
|
|
37418
|
+
function createLocalIdentityProvider(options) {
|
|
37419
|
+
const serverOnly = () => {
|
|
37420
|
+
if (typeof window !== "undefined")
|
|
37421
|
+
throw new Error("Local development identities are server-only");
|
|
37422
|
+
};
|
|
37423
|
+
serverOnly();
|
|
37424
|
+
if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
|
|
37425
|
+
throw new Error("Local Backify identities must not run in production");
|
|
37426
|
+
const uuid5 = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
37427
|
+
const text3 = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
|
|
37428
|
+
if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid5(options.scope.organizationId) || !uuid5(options.scope.applicationId) || !uuid5(options.scope.environmentId) || !text3(options.organizationName, 200) || !Array.isArray(options.users) || options.users.length < 1 || options.users.length > 32 || !Array.isArray(options.requestOrigins) || options.requestOrigins.length < 1 || options.requestOrigins.length > 8)
|
|
37429
|
+
throw new Error("Invalid local identity configuration");
|
|
37430
|
+
const scope = { ...options.scope }, organizationName = options.organizationName;
|
|
37431
|
+
const users = /* @__PURE__ */ new Map();
|
|
37432
|
+
for (const user of options.users) {
|
|
37433
|
+
if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid5(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
|
|
37434
|
+
throw new Error("Invalid local identity user");
|
|
37435
|
+
if (user.roles !== void 0 && (!Array.isArray(user.roles) || user.roles.length > 32 || user.roles.some((role) => !role || Object.keys(role).some((name2) => !["name", "permissions"].includes(name2)) || !text3(role.name, 100) || !Array.isArray(role.permissions) || role.permissions.length > 128 || role.permissions.some((permission) => !text3(permission, 100)) || new Set(role.permissions).size !== role.permissions.length) || new Set(user.roles.map((role) => role.name)).size !== user.roles.length))
|
|
37436
|
+
throw new Error("Invalid local identity roles");
|
|
37437
|
+
users.set(user.id, structuredClone(user));
|
|
37438
|
+
}
|
|
37439
|
+
const origins = /* @__PURE__ */ new Set();
|
|
37440
|
+
for (const value of options.requestOrigins) {
|
|
37441
|
+
let origin;
|
|
37442
|
+
try {
|
|
37443
|
+
origin = new URL(value);
|
|
37444
|
+
} catch {
|
|
37445
|
+
throw new Error("Invalid local identity origin");
|
|
37446
|
+
}
|
|
37447
|
+
if (!["http:", "https:"].includes(origin.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) || origin.origin !== value || origin.username || origin.password || origins.has(value))
|
|
37448
|
+
throw new Error("Local identities require exact loopback origins");
|
|
37449
|
+
origins.add(value);
|
|
37450
|
+
}
|
|
37451
|
+
const clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
37452
|
+
const now = () => {
|
|
37453
|
+
serverOnly();
|
|
37454
|
+
const value = clock();
|
|
37455
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > 253402300499)
|
|
37456
|
+
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
37457
|
+
return value;
|
|
37458
|
+
};
|
|
37459
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
37460
|
+
const digest4 = (token) => createHash3("sha256").update(token).digest("hex");
|
|
37461
|
+
const tokenPattern = /^backify-local-user_[a-zA-Z0-9_-]{43}$/;
|
|
37462
|
+
const requestAuth = {
|
|
37463
|
+
forRequest(request) {
|
|
37464
|
+
serverOnly();
|
|
37465
|
+
const authorization = request.headers.get("authorization"), origin = new URL(request.url).origin;
|
|
37466
|
+
const identity = () => {
|
|
37467
|
+
const time3 = now();
|
|
37468
|
+
if (!origins.has(origin))
|
|
37469
|
+
throw new ApplicationAuthenticationError("application_identity_invalid");
|
|
37470
|
+
if (authorization === null)
|
|
37471
|
+
return null;
|
|
37472
|
+
const match = /^Bearer (backify-local-user_[a-zA-Z0-9_-]{43})$/i.exec(authorization);
|
|
37473
|
+
const session = match && tokenPattern.test(match[1]) ? sessions.get(digest4(match[1])) : void 0;
|
|
37474
|
+
if (!session || session.issued > time3 || session.expires <= time3)
|
|
37475
|
+
throw new ApplicationAuthenticationError("application_identity_invalid");
|
|
37476
|
+
const user = users.get(session.userId);
|
|
37477
|
+
return { ...structuredClone(user), roles: structuredClone(user.roles ?? []), claims: { ...scope, localDevelopment: true } };
|
|
37478
|
+
};
|
|
37479
|
+
return { currentUser: async () => identity(), currentOrganization: async () => identity() ? { id: scope.organizationId, name: organizationName } : null };
|
|
37480
|
+
}
|
|
37481
|
+
};
|
|
37482
|
+
return {
|
|
37483
|
+
requestAuth,
|
|
37484
|
+
profiles() {
|
|
37485
|
+
serverOnly();
|
|
37486
|
+
return [...users.values()].map((user) => structuredClone(user));
|
|
37487
|
+
},
|
|
37488
|
+
issue(userId, lifetimeSeconds = 300) {
|
|
37489
|
+
const time3 = now();
|
|
37490
|
+
if (!users.has(userId) || !Number.isInteger(lifetimeSeconds) || lifetimeSeconds < 1 || lifetimeSeconds > 300)
|
|
37491
|
+
throw new Error("Invalid local identity issuance");
|
|
37492
|
+
for (const [hash2, session] of sessions)
|
|
37493
|
+
if (session.expires <= time3)
|
|
37494
|
+
sessions.delete(hash2);
|
|
37495
|
+
if (sessions.size >= 128)
|
|
37496
|
+
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
37497
|
+
const accessToken = "backify-local-user_" + randomBytes2(32).toString("base64url"), expires = time3 + lifetimeSeconds;
|
|
37498
|
+
sessions.set(digest4(accessToken), { userId, issued: time3, expires });
|
|
37499
|
+
return { accessToken, tokenType: "Bearer", expiresAt: new Date(expires * 1e3).toISOString() };
|
|
37500
|
+
},
|
|
37501
|
+
revoke(accessToken) {
|
|
37502
|
+
serverOnly();
|
|
37503
|
+
return typeof accessToken === "string" && tokenPattern.test(accessToken) && sessions.delete(digest4(accessToken));
|
|
37504
|
+
},
|
|
37505
|
+
clear() {
|
|
37506
|
+
serverOnly();
|
|
37507
|
+
sessions.clear();
|
|
37508
|
+
}
|
|
37509
|
+
};
|
|
37510
|
+
}
|
|
37511
|
+
function createLocalEmailAuth(options, crypto2 = { createHash: createHash3, randomBytes: randomBytes2, randomUUID: randomUUID4 }) {
|
|
37512
|
+
const { createHash: createHash17, randomBytes: randomBytes7, randomUUID: randomUUID13 } = crypto2;
|
|
37513
|
+
const origin = new URL(options.origin);
|
|
37514
|
+
if (typeof window !== "undefined" || process.env.NODE_ENV === "production" || !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) || !["http:", "https:"].includes(origin.protocol) || options.origin !== origin.origin)
|
|
37515
|
+
throw new Error("Local email authentication requires an exact loopback origin outside production");
|
|
37516
|
+
const clock = options.now ?? (() => Date.now());
|
|
37517
|
+
const challenges = /* @__PURE__ */ new Map();
|
|
37518
|
+
const inbox = [];
|
|
37519
|
+
const starts = /* @__PURE__ */ new Map();
|
|
37520
|
+
const hash2 = (value) => createHash17("sha256").update(value).digest("hex");
|
|
37521
|
+
const random2 = () => randomBytes7(32).toString("base64url");
|
|
37522
|
+
const cookie = (name2, value, seconds) => name2 + "=" + value + "; HttpOnly; SameSite=Strict; Path=/; Max-Age=" + seconds + (origin.protocol === "https:" ? "; Secure" : "");
|
|
37523
|
+
const readCookie = (request, name2) => request.headers.get("cookie")?.split(";").map((item) => item.trim()).find((item) => item.startsWith(name2 + "="))?.slice(name2.length + 1) ?? "";
|
|
37524
|
+
const json4 = (value, status = 200, headers = {}) => Response.json(value, { status, headers: { "cache-control": "no-store", ...headers } });
|
|
37525
|
+
const page = (body, headers = {}) => new Response("<!doctype html><html><head><title>Local email sign-in</title></head><body><h1>Local email sign-in</h1>" + body + "</body></html>", { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "strict-origin", "content-security-policy": "default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", ...headers } });
|
|
37526
|
+
const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
37527
|
+
return {
|
|
37528
|
+
inbox() {
|
|
37529
|
+
return structuredClone(inbox);
|
|
37530
|
+
},
|
|
37531
|
+
async handle(request) {
|
|
37532
|
+
const url2 = new URL(request.url);
|
|
37533
|
+
if (url2.origin !== origin.origin || !url2.pathname.startsWith("/.backify/auth/"))
|
|
37534
|
+
return json4({ error: "invalid_local_origin" }, 403);
|
|
37535
|
+
if (request.method === "POST" && request.headers.get("origin") !== origin.origin)
|
|
37536
|
+
return json4({ error: "invalid_local_origin" }, 403);
|
|
37537
|
+
const path = url2.pathname.slice("/.backify/auth/".length);
|
|
37538
|
+
const ticket = readCookie(request, "backify_local_session");
|
|
37539
|
+
let user = null;
|
|
37540
|
+
try {
|
|
37541
|
+
user = await options.identity.requestAuth.forRequest(new Request(origin.origin, { headers: ticket ? { authorization: "Bearer " + ticket } : {} })).currentUser();
|
|
37542
|
+
} catch {
|
|
37543
|
+
}
|
|
37544
|
+
if (request.method === "GET" && path === "me")
|
|
37545
|
+
return json4(user);
|
|
37546
|
+
if (request.method === "GET" && path === "organization")
|
|
37547
|
+
return json4(user ? { id: user.claims?.organizationId, name: "Local development" } : null);
|
|
37548
|
+
if (request.method === "POST" && path === "access-token")
|
|
37549
|
+
return user ? json4({ accessToken: ticket, tokenType: "Bearer", expiresAt: new Date(clock() + 6e4).toISOString() }) : json4({ error: "authentication_required" }, 401);
|
|
37550
|
+
if (request.method === "POST" && path === "signout") {
|
|
37551
|
+
options.identity.revoke(ticket);
|
|
37552
|
+
return new Response(null, { status: 204, headers: { "set-cookie": cookie("backify_local_session", "", 0), "cache-control": "no-store" } });
|
|
37553
|
+
}
|
|
37554
|
+
if (request.method === "GET" && path === "login")
|
|
37555
|
+
return page("<p>Use an email from your reviewed local identity fixtures. Read the captured link with <code>backify identity inbox --local</code>. No email is sent.</p><form method='post' action='/.backify/auth/email/request'><label>Email <input type='email' name='email' required></label><button>Send magic link</button></form>");
|
|
37556
|
+
if (request.method === "POST" && (path === "email/start" || path === "email/request")) {
|
|
37557
|
+
if (Number(request.headers.get("content-length") ?? 0) > 4096)
|
|
37558
|
+
return json4({ error: "request_too_large" }, 413);
|
|
37559
|
+
const body = await request.text();
|
|
37560
|
+
if (body.length > 4096)
|
|
37561
|
+
return json4({ error: "request_too_large" }, 413);
|
|
37562
|
+
let input;
|
|
37563
|
+
try {
|
|
37564
|
+
input = path === "email/request" ? Object.fromEntries(new URLSearchParams(body)) : JSON.parse(body);
|
|
37565
|
+
} catch {
|
|
37566
|
+
return json4({ error: "invalid_email_request" }, 400);
|
|
37567
|
+
}
|
|
37568
|
+
if (!input || typeof input.email !== "string" || input.email.length > 320 || input.method !== void 0 && input.method !== "magic-link")
|
|
37569
|
+
return json4({ error: "local_magic_links_only" }, 400);
|
|
37570
|
+
const email2 = input.email.trim().toLowerCase();
|
|
37571
|
+
const recent = (starts.get(email2) ?? []).filter((time3) => time3 > clock() - 6e4);
|
|
37572
|
+
if (recent.length >= 5 || starts.size >= 256 && !starts.has(email2))
|
|
37573
|
+
return json4({ error: "rate_limited" }, 429);
|
|
37574
|
+
starts.set(email2, [...recent, clock()]);
|
|
37575
|
+
for (const [id2, challenge] of challenges)
|
|
37576
|
+
if (challenge.expires <= clock())
|
|
37577
|
+
challenges.delete(id2);
|
|
37578
|
+
if (challenges.size >= 128)
|
|
37579
|
+
return json4({ error: "rate_limited" }, 429);
|
|
37580
|
+
const id = randomUUID13(), proof = random2(), secret = random2();
|
|
37581
|
+
const profile = options.identity.profiles().find((item) => item.email?.toLowerCase() === email2);
|
|
37582
|
+
if (profile) {
|
|
37583
|
+
challenges.set(id, { userId: profile.id, proof: hash2(proof), token: hash2(secret), expires: clock() + 6e5 });
|
|
37584
|
+
inbox.push({ email: email2, text: origin.origin + "/.backify/auth/email/link?id=" + id + "&code=" + secret, createdAt: new Date(clock()).toISOString() });
|
|
37585
|
+
if (inbox.length > 128)
|
|
37586
|
+
inbox.shift();
|
|
37587
|
+
}
|
|
37588
|
+
const headers = { "set-cookie": cookie("backify_local_email_proof", proof, 600) };
|
|
37589
|
+
return path === "email/request" ? page("<p>Check the private local inbox. Open the magic link in this browser.</p>", headers) : json4({ challengeId: id, status: "check_email" }, 202, headers);
|
|
37590
|
+
}
|
|
37591
|
+
if (request.method === "GET" && path === "email/link") {
|
|
37592
|
+
const id = url2.searchParams.get("id") ?? "", secret = url2.searchParams.get("code") ?? "";
|
|
37593
|
+
if (!/^[a-f0-9-]{36}$/.test(id) || !tokenPattern.test(secret))
|
|
37594
|
+
return json4({ error: "invalid_email_link" }, 400);
|
|
37595
|
+
return page("<form method='post' action='/.backify/auth/email/confirm'><input type='hidden' name='id' value='" + id + "'><input type='hidden' name='code' value='" + secret + "'><button>Confirm local sign-in</button></form>");
|
|
37596
|
+
}
|
|
37597
|
+
if (request.method === "POST" && path === "email/confirm") {
|
|
37598
|
+
const body = await request.text();
|
|
37599
|
+
if (body.length > 4096)
|
|
37600
|
+
return json4({ error: "request_too_large" }, 413);
|
|
37601
|
+
const input = new URLSearchParams(body), id = input.get("id") ?? "", secret = input.get("code") ?? "";
|
|
37602
|
+
const challenge = challenges.get(id), proof = readCookie(request, "backify_local_email_proof");
|
|
37603
|
+
if (!challenge || challenge.expires <= clock() || !tokenPattern.test(secret) || !tokenPattern.test(proof) || challenge.proof !== hash2(proof) || challenge.token !== hash2(secret))
|
|
37604
|
+
return json4({ error: "invalid_email_link" }, 400);
|
|
37605
|
+
challenges.delete(id);
|
|
37606
|
+
const identity = options.identity.issue(challenge.userId);
|
|
37607
|
+
return new Response(null, { status: 303, headers: { location: "/", "set-cookie": cookie("backify_local_session", identity.accessToken, 300), "cache-control": "no-store" } });
|
|
37608
|
+
}
|
|
37609
|
+
return json4({ error: "local_auth_route_unavailable" }, 404);
|
|
37610
|
+
}
|
|
37611
|
+
};
|
|
37612
|
+
}
|
|
37613
|
+
|
|
37614
|
+
// src/local-inspection.ts
|
|
37615
|
+
function createLocalDataInspector(runtime, options) {
|
|
37616
|
+
const tableName = (value) => typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(value) && !/^__backify/i.test(value);
|
|
37617
|
+
const bucketName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(value);
|
|
37618
|
+
if (typeof window !== "undefined" || options.buckets.length > 100 || options.buckets.some((name2) => !bucketName(name2)) || new Set(options.buckets).size !== options.buckets.length) throw new Error("invalid_local_inspection");
|
|
37619
|
+
const fail = () => {
|
|
37620
|
+
throw new Error("invalid_local_inspection");
|
|
37621
|
+
};
|
|
37622
|
+
const unavailable4 = () => {
|
|
37623
|
+
throw new Error("local_inspection_unavailable");
|
|
37624
|
+
};
|
|
37625
|
+
const providerRequest = async (operation, missingObject = false) => {
|
|
37626
|
+
try {
|
|
37627
|
+
return await operation();
|
|
37628
|
+
} catch (error2) {
|
|
37629
|
+
const status = error2?.status;
|
|
37630
|
+
if (status === 413) throw new Error("local_inspection_too_large");
|
|
37631
|
+
if (status === 400) fail();
|
|
37632
|
+
if (status === 404 && missingObject) throw new Error("local_inspection_not_found");
|
|
37633
|
+
return unavailable4();
|
|
37634
|
+
}
|
|
37635
|
+
};
|
|
37636
|
+
const object7 = (value, fields5) => {
|
|
37637
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !fields5.includes(name2))) fail();
|
|
37638
|
+
return value;
|
|
37639
|
+
};
|
|
37640
|
+
const page = (input) => {
|
|
37641
|
+
const limit = input.limit ?? 25, offset = input.offset ?? 0;
|
|
37642
|
+
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 50 || typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > 1e4) fail();
|
|
37643
|
+
return { limit, offset };
|
|
37644
|
+
};
|
|
37645
|
+
const bounded = (value) => {
|
|
37646
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 65536) throw new Error("local_inspection_too_large");
|
|
37647
|
+
return value;
|
|
37648
|
+
};
|
|
37649
|
+
const redact = (value, depth = 0) => {
|
|
37650
|
+
if (depth > 20) return "[DEPTH LIMIT]";
|
|
37651
|
+
if (Array.isArray(value)) return value.map((item) => redact(item, depth + 1));
|
|
37652
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name2, item]) => [name2, /(?:password|secret|token|credential|private.?key|connection.?string)/i.test(name2) ? "[REDACTED]" : redact(item, depth + 1)]));
|
|
37653
|
+
return value;
|
|
37654
|
+
};
|
|
37655
|
+
const requireBucket = (name2) => {
|
|
37656
|
+
if (!options.storageEnabled) unavailable4();
|
|
37657
|
+
const known = [...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)];
|
|
37658
|
+
if (!bucketName(name2) || !known.includes(name2)) fail();
|
|
37659
|
+
return name2;
|
|
37660
|
+
};
|
|
37661
|
+
return {
|
|
37662
|
+
async tables() {
|
|
37663
|
+
if (!options.databaseEnabled) unavailable4();
|
|
37664
|
+
if (runtime.database.listTables) return bounded(await providerRequest(() => runtime.database.listTables()));
|
|
37665
|
+
if (options.nativeDatabase) unavailable4();
|
|
37666
|
+
const names = runtime.inspect().tables.map((table) => table.name).filter(tableName).sort();
|
|
37667
|
+
return { names: names.slice(0, 100), hasMore: names.length > 100 };
|
|
37668
|
+
},
|
|
37669
|
+
async rows(value) {
|
|
37670
|
+
if (!options.databaseEnabled) unavailable4();
|
|
37671
|
+
const input = object7(value, ["table", "limit", "offset"]), pagination = page(input);
|
|
37672
|
+
if (!tableName(input.table)) fail();
|
|
37673
|
+
if (runtime.database.inspectRows) {
|
|
37674
|
+
const result = await providerRequest(() => runtime.database.inspectRows(input.table, pagination));
|
|
37675
|
+
return bounded({ ...result, rows: result.rows.map((row) => redact(row)) });
|
|
37676
|
+
}
|
|
37677
|
+
if (options.nativeDatabase) unavailable4();
|
|
37678
|
+
const rows = await runtime.database.query(input.table, { filters: [], limit: pagination.limit + 1, offset: pagination.offset });
|
|
37679
|
+
return bounded({ rows: rows.slice(0, pagination.limit).map((row) => redact(row)), ...pagination, nextOffset: rows.length > pagination.limit && pagination.offset + pagination.limit <= 1e4 ? pagination.offset + pagination.limit : null });
|
|
37680
|
+
},
|
|
37681
|
+
buckets() {
|
|
37682
|
+
if (!options.storageEnabled) unavailable4();
|
|
37683
|
+
return bounded({ names: [.../* @__PURE__ */ new Set([...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)])].filter(bucketName).sort().slice(0, 100) });
|
|
37684
|
+
},
|
|
37685
|
+
async objects(value) {
|
|
37686
|
+
const input = object7(value, ["bucket", "prefix", "limit", "offset"]), pagination = page(input);
|
|
37687
|
+
const name2 = requireBucket(input.bucket);
|
|
37688
|
+
if (input.prefix !== void 0 && (typeof input.prefix !== "string" || input.prefix.length > 512 || /[\\\x00-\x1f\x7f]/.test(input.prefix) || input.prefix.startsWith("/") || input.prefix.split("/").some((part) => part === "." || part === ".."))) fail();
|
|
37689
|
+
const objects = await providerRequest(() => runtime.storage.list(name2, input.prefix));
|
|
37690
|
+
if (objects.length > 1e3) throw new Error("local_inspection_too_large");
|
|
37691
|
+
objects.sort((first, second) => first.key.localeCompare(second.key));
|
|
37692
|
+
return bounded({ objects: objects.slice(pagination.offset, pagination.offset + pagination.limit), ...pagination, nextOffset: objects.length > pagination.offset + pagination.limit ? pagination.offset + pagination.limit : null });
|
|
37693
|
+
},
|
|
37694
|
+
async preview(value) {
|
|
37695
|
+
const input = object7(value, ["bucket", "key"]), name2 = requireBucket(input.bucket);
|
|
37696
|
+
if (typeof input.key !== "string" || !input.key || input.key.length > 512 || input.key.startsWith("/") || /[\\\x00-\x1f\x7f]/.test(input.key) || input.key.split("/").some((part) => part === "." || part === "..")) fail();
|
|
37697
|
+
if (!options.nativeStorage && !await runtime.storage.exists(name2, input.key)) throw new Error("local_inspection_not_found");
|
|
37698
|
+
const bytes = await providerRequest(() => runtime.storage.download(name2, input.key), true);
|
|
37699
|
+
if (bytes.byteLength > 16384) return { kind: "too-large", size: bytes.byteLength, maximumPreviewBytes: 16384 };
|
|
37700
|
+
try {
|
|
37701
|
+
const text3 = new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
37702
|
+
if (text3.includes("\0")) throw new Error("Binary object");
|
|
37703
|
+
return bounded({ kind: "text", size: bytes.byteLength, text: text3 });
|
|
37704
|
+
} catch (error2) {
|
|
37705
|
+
if (error2 instanceof Error && error2.message === "local_inspection_too_large") throw error2;
|
|
37706
|
+
return { kind: "binary", size: bytes.byteLength, bytes: [...bytes.slice(0, 64)], truncated: bytes.byteLength > 64 };
|
|
37707
|
+
}
|
|
37708
|
+
}
|
|
37709
|
+
};
|
|
37710
|
+
}
|
|
37711
|
+
|
|
37712
|
+
// src/local-dashboard.ts
|
|
37713
|
+
var dashboardHtml = String.raw`<!doctype html>
|
|
37714
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Backify Local</title>
|
|
37715
|
+
<style>body{font:16px system-ui;max-width:1100px;margin:30px auto;padding:20px;background:#10131a;color:#ecf1ff}button,select,input,textarea{font:inherit;padding:8px;margin:4px;border:1px solid #8ca1bc;border-radius:5px}button{cursor:pointer}button:disabled{cursor:wait;opacity:.6}button:focus-visible,select:focus-visible,input:focus-visible,textarea:focus-visible{outline:3px solid #78baff}nav{display:flex;flex-wrap:wrap;margin-bottom:20px}section{padding:16px;border:1px solid #36465f;border-radius:8px;margin:12px 0}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#171f2b;padding:16px;border-radius:6px}label{display:inline-block;margin:4px}p{line-height:1.5;color:#bdcbe0}#message{min-height:24px;color:#f5c575}[hidden]{display:none!important}textarea{display:block;width:30em;max-width:100%;min-height:80px}</style></head>
|
|
37716
|
+
<body><h1>Backify Local Development</h1><p>Application data stays on this computer. This is a local operator dashboard, not an application user's login or a production portal.</p>
|
|
37717
|
+
<nav aria-label="Inspection panels"><button data-panel="overview">Overview</button><button data-panel="data">Data</button><button data-panel="jobs">Jobs</button><button data-panel="events">Events</button><button data-panel="logs">Logs</button></nav>
|
|
37718
|
+
<p id="message" role="status" aria-live="polite">Open this dashboard using backify dev --open to authenticate.</p>
|
|
37719
|
+
<section id="overview"><h2>Supervisor and endpoints</h2><p>A responding endpoint is not proof of provider health. Database and storage data are inspected explicitly in the Data panel.</p><button id="refresh">Refresh status</button><pre id="state" aria-label="Local status"></pre></section>
|
|
37720
|
+
<section id="data" hidden><h2>Read-only data inspection</h2><p>At most 100 public database table names and 50 rows per page are supported. Common credential-named row fields are redacted; this is not comprehensive secret classification. Object contents require an explicit preview request. No data mutation controls are provided.</p>
|
|
37721
|
+
<h3>Database</h3><button id="load-tables">Load tables</button><label>Table <select id="tables" aria-label="Database table"></select></label><button id="load-rows">Inspect rows</button><button id="next-rows" disabled>Next row page</button><pre id="rows" aria-label="Database rows"></pre>
|
|
37722
|
+
<h3>Private storage</h3><button id="load-buckets">Load buckets</button><label>Bucket <select id="buckets" aria-label="Storage bucket"></select></label><label>Prefix <input id="prefix" maxlength="512"></label><button id="load-objects">List objects</button><button id="next-objects" disabled>Next object page</button><pre id="objects" aria-label="Storage objects"></pre><label>Object <select id="keys" aria-label="Storage object"></select></label><button id="preview">Preview selected object</button><pre id="object-preview" aria-label="Object preview"></pre></section>
|
|
37723
|
+
<section id="jobs" hidden><h2>Declared jobs and retained history</h2><p>These are local operator actions, not application-user permissions. Retries create a new run and may repeat business side effects. Do not enter credentials in job payloads.</p><button id="load-jobs">Refresh jobs</button><label>Job <select id="job-name" aria-label="Declared job"></select></label><label>Payload <textarea id="job-payload" aria-label="Job payload (JSON)" maxlength="32768" placeholder="Optional JSON, otherwise null"></textarea></label><button id="run-job">Run selected job</button><h3>Schedules</h3><label>Schedule <select id="schedule-id" aria-label="Declared schedule"></select></label><button id="pause-schedule" disabled>Pause selected schedule</button><button id="resume-schedule" disabled>Resume selected schedule</button><h3>Run recovery</h3><label>Run <select id="run-id" aria-label="Recoverable run"></select></label><button id="retry-run" disabled>Retry failed run</button><button id="cancel-run" disabled>Cancel selected run</button><pre id="job-state" aria-label="Job history"></pre></section>
|
|
37724
|
+
<section id="logs" hidden><h2>Local logs</h2><button id="load-logs">Refresh logs</button><pre id="log-state" aria-label="Local logs"></pre></section>
|
|
37725
|
+
<section id="events" hidden><h2>Local event activity</h2><p>Latest 100 delivery metadata rows and retained status counts. Payloads, idempotency keys and lease receipts are never shown. Lightweight mode preserves snapshot leases. Full mode uses a native PostgreSQL inbox and drains retained snapshot records without renaming or deleting them. Local hooks and retained drainage are single-worker, not distributed cloud subscriptions. No acknowledgement or destructive controls are exposed.</p><button id="load-events">Refresh events</button><pre id="event-state" aria-label="Local event activity"></pre></section>
|
|
37726
|
+
<script>
|
|
37727
|
+
const token=new URLSearchParams(location.hash.slice(1)).get("session");
|
|
37728
|
+
history.replaceState(null,"",location.pathname);
|
|
37729
|
+
const element=id=>document.getElementById(id);
|
|
37730
|
+
let rowPage=null,objectPage=null,rowTable="",objectBucket="",objectPrefix="",jobsBusy=false,jobView={jobs:[],schedules:[],runs:[]};
|
|
37731
|
+
const jobActions=["run-job","pause-schedule","resume-schedule","retry-run","cancel-run"];
|
|
37732
|
+
function show(id,value){element(id).textContent=JSON.stringify(value,null,2)}
|
|
37733
|
+
function choices(id,names){element(id).replaceChildren();for(const name of names){const option=document.createElement("option");option.value=name;option.textContent=name;element(id).append(option)}}
|
|
37734
|
+
async function request(path,input){if(!token)throw new Error("Local session required; reopen using backify dev --open.");const response=await fetch(path,{method:input===undefined?"GET":"POST",headers:{authorization:"Bearer "+token,"content-type":"application/json"},body:input===undefined?undefined:JSON.stringify(input),redirect:"error",cache:"no-store",signal:AbortSignal.timeout(35000)});const value=await response.json();if(!response.ok)throw new Error("Inspection failed ("+response.status+"): "+(value.error||"unavailable"));return value}
|
|
37735
|
+
function action(id,handler){element(id).onclick=async()=>{if(jobActions.includes(id)){if(jobsBusy)return;jobsBusy=true;jobControls()}element(id).disabled=true;element("message").textContent="Loading...";try{await handler();element("message").textContent="Updated."}catch(error){element("message").textContent=error instanceof Error?error.message:"Local operation unavailable"}finally{if(jobActions.includes(id)){jobsBusy=false;jobControls()}else element(id).disabled=id==="next-rows"?rowPage===null:id==="next-objects"?objectPage===null:false}}}
|
|
37736
|
+
async function status(){show("state",await request("/v1/status"))}
|
|
37737
|
+
async function rows(offset){const table=element("tables").value;if(!table)throw new Error("Choose a table first.");const result=await request("/v1/database/rows",{table,offset,limit:25});rowTable=table;rowPage=result.nextOffset;show("rows",result);element("next-rows").disabled=rowPage===null}
|
|
37738
|
+
async function objects(offset){const bucket=element("buckets").value,prefix=element("prefix").value;if(!bucket)throw new Error("Choose a bucket first.");const result=await request("/v1/storage/objects",{bucket,prefix,offset,limit:25});objectBucket=bucket;objectPrefix=prefix;objectPage=result.nextOffset;show("objects",result);choices("keys",result.objects.map(value=>value.key));element("next-objects").disabled=objectPage===null;element("object-preview").textContent=""}
|
|
37739
|
+
function records(id,values,label){const selected=element(id).value;element(id).replaceChildren();for(const value of values){const option=document.createElement("option");option.value=value.id;option.textContent=label(value);element(id).append(option)}if(values.some(value=>value.id===selected))element(id).value=selected}
|
|
37740
|
+
function jobControls(){const schedule=jobView.schedules.find(value=>value.id===element("schedule-id").value),run=jobView.runs.find(value=>value.id===element("run-id").value);element("run-job").disabled=jobsBusy||!jobView.jobs.length;element("pause-schedule").disabled=jobsBusy||!schedule||!schedule.enabled;element("resume-schedule").disabled=jobsBusy||!schedule||schedule.enabled;element("retry-run").disabled=jobsBusy||!run||run.status!=="failed"||run.canRetry===false;element("cancel-run").disabled=jobsBusy||!run||!["queued","running","retrying"].includes(run.status)||run.canCancel===false}
|
|
37741
|
+
async function jobs(){const result=await request("/v1/jobs");jobView=result;show("job-state",result);choices("job-name",result.jobs.map(value=>value.name));records("schedule-id",result.schedules,value=>value.name+" ("+(value.enabled?"enabled":"paused")+")");records("run-id",result.runs.filter(value=>["failed","queued","running","retrying"].includes(value.status)),value=>value.id+" - "+value.job+" ("+value.status+")");jobControls()}
|
|
37742
|
+
element("schedule-id").onchange=jobControls;element("run-id").onchange=jobControls;
|
|
37743
|
+
for(const button of document.querySelectorAll("[data-panel]")){button.onclick=()=>{for(const name of ["overview","data","jobs","events","logs"])element(name).hidden=name!==button.dataset.panel}}
|
|
37744
|
+
action("refresh",status);
|
|
37745
|
+
action("load-tables",async()=>{const result=await request("/v1/database/tables");choices("tables",result.names);show("rows",{tables:result.names.length,hasMore:result.hasMore});rowPage=null;element("next-rows").disabled=true});
|
|
37746
|
+
action("load-rows",()=>rows(0));
|
|
37747
|
+
action("next-rows",()=>{if(rowPage===null||rowTable!==element("tables").value)throw new Error("Reload rows after changing the table.");return rows(rowPage)});
|
|
37748
|
+
action("load-buckets",async()=>{const result=await request("/v1/storage/buckets");choices("buckets",result.names);show("objects",result);objectPage=null;element("next-objects").disabled=true});
|
|
37749
|
+
action("load-objects",()=>objects(0));
|
|
37750
|
+
action("next-objects",()=>{if(objectPage===null||objectBucket!==element("buckets").value||objectPrefix!==element("prefix").value)throw new Error("Reload objects after changing bucket or prefix.");return objects(objectPage)});
|
|
37751
|
+
action("preview",async()=>{const bucket=element("buckets").value,key=element("keys").value;if(!key||bucket!==objectBucket)throw new Error("List and choose an object first.");show("object-preview",await request("/v1/storage/preview",{bucket,key}))});
|
|
37752
|
+
action("load-jobs",jobs);
|
|
37753
|
+
action("run-job",async()=>{const name=element("job-name").value;if(!name)throw new Error("Choose a declared job first.");const raw=element("job-payload").value;if(new TextEncoder().encode(raw).length>32768)throw new Error("Job payload exceeds 32 KiB.");let payload=null;try{if(raw.trim())payload=JSON.parse(raw)}catch{throw new Error("Enter valid JSON for the job payload.")}const input={name,payload};if(new TextEncoder().encode(JSON.stringify(input)).length>32768)throw new Error("Job payload exceeds 32 KiB.");await request("/v1/jobs/run",input);element("job-payload").value="";await jobs()});
|
|
37754
|
+
action("pause-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:false});await jobs()});
|
|
37755
|
+
action("resume-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:true});await jobs()});
|
|
37756
|
+
action("retry-run",async()=>{await request("/v1/jobs/retry",{id:element("run-id").value});await jobs()});
|
|
37757
|
+
action("cancel-run",async()=>{await request("/v1/jobs/cancel",{id:element("run-id").value});await jobs()});
|
|
37758
|
+
action("load-logs",async()=>show("log-state",await request("/v1/logs")));
|
|
37759
|
+
action("load-events",async()=>show("event-state",await request("/v1/events")));
|
|
37760
|
+
if(token)status().then(()=>{element("message").textContent="Local session connected."}).catch(error=>{element("message").textContent=error.message});
|
|
37761
|
+
</script></body></html>`;
|
|
37762
|
+
|
|
37763
|
+
// src/local-native-events.ts
|
|
37764
|
+
function createLocalNativeEvents(local, native) {
|
|
37765
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
37766
|
+
const validateName2 = (name2) => {
|
|
37767
|
+
if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2)) throw new Error("Invalid event name");
|
|
37768
|
+
};
|
|
37769
|
+
return {
|
|
37770
|
+
track: (name2, data, options) => {
|
|
37771
|
+
if (!local.track) throw new Error("Upgrade the local SDK to enable event tracking");
|
|
37772
|
+
return local.track(name2, data, options);
|
|
37773
|
+
},
|
|
37774
|
+
async emit(name2, payload, options) {
|
|
37775
|
+
validateName2(name2);
|
|
37776
|
+
if (options?.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || !options.idempotencyKey || options.idempotencyKey.length > 128)) throw new Error("Invalid idempotency key");
|
|
37777
|
+
if (options?.idempotencyKey !== void 0 && (local.hasIdempotencyKey ? local.hasIdempotencyKey(options.idempotencyKey) : local.snapshot().deliveries.some((item) => item.idempotencyKey === options.idempotencyKey))) {
|
|
37778
|
+
await local.emit(name2, payload, options);
|
|
37779
|
+
return;
|
|
37501
37780
|
}
|
|
37502
|
-
|
|
37503
|
-
|
|
37504
|
-
|
|
37505
|
-
|
|
37506
|
-
|
|
37507
|
-
const bits2 = key.asymmetricKeyDetails?.modulusLength ?? 0;
|
|
37508
|
-
if (key.asymmetricKeyType !== "rsa" || bits2 < 2048 || bits2 > 8192)
|
|
37509
|
-
unavailable();
|
|
37510
|
-
keys.set(entry.id, key);
|
|
37781
|
+
let accepted;
|
|
37782
|
+
try {
|
|
37783
|
+
accepted = JSON.parse(JSON.stringify(payload ?? null));
|
|
37784
|
+
} catch {
|
|
37785
|
+
throw new Error("Event payload must be JSON serializable");
|
|
37511
37786
|
}
|
|
37512
|
-
|
|
37513
|
-
|
|
37514
|
-
|
|
37515
|
-
}
|
|
37516
|
-
|
|
37517
|
-
|
|
37518
|
-
|
|
37519
|
-
|
|
37520
|
-
|
|
37521
|
-
|
|
37522
|
-
const
|
|
37523
|
-
|
|
37524
|
-
|
|
37525
|
-
|
|
37526
|
-
|
|
37527
|
-
|
|
37528
|
-
|
|
37529
|
-
|
|
37530
|
-
|
|
37531
|
-
|
|
37532
|
-
|
|
37533
|
-
|
|
37534
|
-
|
|
37535
|
-
|
|
37536
|
-
|
|
37537
|
-
|
|
37538
|
-
|
|
37539
|
-
|
|
37540
|
-
|
|
37541
|
-
invalid();
|
|
37542
|
-
const payload = json(match[2]);
|
|
37543
|
-
fields(payload, ["ver", "iss", "aud", "sub", "organization_id", "application_id", "environment_id", "iat", "nbf", "exp", "jti", "display_name", "email", "organization_name", "roles"]);
|
|
37544
|
-
const time3 = now();
|
|
37545
|
-
if (payload.ver !== 1 || payload.iss !== trust.issuer || payload.aud !== trust.audience || !uuid(payload.sub) || payload.organization_id !== expectedScope.organizationId || payload.application_id !== expectedScope.applicationId || payload.environment_id !== expectedScope.environmentId || !uuid(payload.jti) || !Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.nbf) || !Number.isSafeInteger(payload.exp))
|
|
37546
|
-
invalid();
|
|
37547
|
-
const issued = payload.iat, notBefore = payload.nbf, expires = payload.exp;
|
|
37548
|
-
if (issued < 0 || issued > time3 || notBefore !== issued || expires <= time3 || expires <= issued || expires - issued > 300 || !text(payload.display_name, 200) || !text(payload.organization_name, 200) || payload.email !== void 0 && !text(payload.email, 320))
|
|
37549
|
-
invalid();
|
|
37550
|
-
return {
|
|
37551
|
-
user: { id: payload.sub, displayName: payload.display_name, ...payload.email === void 0 ? {} : { email: payload.email }, roles: roles(payload.roles), claims: { organizationId: expectedScope.organizationId, applicationId: expectedScope.applicationId, environmentId: expectedScope.environmentId } },
|
|
37552
|
-
organization: { id: expectedScope.organizationId, name: payload.organization_name }
|
|
37553
|
-
};
|
|
37554
|
-
};
|
|
37555
|
-
return { currentUser: async () => identity()?.user ?? null, currentOrganization: async () => identity()?.organization ?? null };
|
|
37787
|
+
if (await native.emitAccepted(name2, accepted, options)) {
|
|
37788
|
+
for (const handler of handlers.get(name2) ?? []) await handler(structuredClone(accepted));
|
|
37789
|
+
}
|
|
37790
|
+
},
|
|
37791
|
+
on(name2, handler) {
|
|
37792
|
+
if (typeof name2 !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/.test(name2) || /[\r\n]/.test(name2) || typeof handler !== "function") throw new Error("Invalid local event subscription");
|
|
37793
|
+
handlers.set(name2, [...handlers.get(name2) ?? [], handler]);
|
|
37794
|
+
return () => handlers.set(name2, (handlers.get(name2) ?? []).filter((value) => value !== handler));
|
|
37795
|
+
},
|
|
37796
|
+
async receive(name2, options) {
|
|
37797
|
+
const retained = await local.receive(name2, options);
|
|
37798
|
+
return retained.length ? retained : native.receive(name2, options);
|
|
37799
|
+
},
|
|
37800
|
+
async complete(id, receipt, retry) {
|
|
37801
|
+
if (retry !== void 0 && typeof retry !== "boolean") throw new Error("Invalid local event retry");
|
|
37802
|
+
if (typeof id === "string" && id.startsWith("event_")) await local.complete(id, receipt, retry);
|
|
37803
|
+
else await native.complete(id, receipt, retry);
|
|
37804
|
+
},
|
|
37805
|
+
async inspect() {
|
|
37806
|
+
const retained = local.inspect(), durable = await native.inspect();
|
|
37807
|
+
const counts = { ...retained.counts };
|
|
37808
|
+
for (const status of Object.keys(counts)) {
|
|
37809
|
+
counts[status] += durable.counts[status];
|
|
37810
|
+
if (!Number.isSafeInteger(counts[status])) throw new Error("Local event inspection count exceeds bounds");
|
|
37811
|
+
}
|
|
37812
|
+
const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
|
|
37813
|
+
if (!Number.isSafeInteger(total)) throw new Error("Local event inspection count exceeds bounds");
|
|
37814
|
+
const deliveries = [...retained.deliveries, ...durable.deliveries].sort((first, second) => Date.parse(second.emittedAt) - Date.parse(first.emittedAt) || (first.id < second.id ? 1 : first.id > second.id ? -1 : 0)).slice(0, 100);
|
|
37815
|
+
return { version: 1, counts, deliveries, hasMore: total > deliveries.length };
|
|
37556
37816
|
}
|
|
37557
37817
|
};
|
|
37558
37818
|
}
|
|
37559
37819
|
|
|
37820
|
+
// src/local-job-executor.ts
|
|
37821
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
37822
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
37823
|
+
import { lstatSync as lstatSync12, readFileSync as readFileSync16 } from "node:fs";
|
|
37824
|
+
import { isAbsolute as isAbsolute8, join as join12, relative as relative3, resolve as resolve12 } from "node:path";
|
|
37825
|
+
|
|
37560
37826
|
// ../sdk/dist/application-auth-state.js
|
|
37561
|
-
import { createHash as
|
|
37562
|
-
import { closeSync, constants, fstatSync, fsyncSync, lstatSync as
|
|
37827
|
+
import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
|
|
37828
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync5, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync8 } from "node:fs";
|
|
37563
37829
|
import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve6, sep as sep2 } from "node:path";
|
|
37564
37830
|
function unavailable2() {
|
|
37565
37831
|
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
@@ -37572,14 +37838,14 @@ function safePath(filename2) {
|
|
|
37572
37838
|
const directory2 = dirname6(filename2);
|
|
37573
37839
|
let ancestor = directory2;
|
|
37574
37840
|
for (; ; ) {
|
|
37575
|
-
const metadata =
|
|
37841
|
+
const metadata = lstatSync5(ancestor);
|
|
37576
37842
|
if (!metadata.isDirectory() || metadata.isSymbolicLink())
|
|
37577
37843
|
unavailable2();
|
|
37578
37844
|
if (ancestor === parse(ancestor).root)
|
|
37579
37845
|
break;
|
|
37580
37846
|
ancestor = dirname6(ancestor);
|
|
37581
37847
|
}
|
|
37582
|
-
const parent =
|
|
37848
|
+
const parent = lstatSync5(directory2);
|
|
37583
37849
|
if (process.platform !== "win32" && ((parent.mode & 63) !== 0 || parent.uid !== process.getuid?.()))
|
|
37584
37850
|
unavailable2();
|
|
37585
37851
|
}
|
|
@@ -37598,7 +37864,7 @@ function syncDirectory(filename2) {
|
|
|
37598
37864
|
}
|
|
37599
37865
|
}
|
|
37600
37866
|
function readState(filename2) {
|
|
37601
|
-
const metadata =
|
|
37867
|
+
const metadata = lstatSync5(filename2);
|
|
37602
37868
|
safeFile(metadata);
|
|
37603
37869
|
if (metadata.size > 2048)
|
|
37604
37870
|
unavailable2();
|
|
@@ -37631,10 +37897,10 @@ function readState(filename2) {
|
|
|
37631
37897
|
}
|
|
37632
37898
|
}
|
|
37633
37899
|
function persist(filename2, state) {
|
|
37634
|
-
const temporary = filename2 + "." +
|
|
37900
|
+
const temporary = filename2 + "." + randomUUID5() + ".tmp";
|
|
37635
37901
|
const descriptor2 = openSync(temporary, "wx", 384);
|
|
37636
37902
|
try {
|
|
37637
|
-
|
|
37903
|
+
writeFileSync8(descriptor2, JSON.stringify(state));
|
|
37638
37904
|
fsyncSync(descriptor2);
|
|
37639
37905
|
} finally {
|
|
37640
37906
|
closeSync(descriptor2);
|
|
@@ -37649,12 +37915,12 @@ function checkpoint(filename2, trust, initialize2) {
|
|
|
37649
37915
|
filename2 = resolve6(filename2);
|
|
37650
37916
|
safePath(filename2);
|
|
37651
37917
|
const lock = filename2 + ".lock";
|
|
37652
|
-
const next = { version: 1, scope: trust.scope, revision: trust.revision, digest:
|
|
37918
|
+
const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash4("sha256").update(trust.content).digest("hex") };
|
|
37653
37919
|
if (!initialize2) {
|
|
37654
37920
|
const previous = readState(filename2);
|
|
37655
37921
|
if (previous.scope.organizationId === next.scope.organizationId && previous.scope.applicationId === next.scope.applicationId && previous.scope.environmentId === next.scope.environmentId && previous.revision === next.revision && previous.digest === next.digest) {
|
|
37656
37922
|
try {
|
|
37657
|
-
|
|
37923
|
+
lstatSync5(lock);
|
|
37658
37924
|
} catch (error2) {
|
|
37659
37925
|
if (error2.code === "ENOENT")
|
|
37660
37926
|
return;
|
|
@@ -37665,7 +37931,7 @@ function checkpoint(filename2, trust, initialize2) {
|
|
|
37665
37931
|
}
|
|
37666
37932
|
const descriptor2 = openSync(lock, "wx", 384);
|
|
37667
37933
|
try {
|
|
37668
|
-
|
|
37934
|
+
writeFileSync8(descriptor2, "backify-application-auth-state-v1");
|
|
37669
37935
|
fsyncSync(descriptor2);
|
|
37670
37936
|
} finally {
|
|
37671
37937
|
closeSync(descriptor2);
|
|
@@ -37675,7 +37941,7 @@ function checkpoint(filename2, trust, initialize2) {
|
|
|
37675
37941
|
try {
|
|
37676
37942
|
if (initialize2) {
|
|
37677
37943
|
try {
|
|
37678
|
-
|
|
37944
|
+
lstatSync5(filename2);
|
|
37679
37945
|
unavailable2();
|
|
37680
37946
|
} catch (error2) {
|
|
37681
37947
|
if (error2.code !== "ENOENT")
|
|
@@ -37712,8 +37978,8 @@ function createPersistentApplicationAuthProvider(source, options) {
|
|
|
37712
37978
|
}
|
|
37713
37979
|
|
|
37714
37980
|
// ../sdk/dist/application-auth-sync.js
|
|
37715
|
-
import { createHash as
|
|
37716
|
-
import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as
|
|
37981
|
+
import { createHash as createHash5, createPublicKey as createPublicKey2, randomUUID as randomUUID6, verify as verify2 } from "node:crypto";
|
|
37982
|
+
import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as lstatSync6, openSync as openSync2, readFileSync as readFileSync10, renameSync as renameSync4, unlinkSync as unlinkSync3, writeFileSync as writeFileSync9 } from "node:fs";
|
|
37717
37983
|
import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
|
|
37718
37984
|
var maximumBytes = 512 * 1024;
|
|
37719
37985
|
var identifier = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
@@ -37752,7 +38018,7 @@ function prepare(options) {
|
|
|
37752
38018
|
function planApplicationAuthSynchronization(options) {
|
|
37753
38019
|
try {
|
|
37754
38020
|
const prepared = prepare(options);
|
|
37755
|
-
return { schemaVersion: 1, status: "planned", scope: structuredClone(options.expectedScope), agentId: options.agentId, endpoint: prepared.endpoint.href, managementKeySha256:
|
|
38021
|
+
return { schemaVersion: 1, status: "planned", scope: structuredClone(options.expectedScope), agentId: options.agentId, endpoint: prepared.endpoint.href, managementKeySha256: createHash5("sha256").update(prepared.key.export({ type: "spki", format: "der" })).digest("hex"), trustFile: prepared.trustFile, stateFile: prepared.stateFile, requiresInitializedOperatorJournal: true, workloadCredentialsRequired: false, deploymentReady: false };
|
|
37756
38022
|
} catch {
|
|
37757
38023
|
return unavailable3();
|
|
37758
38024
|
}
|
|
@@ -37760,13 +38026,13 @@ function planApplicationAuthSynchronization(options) {
|
|
|
37760
38026
|
function directory(filename2, privateState) {
|
|
37761
38027
|
const parent = dirname7(filename2);
|
|
37762
38028
|
for (let ancestor = parent; ; ancestor = dirname7(ancestor)) {
|
|
37763
|
-
const metadata2 =
|
|
38029
|
+
const metadata2 = lstatSync6(ancestor);
|
|
37764
38030
|
if (!metadata2.isDirectory() || metadata2.isSymbolicLink())
|
|
37765
38031
|
unavailable3();
|
|
37766
38032
|
if (ancestor === parse2(ancestor).root)
|
|
37767
38033
|
break;
|
|
37768
38034
|
}
|
|
37769
|
-
const metadata =
|
|
38035
|
+
const metadata = lstatSync6(parent);
|
|
37770
38036
|
if (process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & (privateState ? 63 : 18)) !== 0))
|
|
37771
38037
|
unavailable3();
|
|
37772
38038
|
}
|
|
@@ -37782,10 +38048,10 @@ function syncDirectory2(filename2) {
|
|
|
37782
38048
|
}
|
|
37783
38049
|
function currentPublicFile(filename2) {
|
|
37784
38050
|
try {
|
|
37785
|
-
const metadata =
|
|
38051
|
+
const metadata = lstatSync6(filename2);
|
|
37786
38052
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
|
|
37787
38053
|
unavailable3();
|
|
37788
|
-
const bytes =
|
|
38054
|
+
const bytes = readFileSync10(filename2);
|
|
37789
38055
|
if (bytes.length > 131072)
|
|
37790
38056
|
unavailable3();
|
|
37791
38057
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
@@ -37852,7 +38118,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
|
|
|
37852
38118
|
const lock = prepared.stateFile + ".delivery.lock";
|
|
37853
38119
|
const descriptor2 = openSync2(lock, "wx", 384);
|
|
37854
38120
|
try {
|
|
37855
|
-
|
|
38121
|
+
writeFileSync9(descriptor2, "backify-application-auth-delivery-v1");
|
|
37856
38122
|
fsyncSync2(descriptor2);
|
|
37857
38123
|
} finally {
|
|
37858
38124
|
closeSync2(descriptor2);
|
|
@@ -37863,14 +38129,14 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
|
|
|
37863
38129
|
const current = currentPublicFile(prepared.trustFile);
|
|
37864
38130
|
createPersistentApplicationAuthProvider(trust, { expectedScope: options.expectedScope, stateFile: prepared.stateFile, now: options.now });
|
|
37865
38131
|
const content = JSON.stringify(trust);
|
|
37866
|
-
const trustDigest =
|
|
38132
|
+
const trustDigest = createHash5("sha256").update(content).digest("hex");
|
|
37867
38133
|
if (current === content)
|
|
37868
38134
|
return { status: "unchanged", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
|
|
37869
38135
|
writePending = true;
|
|
37870
|
-
const temporary = prepared.trustFile + "." +
|
|
38136
|
+
const temporary = prepared.trustFile + "." + randomUUID6() + ".tmp";
|
|
37871
38137
|
const output = openSync2(temporary, "wx", process.platform === "win32" ? 384 : 292);
|
|
37872
38138
|
try {
|
|
37873
|
-
|
|
38139
|
+
writeFileSync9(output, content);
|
|
37874
38140
|
fsyncSync2(output);
|
|
37875
38141
|
} finally {
|
|
37876
38142
|
closeSync2(output);
|
|
@@ -38481,10 +38747,10 @@ function jsonValue(value) {
|
|
|
38481
38747
|
|
|
38482
38748
|
// src/local-services.ts
|
|
38483
38749
|
import { spawn, execFile } from "node:child_process";
|
|
38484
|
-
import { createHash as
|
|
38750
|
+
import { createHash as createHash7, generateKeyPairSync, randomBytes as randomBytes4, randomUUID as randomUUID8, sign } from "node:crypto";
|
|
38485
38751
|
import { createServer as createServer3 } from "node:net";
|
|
38486
|
-
import { existsSync as
|
|
38487
|
-
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as
|
|
38752
|
+
import { existsSync as existsSync11, lstatSync as lstatSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync12, readdirSync as readdirSync5, realpathSync, unlinkSync as unlinkSync4, writeFileSync as writeFileSync10 } from "node:fs";
|
|
38753
|
+
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join11, relative, resolve as resolve8 } from "node:path";
|
|
38488
38754
|
|
|
38489
38755
|
// src/local-typed-migrations.ts
|
|
38490
38756
|
var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -38531,10 +38797,10 @@ function typedMigrationSql(source) {
|
|
|
38531
38797
|
}
|
|
38532
38798
|
|
|
38533
38799
|
// src/local-job-services.ts
|
|
38534
|
-
import { createHash as
|
|
38535
|
-
import { existsSync as
|
|
38800
|
+
import { createHash as createHash6, randomBytes as randomBytes3, randomUUID as randomUUID7 } from "node:crypto";
|
|
38801
|
+
import { existsSync as existsSync10, lstatSync as lstatSync7, readFileSync as readFileSync11 } from "node:fs";
|
|
38536
38802
|
import { isIP } from "node:net";
|
|
38537
|
-
import { dirname as dirname8, join as
|
|
38803
|
+
import { dirname as dirname8, join as join10 } from "node:path";
|
|
38538
38804
|
function fields3(value, names) {
|
|
38539
38805
|
return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
|
|
38540
38806
|
}
|
|
@@ -38585,12 +38851,12 @@ function validLocalJobState(value, otherIds) {
|
|
|
38585
38851
|
function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
|
|
38586
38852
|
const requested = validateLocalJobArtifacts(artifacts);
|
|
38587
38853
|
const readSchema = (name2) => {
|
|
38588
|
-
const filename2 =
|
|
38854
|
+
const filename2 = join10(dirname8(hcrPath), "sql", name2), info = existsSync10(filename2) ? lstatSync7(filename2) : void 0;
|
|
38589
38855
|
if (!info?.isFile() || info.isSymbolicLink() || info.size > 65536) throw new Error("Native jobs require the reviewed jobs-v1.sql and jobs-producer-v1.sql assets beside the HCR host");
|
|
38590
|
-
return
|
|
38856
|
+
return readFileSync11(filename2, "utf8");
|
|
38591
38857
|
};
|
|
38592
38858
|
const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
|
|
38593
|
-
const schemaDigests = { base:
|
|
38859
|
+
const schemaDigests = { base: createHash6("sha256").update(base).digest("hex"), producer: createHash6("sha256").update(producer).digest("hex") };
|
|
38594
38860
|
if (retained && (retained.schemaDigests.base !== schemaDigests.base || retained.schemaDigests.producer !== schemaDigests.producer)) throw new Error("Native job schema changed; preserve its database and plan an explicit migration");
|
|
38595
38861
|
if (!retained?.initialized && !applyMigrations) throw new Error("Review both HCR job SQL assets and pass --apply-migrations for explicit native job schema approval");
|
|
38596
38862
|
const retainedArtifacts = retained ? validateLocalJobArtifacts(retained.artifacts) : [];
|
|
@@ -38599,20 +38865,20 @@ function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
|
|
|
38599
38865
|
if (previous && JSON.stringify(previous) !== JSON.stringify(artifact)) throw new Error("Retained local job artifact metadata cannot change; preserve the original pins and policies");
|
|
38600
38866
|
if (!previous) retainedArtifacts.push(artifact);
|
|
38601
38867
|
}
|
|
38602
|
-
const state = { ...retained ?? { id:
|
|
38868
|
+
const state = { ...retained ?? { id: randomUUID7(), password: randomBytes3(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
|
|
38603
38869
|
return { state, base, producer };
|
|
38604
38870
|
}
|
|
38605
38871
|
|
|
38606
38872
|
// src/local-services.ts
|
|
38607
38873
|
function writePrivate(filename2, value) {
|
|
38608
38874
|
if (isLink(filename2)) throw new Error("Local service files must not be symbolic links");
|
|
38609
|
-
const temporary = filename2 + "." +
|
|
38610
|
-
|
|
38875
|
+
const temporary = filename2 + "." + randomUUID8() + ".tmp";
|
|
38876
|
+
writeFileSync10(temporary, value, { flag: "wx", mode: 384 });
|
|
38611
38877
|
renameLocalFile(temporary, filename2);
|
|
38612
38878
|
}
|
|
38613
38879
|
function isLink(filename2) {
|
|
38614
38880
|
try {
|
|
38615
|
-
return
|
|
38881
|
+
return lstatSync8(filename2).isSymbolicLink();
|
|
38616
38882
|
} catch (error2) {
|
|
38617
38883
|
if (error2.code === "ENOENT") return false;
|
|
38618
38884
|
throw error2;
|
|
@@ -38633,17 +38899,17 @@ function stateValid(value) {
|
|
|
38633
38899
|
return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier3) => typeof identifier3 === "string" && uuid5.test(identifier3)) && Number.isSafeInteger(value.configurationVersion) && value.configurationVersion >= 0 && /^[a-f0-9]{64}$/.test(value.adminPassword) && /^[a-f0-9]{64}$/.test(value.databasePassword) && (value.retainedDatabasePort === void 0 || Number.isInteger(value.retainedDatabasePort) && value.retainedDatabasePort > 0 && value.retainedDatabasePort <= 65535);
|
|
38634
38900
|
}
|
|
38635
38901
|
function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
|
|
38636
|
-
const filename2 =
|
|
38902
|
+
const filename2 = join11(root, relativePath2);
|
|
38637
38903
|
assertLocalStatePath(root, filename2);
|
|
38638
38904
|
mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
|
|
38639
|
-
const owner = JSON.stringify({ version: 1, pid: process.pid, id:
|
|
38905
|
+
const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID8() });
|
|
38640
38906
|
try {
|
|
38641
|
-
|
|
38907
|
+
writeFileSync10(filename2, owner, { flag: "wx", mode: 384 });
|
|
38642
38908
|
} catch {
|
|
38643
38909
|
throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
|
|
38644
38910
|
}
|
|
38645
38911
|
return () => {
|
|
38646
|
-
if (
|
|
38912
|
+
if (existsSync11(filename2) && readFileSync12(filename2, "utf8") === owner) unlinkSync4(filename2);
|
|
38647
38913
|
};
|
|
38648
38914
|
}
|
|
38649
38915
|
async function allocateLocalPort(requested) {
|
|
@@ -38686,42 +38952,42 @@ function command(executable, args2, options = {}) {
|
|
|
38686
38952
|
});
|
|
38687
38953
|
}
|
|
38688
38954
|
function postgresExecutable(name2, bin) {
|
|
38689
|
-
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
38690
|
-
return directory2 ?
|
|
38955
|
+
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join11(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
|
|
38956
|
+
return directory2 ? join11(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
38691
38957
|
}
|
|
38692
38958
|
function localMigrationFiles(root, directory2) {
|
|
38693
|
-
const typed =
|
|
38959
|
+
const typed = join11(root, "backify.migrations.json");
|
|
38694
38960
|
if (directory2 === void 0) {
|
|
38695
|
-
if (!
|
|
38961
|
+
if (!existsSync11(typed) && !lstatIfPresent(typed)) return [];
|
|
38696
38962
|
assertLocalStatePath(root, typed);
|
|
38697
|
-
const info =
|
|
38963
|
+
const info = lstatSync8(typed);
|
|
38698
38964
|
if (!info.isFile() || info.size > 1024 * 1024) throw new Error("Typed migration manifest must be a file at most 1 MiB");
|
|
38699
|
-
return typedMigrationSql(
|
|
38965
|
+
return typedMigrationSql(readFileSync12(typed, "utf8")).map((migration) => ({ ...migration, digest: createHash7("sha256").update(migration.sql).digest("hex") }));
|
|
38700
38966
|
}
|
|
38701
|
-
if (
|
|
38967
|
+
if (existsSync11(typed) || lstatIfPresent(typed)) throw new Error("Use either declared SQL migrations or the typed manifest, not both");
|
|
38702
38968
|
if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
|
|
38703
38969
|
const folder = resolve8(root, directory2);
|
|
38704
38970
|
assertLocalStatePath(root, folder);
|
|
38705
|
-
if (!
|
|
38971
|
+
if (!existsSync11(folder)) throw new Error("Declared migration directory does not exist");
|
|
38706
38972
|
const entries2 = readdirSync5(folder);
|
|
38707
38973
|
const filenames = entries2.filter((entry) => entry.endsWith(".sql")).sort();
|
|
38708
38974
|
if (filenames.length > 100 || entries2.some((entry) => !entry.endsWith(".sql"))) throw new Error("Migrations require at most 100 flat .sql files");
|
|
38709
38975
|
let total = 0;
|
|
38710
38976
|
return filenames.map((name2) => {
|
|
38711
38977
|
if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
|
|
38712
|
-
const filename2 =
|
|
38978
|
+
const filename2 = join11(folder, name2);
|
|
38713
38979
|
assertLocalStatePath(root, filename2);
|
|
38714
|
-
const info =
|
|
38980
|
+
const info = lstatSync8(filename2);
|
|
38715
38981
|
if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
|
|
38716
|
-
const sql =
|
|
38982
|
+
const sql = readFileSync12(filename2, "utf8");
|
|
38717
38983
|
if (!sql.trim()) throw new Error("Migration SQL must not be empty");
|
|
38718
38984
|
validateLocalMigrationSql(sql);
|
|
38719
|
-
return { name: name2, digest:
|
|
38985
|
+
return { name: name2, digest: createHash7("sha256").update(sql).digest("hex"), sql };
|
|
38720
38986
|
});
|
|
38721
38987
|
}
|
|
38722
38988
|
function lstatIfPresent(filename2) {
|
|
38723
38989
|
try {
|
|
38724
|
-
return
|
|
38990
|
+
return lstatSync8(filename2);
|
|
38725
38991
|
} catch (error2) {
|
|
38726
38992
|
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return void 0;
|
|
38727
38993
|
throw error2;
|
|
@@ -38798,19 +39064,19 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38798
39064
|
const reviewedScope = options.jobIdentityScope;
|
|
38799
39065
|
if (reviewedScope !== void 0 && (!jobs || !manifest.capabilities.auth || manifest.capabilities.auth.enabled === false || !reviewedScope || Object.keys(reviewedScope).sort().join(",") !== "applicationId,environmentId,organizationId" || Object.values(reviewedScope).some((value) => typeof value !== "string" || value.length !== 36 || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === "00000000-0000-0000-0000-000000000000"))) throw new Error("Native worker identity scope requires reviewed jobs and enabled auth");
|
|
38800
39066
|
const installed = options.hcrPath || process.env.BACKIFY_LOCAL_HCR_PATH ? void 0 : installedLocalRuntime();
|
|
38801
|
-
const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ??
|
|
38802
|
-
if (!
|
|
38803
|
-
const directory2 =
|
|
39067
|
+
const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join11(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
|
|
39068
|
+
if (!existsSync11(hcrPath) || !lstatSync8(hcrPath).isFile() || !hcrPath.endsWith(".dll")) throw new Error("Full-fidelity mode requires a built Backify.Hcr.dll; set --hcr-path or BACKIFY_LOCAL_HCR_PATH");
|
|
39069
|
+
const directory2 = join11(root, ".backify", "dev", "services");
|
|
38804
39070
|
assertLocalStatePath(root, directory2);
|
|
38805
39071
|
mkdirSync4(directory2, { recursive: true, mode: 448 });
|
|
38806
39072
|
assertLocalStatePath(root, directory2);
|
|
38807
|
-
const statePath =
|
|
39073
|
+
const statePath = join11(directory2, "host.json");
|
|
38808
39074
|
assertLocalStatePath(root, statePath);
|
|
38809
39075
|
let existing;
|
|
38810
|
-
if (
|
|
38811
|
-
if (
|
|
39076
|
+
if (existsSync11(statePath)) {
|
|
39077
|
+
if (lstatSync8(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
|
|
38812
39078
|
try {
|
|
38813
|
-
existing = JSON.parse(
|
|
39079
|
+
existing = JSON.parse(readFileSync12(statePath, "utf8"));
|
|
38814
39080
|
} catch {
|
|
38815
39081
|
throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
|
|
38816
39082
|
}
|
|
@@ -38818,31 +39084,31 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38818
39084
|
}
|
|
38819
39085
|
const state = existing ?? {
|
|
38820
39086
|
version: 1,
|
|
38821
|
-
scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId:
|
|
38822
|
-
databaseId:
|
|
38823
|
-
storageId:
|
|
39087
|
+
scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID8(), applicationId: randomUUID8(), environmentId: randomUUID8() },
|
|
39088
|
+
databaseId: randomUUID8(),
|
|
39089
|
+
storageId: randomUUID8(),
|
|
38824
39090
|
configurationVersion: 0,
|
|
38825
|
-
adminPassword:
|
|
38826
|
-
databasePassword:
|
|
39091
|
+
adminPassword: randomBytes4(32).toString("hex"),
|
|
39092
|
+
databasePassword: randomBytes4(32).toString("hex")
|
|
38827
39093
|
};
|
|
38828
39094
|
if (!stateValid(state)) throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
|
|
38829
39095
|
if (reviewedScope && ["organizationId", "applicationId", "environmentId"].some((name2) => state.scope[name2] !== reviewedScope[name2])) throw new Error("Reviewed native worker identity scope conflicts with retained local ownership; preserve data and use a separate reviewed workspace");
|
|
38830
39096
|
let eventSchema;
|
|
38831
39097
|
if (events) {
|
|
38832
|
-
const filename2 =
|
|
38833
|
-
if (!
|
|
38834
|
-
eventSchema =
|
|
38835
|
-
const digest4 =
|
|
39098
|
+
const filename2 = join11(dirname9(hcrPath), "sql", "events-v1.sql");
|
|
39099
|
+
if (!existsSync11(filename2) || lstatSync8(filename2).isSymbolicLink() || !lstatSync8(filename2).isFile() || lstatSync8(filename2).size > 65536) throw new Error("Native events require the reviewed events-v1.sql asset beside the HCR host.");
|
|
39100
|
+
eventSchema = readFileSync12(filename2, "utf8");
|
|
39101
|
+
const digest4 = createHash7("sha256").update(eventSchema).digest("hex");
|
|
38836
39102
|
if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
|
|
38837
39103
|
if (!state.events?.initialized && !options.applyMigrations) throw new Error("Review the HCR events-v1.sql asset and pass --apply-migrations for explicit native event schema approval.");
|
|
38838
|
-
state.events ??= { id:
|
|
39104
|
+
state.events ??= { id: randomUUID8(), password: randomBytes4(32).toString("hex"), schemaDigest: digest4, initialized: false };
|
|
38839
39105
|
}
|
|
38840
39106
|
const jobSchema = jobs ? prepareLocalJobService(hcrPath, state.jobs, options.jobArtifacts, options.applyMigrations) : void 0;
|
|
38841
39107
|
if (jobSchema) state.jobs = jobSchema.state;
|
|
38842
39108
|
const storageNames = manifest.capabilities.storage?.buckets === void 0 ? ["default"] : manifest.capabilities.storage.buckets.map((bucket) => bucket.name);
|
|
38843
39109
|
state.storageBindings ??= { default: state.storageId };
|
|
38844
39110
|
if (typeof state.storageBindings !== "object" || state.storageBindings === null || Array.isArray(state.storageBindings) || Object.entries(state.storageBindings).some(([name2, identifier3]) => !/^[A-Za-z0-9_-]{1,100}$/.test(name2) || typeof identifier3 !== "string" || !/^[0-9a-f-]{36}$/i.test(identifier3))) throw new Error("Invalid local storage binding ownership state");
|
|
38845
|
-
for (const name2 of storageNames) state.storageBindings[name2] ??=
|
|
39111
|
+
for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID8();
|
|
38846
39112
|
if (Object.keys(state.storageBindings).length > 100) throw new Error("Local storage ownership history exceeds 100 bindings; preserve the data and plan an explicit migration");
|
|
38847
39113
|
if (Buffer.byteLength(JSON.stringify({ ...state, configurationVersion: Number.MAX_SAFE_INTEGER, retainedDatabasePort: 65535 }), "utf8") > 16384) throw new Error("Local ownership history exceeds supported limits; preserve state and plan an explicit migration");
|
|
38848
39114
|
const migrations = database ? localMigrationFiles(root, manifest.capabilities.database?.migrations) : [];
|
|
@@ -38850,7 +39116,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38850
39116
|
const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
|
|
38851
39117
|
if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
|
|
38852
39118
|
if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
|
|
38853
|
-
const cluster =
|
|
39119
|
+
const cluster = join11(directory2, "postgres");
|
|
38854
39120
|
assertLocalStatePath(root, cluster);
|
|
38855
39121
|
const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
|
|
38856
39122
|
let postgresStarted = false;
|
|
@@ -38866,7 +39132,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38866
39132
|
}
|
|
38867
39133
|
};
|
|
38868
39134
|
const runtimeUrl = "http://127.0.0.1:" + hcrPort;
|
|
38869
|
-
const tokenPath =
|
|
39135
|
+
const tokenPath = join11(directory2, "workload-token");
|
|
38870
39136
|
const stop = () => stopping ??= (async () => {
|
|
38871
39137
|
if (timer) clearInterval(timer);
|
|
38872
39138
|
if (snapshotTimer) clearInterval(snapshotTimer);
|
|
@@ -38885,9 +39151,9 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38885
39151
|
}
|
|
38886
39152
|
notify("hcr", "stopped");
|
|
38887
39153
|
try {
|
|
38888
|
-
if (postgresStarted &&
|
|
39154
|
+
if (postgresStarted && existsSync11(join11(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
|
|
38889
39155
|
if (postgresStarted) notify("postgres", "stopped");
|
|
38890
|
-
if (
|
|
39156
|
+
if (existsSync11(tokenPath)) unlinkSync4(tokenPath);
|
|
38891
39157
|
} finally {
|
|
38892
39158
|
release2();
|
|
38893
39159
|
}
|
|
@@ -38897,28 +39163,28 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38897
39163
|
writePrivate(statePath, JSON.stringify(state));
|
|
38898
39164
|
if (database || events || jobs) {
|
|
38899
39165
|
notify("postgres", "starting");
|
|
38900
|
-
if (!
|
|
38901
|
-
const passwordPath =
|
|
39166
|
+
if (!existsSync11(join11(cluster, "PG_VERSION"))) {
|
|
39167
|
+
const passwordPath = join11(directory2, "init-password");
|
|
38902
39168
|
writePrivate(passwordPath, state.adminPassword);
|
|
38903
39169
|
try {
|
|
38904
39170
|
await command(postgresExecutable("initdb", options.postgresBin), ["-D", cluster, "-U", "backify_admin", "--auth-host=scram-sha-256", "--auth-local=scram-sha-256", "--pwfile=" + passwordPath, "--no-locale", "--encoding=UTF8"]);
|
|
38905
39171
|
} finally {
|
|
38906
|
-
if (
|
|
39172
|
+
if (existsSync11(passwordPath)) unlinkSync4(passwordPath);
|
|
38907
39173
|
}
|
|
38908
39174
|
}
|
|
38909
|
-
if (
|
|
39175
|
+
if (existsSync11(join11(cluster, "postmaster.pid"))) throw new Error("A retained local PostgreSQL server is still running; stop or recover that exact owned cluster before restarting dev");
|
|
38910
39176
|
postgresStarted = true;
|
|
38911
|
-
await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l",
|
|
39177
|
+
await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l", join11(directory2, "postgres.log"), "-o", "-h 127.0.0.1 -p " + databasePort, "-w", "start"]);
|
|
38912
39178
|
notify("postgres", "ready");
|
|
38913
39179
|
const sql = (query, application = false) => command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", application ? "backify_local" : "backify_admin", "-d", application ? "backify_local" : "postgres", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-c", query], { env: { ...process.env, PGPASSWORD: application ? state.databasePassword : state.adminPassword } });
|
|
38914
39180
|
if (database) {
|
|
38915
39181
|
if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
|
|
38916
|
-
const filename2 =
|
|
39182
|
+
const filename2 = join11(directory2, "role-" + randomUUID8() + ".sql");
|
|
38917
39183
|
writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
|
|
38918
39184
|
try {
|
|
38919
39185
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_admin", "-d", "postgres", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", filename2], { env: { ...process.env, PGPASSWORD: state.adminPassword } });
|
|
38920
39186
|
} finally {
|
|
38921
|
-
if (
|
|
39187
|
+
if (existsSync11(filename2)) unlinkSync4(filename2);
|
|
38922
39188
|
}
|
|
38923
39189
|
}
|
|
38924
39190
|
if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_local'")).trim() === "0") await sql("CREATE DATABASE backify_local OWNER backify_local");
|
|
@@ -38933,12 +39199,12 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38933
39199
|
notify("migrations", "starting");
|
|
38934
39200
|
if (pending.length) await sql("CREATE TABLE IF NOT EXISTS public.__backify_migrations (name text PRIMARY KEY, digest text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now())", true);
|
|
38935
39201
|
for (const migration of pending) {
|
|
38936
|
-
const filename2 =
|
|
39202
|
+
const filename2 = join11(directory2, "apply-" + randomUUID8() + ".sql");
|
|
38937
39203
|
writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
|
|
38938
39204
|
try {
|
|
38939
39205
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_local", "-d", "backify_local", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", filename2], { env: { ...process.env, PGPASSWORD: state.databasePassword } });
|
|
38940
39206
|
} finally {
|
|
38941
|
-
if (
|
|
39207
|
+
if (existsSync11(filename2)) unlinkSync4(filename2);
|
|
38942
39208
|
}
|
|
38943
39209
|
applied.push(migration.name);
|
|
38944
39210
|
}
|
|
@@ -38949,20 +39215,20 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38949
39215
|
const eventSql = (query) => command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_events", "-d", "backify_events", "-X", "-q", "-t", "-A", "-v", "ON_ERROR_STOP=1", "-c", query], { env: { ...process.env, PGPASSWORD: eventState.password } });
|
|
38950
39216
|
if (!eventState.initialized) {
|
|
38951
39217
|
if ((await sql("SELECT count(*) FROM pg_database WHERE datname='backify_events'")).trim() !== "0" || (await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_events'")).trim() !== "0") throw new Error("Uninitialized native event ownership conflicts with retained state; preserve it and repair explicitly.");
|
|
38952
|
-
const roleFile =
|
|
39218
|
+
const roleFile = join11(directory2, "event-role-" + randomUUID8() + ".sql");
|
|
38953
39219
|
writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
|
|
38954
39220
|
try {
|
|
38955
39221
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_admin", "-d", "postgres", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", roleFile], { env: { ...process.env, PGPASSWORD: state.adminPassword } });
|
|
38956
39222
|
} finally {
|
|
38957
|
-
if (
|
|
39223
|
+
if (existsSync11(roleFile)) unlinkSync4(roleFile);
|
|
38958
39224
|
}
|
|
38959
39225
|
await sql("CREATE DATABASE backify_events OWNER backify_events");
|
|
38960
|
-
const schemaFile =
|
|
39226
|
+
const schemaFile = join11(directory2, "event-schema-" + randomUUID8() + ".sql");
|
|
38961
39227
|
writePrivate(schemaFile, eventSchema);
|
|
38962
39228
|
try {
|
|
38963
39229
|
await command(postgresExecutable("psql", options.postgresBin), ["-h", "127.0.0.1", "-p", String(databasePort), "-U", "backify_events", "-d", "backify_events", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-f", schemaFile], { env: { ...process.env, PGPASSWORD: eventState.password } });
|
|
38964
39230
|
} finally {
|
|
38965
|
-
if (
|
|
39231
|
+
if (existsSync11(schemaFile)) unlinkSync4(schemaFile);
|
|
38966
39232
|
}
|
|
38967
39233
|
eventState.initialized = true;
|
|
38968
39234
|
writePrivate(statePath, JSON.stringify(state));
|
|
@@ -38976,21 +39242,21 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38976
39242
|
const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
|
|
38977
39243
|
if (!jobState.initialized) {
|
|
38978
39244
|
if ((await adminSql("SELECT count(*) FROM pg_database WHERE datname='backify_jobs'")).trim() !== "0" || (await adminSql("SELECT count(*) FROM pg_roles WHERE rolname='backify_jobs'")).trim() !== "0") throw new Error("Uninitialized native job ownership conflicts with retained state; preserve it and repair explicitly");
|
|
38979
|
-
const roleFile =
|
|
39245
|
+
const roleFile = join11(directory2, "job-role-" + randomUUID8() + ".sql");
|
|
38980
39246
|
writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
|
|
38981
39247
|
try {
|
|
38982
39248
|
await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
|
|
38983
39249
|
} finally {
|
|
38984
|
-
if (
|
|
39250
|
+
if (existsSync11(roleFile)) unlinkSync4(roleFile);
|
|
38985
39251
|
}
|
|
38986
39252
|
await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
|
|
38987
39253
|
for (const schema of [jobSchema.base, jobSchema.producer]) {
|
|
38988
|
-
const filename2 =
|
|
39254
|
+
const filename2 = join11(directory2, "job-schema-" + randomUUID8() + ".sql");
|
|
38989
39255
|
writePrivate(filename2, schema);
|
|
38990
39256
|
try {
|
|
38991
39257
|
await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
|
|
38992
39258
|
} finally {
|
|
38993
|
-
if (
|
|
39259
|
+
if (existsSync11(filename2)) unlinkSync4(filename2);
|
|
38994
39260
|
}
|
|
38995
39261
|
}
|
|
38996
39262
|
await adminSql("REVOKE ALL ON DATABASE backify_jobs FROM PUBLIC; GRANT CONNECT ON DATABASE backify_jobs TO backify_jobs; REVOKE CREATE ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA __backify_jobs TO backify_jobs; GRANT SELECT ON __backify_jobs.schema_version,__backify_jobs.producer_schema_version TO backify_jobs; GRANT SELECT,INSERT,UPDATE ON __backify_jobs.runs,__backify_jobs.attempts TO backify_jobs; GRANT SELECT,INSERT ON __backify_jobs.producers TO backify_jobs", "backify_jobs");
|
|
@@ -39019,7 +39285,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39019
39285
|
...events ? [{ id: state.events.id, scope: state.scope, capability: "events", contractVersion: 1, logicalBinding: "default", provider: "postgres-events", resourceReference: "backify_events", ownership: "Managed", accessMode: "Gateway", permissions: ["events.emit", "events.receive", "events.complete", "events.inspect"], status: "ready" }] : [],
|
|
39020
39286
|
...jobs ? [{ id: state.jobs.id, scope: state.scope, capability: "jobs", contractVersion: 1, logicalBinding: "default", provider: "postgres-jobs", resourceReference: "backify_jobs", ownership: "Managed", accessMode: "Gateway", permissions: ["jobs.enqueue", "jobs.receive", "jobs.complete", "jobs.cancel", "jobs.inspect", "jobs.retry"], status: "ready" }] : []
|
|
39021
39287
|
];
|
|
39022
|
-
const snapshotPath =
|
|
39288
|
+
const snapshotPath = join11(directory2, "snapshot.json");
|
|
39023
39289
|
const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
|
|
39024
39290
|
const renewConfiguration = () => {
|
|
39025
39291
|
if (stopping) throw new Error("Stopped local services cannot renew configuration");
|
|
@@ -39029,15 +39295,15 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39029
39295
|
writeSnapshot();
|
|
39030
39296
|
};
|
|
39031
39297
|
writeSnapshot();
|
|
39032
|
-
const settingsPath =
|
|
39298
|
+
const settingsPath = join11(directory2, "appsettings.json");
|
|
39033
39299
|
writePrivate(settingsPath, JSON.stringify({ Hcr: {
|
|
39034
39300
|
Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
|
|
39035
39301
|
SnapshotPath: snapshotPath,
|
|
39036
|
-
SnapshotJournalPath:
|
|
39302
|
+
SnapshotJournalPath: join11(directory2, "journal.json"),
|
|
39037
39303
|
Postgres: { Bindings: state.retainedDatabasePort ? { [state.databaseId]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_local;Username=backify_local;Password=" + state.databasePassword } } : {} },
|
|
39038
39304
|
Events: { Bindings: state.retainedDatabasePort && state.events?.initialized ? { [state.events.id]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_events;Username=backify_events;Password=" + state.events.password } } : {} },
|
|
39039
39305
|
Jobs: { Bindings: state.retainedDatabasePort && state.jobs?.initialized ? { [state.jobs.id]: { Scope: state.scope, ConnectionString: "Host=127.0.0.1;Port=" + state.retainedDatabasePort + ";Database=backify_jobs;Username=backify_jobs;Password=" + state.jobs.password, Artifacts: state.jobs.artifacts } } : {} },
|
|
39040
|
-
Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier3]) => [identifier3, { Scope: state.scope, ResourceReference: name2, RootPath:
|
|
39306
|
+
Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier3]) => [identifier3, { Scope: state.scope, ResourceReference: name2, RootPath: join11(directory2, "objects", identifier3) }])) }
|
|
39041
39307
|
} }));
|
|
39042
39308
|
issueToken();
|
|
39043
39309
|
notify("hcr", "starting");
|
|
@@ -39051,7 +39317,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39051
39317
|
while (true) {
|
|
39052
39318
|
if (spawnFailed || hcr.exitCode !== null || hcr.signalCode !== null || Date.now() > deadline) throw new Error("Local HCR could not become ready; check the .NET runtime, bindings and retained journal");
|
|
39053
39319
|
try {
|
|
39054
|
-
const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " +
|
|
39320
|
+
const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " + readFileSync12(tokenPath, "utf8") }, signal: AbortSignal.timeout(500), redirect: "error", credentials: "omit", cache: "no-store" });
|
|
39055
39321
|
if (response.ok) {
|
|
39056
39322
|
const status = await response.json();
|
|
39057
39323
|
if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
|
|
@@ -39060,8 +39326,8 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39060
39326
|
}
|
|
39061
39327
|
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
|
|
39062
39328
|
}
|
|
39063
|
-
if (events) await createHcrEventsProvider({ runtimeUrl, token: () =>
|
|
39064
|
-
if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () =>
|
|
39329
|
+
if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync12(tokenPath, "utf8") }).inspect();
|
|
39330
|
+
if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync12(tokenPath, "utf8") }).inspect();
|
|
39065
39331
|
timer = setInterval(() => {
|
|
39066
39332
|
try {
|
|
39067
39333
|
issueToken();
|
|
@@ -39077,7 +39343,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39077
39343
|
}
|
|
39078
39344
|
}, 36e5);
|
|
39079
39345
|
notify("hcr", "ready");
|
|
39080
|
-
const configurationFingerprint =
|
|
39346
|
+
const configurationFingerprint = createHash7("sha256").update(JSON.stringify({ mode: "full", capabilities: manifest.capabilities, migrations: migrations.map(({ name: name2, digest: digest4 }) => ({ name: name2, digest: digest4 })), ...jobs ? { jobArtifacts: state.jobs.artifacts } : {} })).digest("hex");
|
|
39081
39347
|
return { identityScope: { ...state.scope }, runtimeUrl, tokenPath, database, storage, events, jobs, databasePort, migrations: applied, configurationFingerprint, renewConfiguration, stop };
|
|
39082
39348
|
} catch (error2) {
|
|
39083
39349
|
await stop();
|
|
@@ -39086,15 +39352,15 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39086
39352
|
}
|
|
39087
39353
|
|
|
39088
39354
|
// src/local-job-auth.ts
|
|
39089
|
-
import { createHash as
|
|
39090
|
-
import { lstatSync as
|
|
39355
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
39356
|
+
import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
|
|
39091
39357
|
import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
|
|
39092
39358
|
function prepareLocalJobAuth(root, filename2) {
|
|
39093
39359
|
const read = (path, maximum) => {
|
|
39094
39360
|
assertLocalStatePath(root, path);
|
|
39095
|
-
const metadata =
|
|
39361
|
+
const metadata = lstatSync9(path);
|
|
39096
39362
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
39097
|
-
const bytes =
|
|
39363
|
+
const bytes = readFileSync13(path);
|
|
39098
39364
|
if (bytes.length > maximum) throw new Error();
|
|
39099
39365
|
return bytes;
|
|
39100
39366
|
};
|
|
@@ -39108,7 +39374,7 @@ function prepareLocalJobAuth(root, filename2) {
|
|
|
39108
39374
|
if (trustFile === stateFile) throw new Error();
|
|
39109
39375
|
const bytes = read(trustFile, 131072), trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
39110
39376
|
read(stateFile, 2048);
|
|
39111
|
-
if (
|
|
39377
|
+
if (createHash8("sha256").update(bytes).digest("hex") !== input.trustDigest || trust.revision !== input.revision) throw new Error();
|
|
39112
39378
|
createPersistentApplicationAuthProvider(trust, { expectedScope: input.scope, stateFile });
|
|
39113
39379
|
return { trustFile, stateFile, scope: structuredClone(input.scope), revision: input.revision, trustDigest: input.trustDigest };
|
|
39114
39380
|
} catch {
|
|
@@ -39117,20 +39383,20 @@ function prepareLocalJobAuth(root, filename2) {
|
|
|
39117
39383
|
}
|
|
39118
39384
|
|
|
39119
39385
|
// src/local-job-trust-renewal.ts
|
|
39120
|
-
import { createHash as
|
|
39121
|
-
import { lstatSync as
|
|
39386
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
39387
|
+
import { lstatSync as lstatSync11, readFileSync as readFileSync15 } from "node:fs";
|
|
39122
39388
|
import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
|
|
39123
39389
|
|
|
39124
39390
|
// src/workload-trust-sync.ts
|
|
39125
|
-
import { lstatSync as
|
|
39391
|
+
import { lstatSync as lstatSync10, readFileSync as readFileSync14 } from "node:fs";
|
|
39126
39392
|
import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
|
|
39127
|
-
import { createHash as
|
|
39393
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
39128
39394
|
function prepareWorkloadTrustSynchronization(filename2) {
|
|
39129
39395
|
try {
|
|
39130
39396
|
if (!isAbsolute6(filename2)) throw new Error();
|
|
39131
|
-
const metadata =
|
|
39397
|
+
const metadata = lstatSync10(filename2);
|
|
39132
39398
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
|
|
39133
|
-
const bytes =
|
|
39399
|
+
const bytes = readFileSync14(filename2);
|
|
39134
39400
|
if (bytes.length > 65536) throw new Error();
|
|
39135
39401
|
const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
39136
39402
|
const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
|
|
@@ -39141,15 +39407,15 @@ function prepareWorkloadTrustSynchronization(filename2) {
|
|
|
39141
39407
|
const intervalSeconds = value.intervalSeconds ?? 30;
|
|
39142
39408
|
if (!Number.isSafeInteger(intervalSeconds) || intervalSeconds < 10 || intervalSeconds > 300) throw new Error();
|
|
39143
39409
|
const credential = () => {
|
|
39144
|
-
const metadata2 =
|
|
39410
|
+
const metadata2 = lstatSync10(credentialFile);
|
|
39145
39411
|
if (!metadata2.isFile() || metadata2.isSymbolicLink() || metadata2.nlink !== 1 || metadata2.size > 256 || process.platform !== "win32" && (metadata2.uid !== process.getuid?.() || (metadata2.mode & 63) !== 0)) throw new Error("Management credential unavailable");
|
|
39146
|
-
const bytes2 =
|
|
39412
|
+
const bytes2 = readFileSync14(credentialFile);
|
|
39147
39413
|
if (bytes2.length > 256) throw new Error("Management credential unavailable");
|
|
39148
39414
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
|
|
39149
39415
|
};
|
|
39150
39416
|
const options = { controlPlaneUrl: value.controlPlaneUrl, agentId: value.agentId, expectedScope: value.expectedScope, managementIssuer: value.managementIssuer, managementAudience: value.managementAudience, managementPublicKeyPem: value.managementPublicKeyPem, credential, trustFile, stateFile };
|
|
39151
39417
|
const plan = planApplicationAuthSynchronization(options);
|
|
39152
|
-
return { options, plan, intervalSeconds, credentialFile, configurationDigest:
|
|
39418
|
+
return { options, plan, intervalSeconds, credentialFile, configurationDigest: createHash9("sha256").update(bytes).digest("hex") };
|
|
39153
39419
|
} catch {
|
|
39154
39420
|
throw new Error("Invalid operator trust-sync configuration");
|
|
39155
39421
|
}
|
|
@@ -39208,15 +39474,15 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
|
|
|
39208
39474
|
const same = (first, second) => process.platform === "win32" ? first.toLowerCase() === second.toLowerCase() : first === second;
|
|
39209
39475
|
if (!same(options.trustFile, mount.trustFile) || !same(options.stateFile, mount.stateFile) || ["organizationId", "applicationId", "environmentId"].some((name2) => options.expectedScope[name2] !== mount.scope[name2])) throw new Error();
|
|
39210
39476
|
assertLocalStatePath(root, configured.credentialFile);
|
|
39211
|
-
const metadata =
|
|
39477
|
+
const metadata = lstatSync11(configured.credentialFile);
|
|
39212
39478
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 256 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
|
|
39213
39479
|
return { configurationFile, configurationDigest: configured.configurationDigest, credentialFile: configured.credentialFile, intervalSeconds: configured.intervalSeconds, options };
|
|
39214
39480
|
} catch {
|
|
39215
39481
|
throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
|
|
39216
39482
|
}
|
|
39217
39483
|
}
|
|
39218
|
-
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash:
|
|
39219
|
-
const { createHash: createHash17, lstatSync:
|
|
39484
|
+
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync15, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
|
|
39485
|
+
const { createHash: createHash17, lstatSync: lstatSync21, readFileSync: readFileSync30, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
|
|
39220
39486
|
const key = (filename2) => process.platform === "win32" ? resolve25(filename2).toLowerCase() : resolve25(filename2);
|
|
39221
39487
|
const groups = [];
|
|
39222
39488
|
for (const mount of mounts) {
|
|
@@ -39236,11 +39502,11 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
|
|
|
39236
39502
|
const read = (filename2, maximum, privateFile2 = false) => {
|
|
39237
39503
|
for (let current = resolve25(filename2); current !== root; current = resolve25(current, "..")) {
|
|
39238
39504
|
const part = relative11(root, current);
|
|
39239
|
-
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) ||
|
|
39505
|
+
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error();
|
|
39240
39506
|
}
|
|
39241
|
-
const metadata =
|
|
39507
|
+
const metadata = lstatSync21(filename2);
|
|
39242
39508
|
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > maximum || privateFile2 && process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 63) !== 0)) throw new Error();
|
|
39243
|
-
const bytes =
|
|
39509
|
+
const bytes = readFileSync30(filename2);
|
|
39244
39510
|
if (bytes.length > maximum) throw new Error();
|
|
39245
39511
|
return bytes;
|
|
39246
39512
|
};
|
|
@@ -39321,14 +39587,14 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
|
|
|
39321
39587
|
if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
|
|
39322
39588
|
const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
|
|
39323
39589
|
if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
|
|
39324
|
-
const workerFile =
|
|
39590
|
+
const workerFile = join12(resolve12(root, directory2), "workload.mjs"), metadataFile = join12(resolve12(root, directory2), "artifact.json");
|
|
39325
39591
|
for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
|
|
39326
|
-
if (!
|
|
39327
|
-
const metadata = JSON.parse(
|
|
39328
|
-
const bundle =
|
|
39329
|
-
const actual =
|
|
39592
|
+
if (!lstatSync12(workerFile).isFile() || lstatSync12(workerFile).size > 16777216 || !lstatSync12(metadataFile).isFile() || lstatSync12(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
|
|
39593
|
+
const metadata = JSON.parse(readFileSync16(metadataFile, "utf8"));
|
|
39594
|
+
const bundle = readFileSync16(workerFile);
|
|
39595
|
+
const actual = createHash11("sha256").update(bundle).digest("hex");
|
|
39330
39596
|
const scheduleDiscovery = bundle.subarray(0, 100).toString("utf8").startsWith('var __backifyWorkerProtocols = ["hcr-v1","hcr-schedules-v1"];\n');
|
|
39331
|
-
if (!metadata || metadata.schemaVersion !== 1 || metadata.kind !== "worker" || metadata.artifactVersion !== actual || metadata.manifestVersion !==
|
|
39597
|
+
if (!metadata || metadata.schemaVersion !== 1 || metadata.kind !== "worker" || metadata.artifactVersion !== actual || metadata.manifestVersion !== createHash11("sha256").update(JSON.stringify(manifest)).digest("hex")) throw new Error("Native worker kind, bundle or manifest pin does not match the reviewed artifact");
|
|
39332
39598
|
const artifact = validateLocalJobArtifacts(artifacts).find((item) => item.artifactVersion === actual);
|
|
39333
39599
|
if (!artifact) throw new Error("Native worker bundle is not an explicitly reviewed job artifact");
|
|
39334
39600
|
if (metadata.workerProtocols !== void 0 && (!scheduleDiscovery || JSON.stringify(metadata.workerProtocols) !== JSON.stringify(["hcr-v1", "hcr-schedules-v1"]))) throw new Error("Invalid worker protocol admission");
|
|
@@ -39338,29 +39604,29 @@ function readLocalJobArtifacts(root, filename2) {
|
|
|
39338
39604
|
if (!filename2 || isAbsolute8(filename2)) throw new Error("Job artifact admission requires a repository-relative reviewed JSON file");
|
|
39339
39605
|
const path = resolve12(root, filename2);
|
|
39340
39606
|
assertLocalStatePath(root, path);
|
|
39341
|
-
if (!
|
|
39342
|
-
return validateLocalJobArtifacts(JSON.parse(
|
|
39607
|
+
if (!lstatSync12(path).isFile() || lstatSync12(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
|
|
39608
|
+
return validateLocalJobArtifacts(JSON.parse(readFileSync16(path, "utf8")));
|
|
39343
39609
|
}
|
|
39344
|
-
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash:
|
|
39345
|
-
const { spawn: spawn6, createHash: createHash17, lstatSync:
|
|
39610
|
+
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash11, lstatSync: lstatSync12, readFileSync: readFileSync16, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
|
|
39611
|
+
const { spawn: spawn6, createHash: createHash17, lstatSync: lstatSync21, readFileSync: readFileSync30, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
|
|
39346
39612
|
const assertReady = () => {
|
|
39347
39613
|
for (let current = resolve25(options.workerFile); current !== options.root; current = resolve25(current, "..")) {
|
|
39348
39614
|
const part = relative11(options.root, current);
|
|
39349
|
-
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) ||
|
|
39615
|
+
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
|
|
39350
39616
|
}
|
|
39351
|
-
if (!
|
|
39617
|
+
if (!lstatSync21(options.workerFile).isFile() || lstatSync21(options.workerFile).size > 16777216 || createHash17("sha256").update(readFileSync30(options.workerFile)).digest("hex") !== options.artifact.artifactVersion) throw new Error("Native worker paths or pins changed");
|
|
39352
39618
|
if (options.authTrust) {
|
|
39353
39619
|
try {
|
|
39354
39620
|
const mount = options.authTrust;
|
|
39355
39621
|
for (const path of [mount.trustFile, mount.stateFile]) {
|
|
39356
39622
|
for (let current = resolve25(path); current !== options.root; current = resolve25(current, "..")) {
|
|
39357
39623
|
const part = relative11(options.root, current);
|
|
39358
|
-
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) ||
|
|
39624
|
+
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error();
|
|
39359
39625
|
}
|
|
39360
|
-
const metadata =
|
|
39626
|
+
const metadata = lstatSync21(path);
|
|
39361
39627
|
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
|
|
39362
39628
|
}
|
|
39363
|
-
const bytes =
|
|
39629
|
+
const bytes = readFileSync30(mount.trustFile);
|
|
39364
39630
|
if (bytes.length > 131072 || createHash17("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
|
|
39365
39631
|
const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
39366
39632
|
if (trust.revision !== mount.revision) throw new Error();
|
|
@@ -39474,9 +39740,9 @@ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createH
|
|
|
39474
39740
|
}
|
|
39475
39741
|
|
|
39476
39742
|
// src/local-native-jobs.ts
|
|
39477
|
-
import { createHash as
|
|
39743
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
39478
39744
|
function createLocalNativeJobs(local, native, executor, artifact, scope, onFailure = () => {
|
|
39479
|
-
}, hash2 =
|
|
39745
|
+
}, hash2 = createHash12, catalog = { workloadJobSchedules, validateWorkloadJobSchedules, HcrJobsRequestError }, historical = []) {
|
|
39480
39746
|
const workers = [{ artifact, executor }, ...historical];
|
|
39481
39747
|
if (historical.length > 15 || new Set(workers.map((worker) => worker.artifact.artifactVersion)).size !== workers.length) throw new Error("Historical workers require bounded unique artifact pins");
|
|
39482
39748
|
const lanes = workers.flatMap((worker) => worker.artifact.jobs.map((policy) => ({ ...worker, policy })));
|
|
@@ -39615,7 +39881,7 @@ import { jobs } from "@backifydev/sdk";
|
|
|
39615
39881
|
import { createHcrDatabaseProvider, createHcrStorageProvider, createHcrEventsProvider, createHcrJobsProvider, HcrJobsRequestError, workloadJobSchedules, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider } from "@backifydev/sdk/server";
|
|
39616
39882
|
import { createServer } from "node:http";
|
|
39617
39883
|
import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync } from "node:fs";
|
|
39618
|
-
import { timingSafeEqual, createHash } from "node:crypto";
|
|
39884
|
+
import { timingSafeEqual, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
39619
39885
|
import { spawn } from "node:child_process";
|
|
39620
39886
|
import { isAbsolute, relative, resolve } from "node:path";
|
|
39621
39887
|
const statePath = process.env.BACKIFY_LOCAL_STATE;
|
|
@@ -39679,11 +39945,26 @@ async function inspectEndpoint(url) {
|
|
|
39679
39945
|
return { url, status: "responding", httpStatus: response.status };
|
|
39680
39946
|
} catch { return { url, status: "unreachable" }; }
|
|
39681
39947
|
}
|
|
39948
|
+
const createLocalEmailAuth = __BACKIFY_LOCAL_EMAIL_AUTH__;
|
|
39949
|
+
const emailOrigin = process.env.BACKIFY_LOCAL_FRONTEND_URL || process.env.BACKIFY_LOCAL_BACKEND_URL;
|
|
39950
|
+
const localEmailAuth = runtime.localIdentity && emailOrigin ? createLocalEmailAuth({ identity: runtime.localIdentity, origin: emailOrigin }, { createHash, randomBytes, randomUUID }) : undefined;
|
|
39682
39951
|
const server = createServer(async (request, response) => {
|
|
39683
39952
|
response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff");
|
|
39684
39953
|
const send = (status, value) => { response.writeHead(status, { "content-type": "application/json" }); response.end(JSON.stringify(value)); };
|
|
39685
39954
|
if (!/^((127\.0\.0\.1)|(localhost)):\d+$/.test(request.headers.host ?? "")) return send(403, { error: "Invalid host" });
|
|
39686
39955
|
if (request.method === "GET" && request.url === "/") { response.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'" }); return response.end(dashboard); }
|
|
39956
|
+
if (request.url?.startsWith("/.backify/auth/")) {
|
|
39957
|
+
if (!localEmailAuth) return send(503, { error: "local_identity_unavailable" });
|
|
39958
|
+
try {
|
|
39959
|
+
let body = "";
|
|
39960
|
+
for await (const chunk of request) { body += chunk.toString(); if (Buffer.byteLength(body) > 8192) return send(413, { error: "request_too_large" }); }
|
|
39961
|
+
const headers = new Headers();
|
|
39962
|
+
for (const [name, value] of Object.entries(request.headers)) if (typeof value === "string" && name !== "host") headers.set(name, value);
|
|
39963
|
+
const result = await localEmailAuth.handle(new Request(emailOrigin + request.url, { method: request.method, headers, ...(body ? { body } : {}) }));
|
|
39964
|
+
response.writeHead(result.status, Object.fromEntries(result.headers));
|
|
39965
|
+
return response.end(Buffer.from(await result.arrayBuffer()));
|
|
39966
|
+
} catch { return send(400, { error: "invalid_local_auth_request" }); }
|
|
39967
|
+
}
|
|
39687
39968
|
const provided = request.headers.authorization?.replace(/^Bearer /, "") ?? "";
|
|
39688
39969
|
const bytes = /^[a-f0-9]{64}$/.test(provided) ? Buffer.from(provided, "hex") : Buffer.alloc(0);
|
|
39689
39970
|
if (bytes.length !== token.length || !timingSafeEqual(bytes, token)) return send(401, { error: "Local session required" });
|
|
@@ -39691,6 +39972,7 @@ const server = createServer(async (request, response) => {
|
|
|
39691
39972
|
if (request.method === "GET" && request.url === "/v1/status") { const inspected = runtime.inspect(); return send(200, { status: "healthy", ...inspected, events: await inspectEvents(), ...(nativeJobs ? { jobs: (await nativeJobs.inspect()).runs } : {}), tables: process.env.BACKIFY_LOCAL_DATABASE === "postgres" ? [] : inspected.tables, buckets: process.env.BACKIFY_LOCAL_STORAGE === "filesystem" ? [] : inspected.buckets, services: { mode: process.env.BACKIFY_LOCAL_HCR_URL ? "full" : "lightweight", hcrUrl: process.env.BACKIFY_LOCAL_HCR_URL, database: process.env.BACKIFY_LOCAL_DATABASE ?? "document-emulator", storage: process.env.BACKIFY_LOCAL_STORAGE ?? "snapshot-emulator", events: process.env.BACKIFY_LOCAL_EVENTS ?? "snapshot-emulator", jobs: process.env.BACKIFY_LOCAL_JOBS ?? "snapshot-emulator", frontend: await inspectEndpoint(process.env.BACKIFY_LOCAL_FRONTEND_URL), backend: await inspectEndpoint(process.env.BACKIFY_LOCAL_BACKEND_URL), inspection: process.env.BACKIFY_LOCAL_HCR_URL ? "scoped read-only provider inspection available in Data panel; status contains metadata only" : "local snapshot" } }); }
|
|
39692
39973
|
if (request.method === "GET" && request.url === "/v1/logs") return send(200, runtime.inspect().logs);
|
|
39693
39974
|
if (request.method === "GET" && request.url === "/v1/events") return send(200, await inspectEvents());
|
|
39975
|
+
if (request.method === "GET" && request.url === "/v1/identity/inbox") return localEmailAuth ? send(200, { messages: localEmailAuth.inbox() }) : send(503, { error: "local_identity_unavailable" });
|
|
39694
39976
|
if (request.method === "GET" && request.url === "/v1/identity/users") return runtime.localIdentity ? send(200, { kind: "local-development", users: runtime.localIdentity.profiles() }) : send(503, { error: "local_identity_unavailable" });
|
|
39695
39977
|
if (request.method === "GET" && request.url === "/v1/database/tables") return send(200, await inspector.tables());
|
|
39696
39978
|
if (request.method === "GET" && request.url === "/v1/storage/buckets") return send(200, inspector.buckets());
|
|
@@ -39729,14 +40011,14 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
|
|
|
39729
40011
|
catch { console.error("Native worker trust renewal delivery refused; pin guards remain enforced."); }
|
|
39730
40012
|
}
|
|
39731
40013
|
});
|
|
39732
|
-
`.replace("__BACKIFY_ENTRY__", JSON.stringify(entrypoint)).replace("__BACKIFY_STATE_REPLACEMENT__", replaceLocalFile.toString()).replace("__BACKIFY_INSPECTOR_FACTORY__", createLocalDataInspector.toString()).replace("__BACKIFY_DASHBOARD__", JSON.stringify(dashboardHtml)).replace("__BACKIFY_NATIVE_EVENTS__", createLocalNativeEvents.toString()).replace("__BACKIFY_NATIVE_JOB_EXECUTOR__", createLocalJobExecutor.toString()).replace("__BACKIFY_NATIVE_JOBS__", createLocalNativeJobs.toString()).replace("__BACKIFY_TRUST_RENEWAL_DELIVERY__", applyLocalJobTrustRenewal.toString());
|
|
40014
|
+
`.replace("__BACKIFY_LOCAL_EMAIL_AUTH__", createLocalEmailAuth.toString()).replace("__BACKIFY_ENTRY__", JSON.stringify(entrypoint)).replace("__BACKIFY_STATE_REPLACEMENT__", replaceLocalFile.toString()).replace("__BACKIFY_INSPECTOR_FACTORY__", createLocalDataInspector.toString()).replace("__BACKIFY_DASHBOARD__", JSON.stringify(dashboardHtml)).replace("__BACKIFY_NATIVE_EVENTS__", createLocalNativeEvents.toString()).replace("__BACKIFY_NATIVE_JOB_EXECUTOR__", createLocalJobExecutor.toString()).replace("__BACKIFY_NATIVE_JOBS__", createLocalNativeJobs.toString()).replace("__BACKIFY_TRUST_RENEWAL_DELIVERY__", applyLocalJobTrustRenewal.toString());
|
|
39733
40015
|
}
|
|
39734
40016
|
|
|
39735
40017
|
// src/local-frontend.ts
|
|
39736
40018
|
import { spawn as spawn3 } from "node:child_process";
|
|
39737
|
-
import { readFileSync as
|
|
40019
|
+
import { readFileSync as readFileSync18, realpathSync as realpathSync3, existsSync as existsSync12, statSync } from "node:fs";
|
|
39738
40020
|
import { createRequire as createRequire3 } from "node:module";
|
|
39739
|
-
import { dirname as dirname10, isAbsolute as isAbsolute10, join as
|
|
40021
|
+
import { dirname as dirname10, isAbsolute as isAbsolute10, join as join14, relative as relative5, resolve as resolve14 } from "node:path";
|
|
39740
40022
|
import { pathToFileURL } from "node:url";
|
|
39741
40023
|
|
|
39742
40024
|
// src/local-frontend-guard.ts
|
|
@@ -39754,6 +40036,7 @@ const guard = {
|
|
|
39754
40036
|
config.root = settings.directory;
|
|
39755
40037
|
config.server = {
|
|
39756
40038
|
...config.server, host: "127.0.0.1", port: settings.port, strictPort: true,
|
|
40039
|
+
...(settings.authUrl ? { proxy: { ...config.server?.proxy, "/.backify/auth": { target: settings.authUrl, changeOrigin: true } } } : {}),
|
|
39757
40040
|
fs: { ...config.server?.fs, strict: true, deny: [...new Set([...(config.server?.fs?.deny ?? []), ...settings.denied])] }
|
|
39758
40041
|
};
|
|
39759
40042
|
}
|
|
@@ -39803,9 +40086,9 @@ await server.listen();
|
|
|
39803
40086
|
`;
|
|
39804
40087
|
|
|
39805
40088
|
// src/local-static-frontend.ts
|
|
39806
|
-
import { createServer as createServer4 } from "node:http";
|
|
39807
|
-
import { lstatSync as
|
|
39808
|
-
import { extname as extname2, isAbsolute as isAbsolute9, join as
|
|
40089
|
+
import { createServer as createServer4, request as proxyRequest } from "node:http";
|
|
40090
|
+
import { lstatSync as lstatSync13, readFileSync as readFileSync17, realpathSync as realpathSync2, watch } from "node:fs";
|
|
40091
|
+
import { extname as extname2, isAbsolute as isAbsolute9, join as join13, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
|
|
39809
40092
|
var contentTypes = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".txt": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif", ".webp": "image/webp", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf" };
|
|
39810
40093
|
var publicParts = (parts) => parts.every((part) => part.length > 0 && !part.startsWith(".") && !part.includes(":") && !part.includes("\\") && !part.includes("\0") && !["node_modules", "__backify"].includes(part.toLowerCase()));
|
|
39811
40094
|
function publicFile(directory2, pathname) {
|
|
@@ -39815,12 +40098,12 @@ function publicFile(directory2, pathname) {
|
|
|
39815
40098
|
const filename2 = resolve13(directory2, ...parts), part = relative4(directory2, filename2);
|
|
39816
40099
|
if (part === ".." || part.startsWith(".." + sep4) || isAbsolute9(part) || !contentTypes[extname2(filename2).toLowerCase()]) throw new Error("refused");
|
|
39817
40100
|
let current = directory2;
|
|
39818
|
-
if (
|
|
40101
|
+
if (lstatSync13(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
|
|
39819
40102
|
for (const segment of parts) {
|
|
39820
|
-
current =
|
|
39821
|
-
if (
|
|
40103
|
+
current = join13(current, segment);
|
|
40104
|
+
if (lstatSync13(current).isSymbolicLink()) throw new Error("refused");
|
|
39822
40105
|
}
|
|
39823
|
-
const stat =
|
|
40106
|
+
const stat = lstatSync13(filename2);
|
|
39824
40107
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size > 5242880) throw new Error("refused");
|
|
39825
40108
|
return filename2;
|
|
39826
40109
|
}
|
|
@@ -39828,7 +40111,7 @@ function prepareLocalStaticFrontend(directory2) {
|
|
|
39828
40111
|
publicFile(directory2, "/index.html");
|
|
39829
40112
|
return { adapter: "static", directory: directory2 };
|
|
39830
40113
|
}
|
|
39831
|
-
async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
40114
|
+
async function startLocalStaticFrontend(directory2, port, backendUrl, authUrl) {
|
|
39832
40115
|
const assignedPort = await allocateLocalPort(port), url2 = "http://127.0.0.1:" + assignedPort;
|
|
39833
40116
|
let revision = 0;
|
|
39834
40117
|
const reload = '(()=>{let revision=new URL(document.currentScript.src).searchParams.get("revision")??undefined;setInterval(async()=>{try{const response=await fetch("/__backify/revision",{cache:"no-store"});if(!response.ok)return;const current=await response.text();if(revision!==undefined&&revision!==current)location.reload();revision=current;}catch{}},500);})();';
|
|
@@ -39841,6 +40124,18 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
|
39841
40124
|
response.end(request.method === "HEAD" ? void 0 : body);
|
|
39842
40125
|
};
|
|
39843
40126
|
if (request.headers.host !== "127.0.0.1:" + assignedPort || request.headers.origin && request.headers.origin !== url2) return send(403, "text/plain", "Development request refused");
|
|
40127
|
+
if (authUrl && request.url?.startsWith("/.backify/auth/")) {
|
|
40128
|
+
const upstream = proxyRequest(new URL(request.url, authUrl), { method: request.method, headers: { ...request.headers, host: new URL(authUrl).host } }, (incoming) => {
|
|
40129
|
+
response.writeHead(incoming.statusCode ?? 502, incoming.headers);
|
|
40130
|
+
incoming.pipe(response);
|
|
40131
|
+
});
|
|
40132
|
+
upstream.on("error", () => {
|
|
40133
|
+
if (!response.headersSent) send(502, "text/plain", "Local authentication unavailable");
|
|
40134
|
+
else response.destroy();
|
|
40135
|
+
});
|
|
40136
|
+
request.pipe(upstream);
|
|
40137
|
+
return;
|
|
40138
|
+
}
|
|
39844
40139
|
if (!["GET", "HEAD"].includes(request.method ?? "")) return send(405, "text/plain", "Method not allowed");
|
|
39845
40140
|
try {
|
|
39846
40141
|
const pathname = decodeURIComponent((request.url ?? "/").split("?")[0]);
|
|
@@ -39848,7 +40143,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
|
39848
40143
|
if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
|
|
39849
40144
|
if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
|
|
39850
40145
|
const filename2 = publicFile(directory2, pathname);
|
|
39851
|
-
const content =
|
|
40146
|
+
const content = readFileSync17(filename2);
|
|
39852
40147
|
if (content.length > 5242880) throw new Error("refused");
|
|
39853
40148
|
const extension = extname2(filename2).toLowerCase();
|
|
39854
40149
|
const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
|
|
@@ -39898,15 +40193,15 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
|
|
|
39898
40193
|
if (part && part.split(/[\\/]/).some((segment) => segment.startsWith(".") || segment.toLowerCase() === "node_modules")) throw new Error("Static frontend must not use a private state or dependency directory");
|
|
39899
40194
|
return prepareLocalStaticFrontend(directory2);
|
|
39900
40195
|
}
|
|
39901
|
-
if (!
|
|
39902
|
-
const require3 = createRequire3(
|
|
40196
|
+
if (!existsSync12(join14(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
|
|
40197
|
+
const require3 = createRequire3(join14(directory2, "package.json"));
|
|
39903
40198
|
let packagePath;
|
|
39904
40199
|
try {
|
|
39905
40200
|
packagePath = require3.resolve("vite/package.json");
|
|
39906
40201
|
} catch {
|
|
39907
40202
|
throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
|
|
39908
40203
|
}
|
|
39909
|
-
const metadata = JSON.parse(
|
|
40204
|
+
const metadata = JSON.parse(readFileSync18(packagePath, "utf8"));
|
|
39910
40205
|
if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
|
|
39911
40206
|
const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
|
|
39912
40207
|
const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
|
|
@@ -39932,15 +40227,15 @@ async function stopFrontend(child) {
|
|
|
39932
40227
|
else child.kill("SIGTERM");
|
|
39933
40228
|
});
|
|
39934
40229
|
}
|
|
39935
|
-
async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic) {
|
|
39936
|
-
if (prepared.adapter === "static") return startLocalStaticFrontend(prepared.directory, port, backendUrl);
|
|
40230
|
+
async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic, authUrl) {
|
|
40231
|
+
if (prepared.adapter === "static") return startLocalStaticFrontend(prepared.directory, port, backendUrl, authUrl);
|
|
39937
40232
|
const assignedPort = await allocateLocalPort(port);
|
|
39938
40233
|
const url2 = "http://127.0.0.1:" + assignedPort;
|
|
39939
40234
|
const environment = { ...process.env };
|
|
39940
40235
|
for (const name2 of Object.keys(environment)) if (name2.startsWith("BACKIFY_")) delete environment[name2];
|
|
39941
40236
|
if (backendUrl) environment.VITE_BACKIFY_BACKEND_URL = backendUrl;
|
|
39942
40237
|
const denied = [".env", ".env.*", "*.{crt,pem}", "**/.git/**", "**/.backify", "**/.backify/**", "**/.local-secrets", "**/.local-secrets/**", ...prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/"))];
|
|
39943
|
-
const settings = { moduleUrl: pathToFileURL(prepared.modulePath).href, directory: prepared.directory, port: assignedPort, denied, privateFiles: prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/")) };
|
|
40238
|
+
const settings = { authUrl, moduleUrl: pathToFileURL(prepared.modulePath).href, directory: prepared.directory, port: assignedPort, denied, privateFiles: prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/")) };
|
|
39944
40239
|
const launcher = "const settings=" + JSON.stringify(settings) + ";\n" + protectedFrontendSource;
|
|
39945
40240
|
const child = spawn3(process.execPath, ["--input-type=module", "--eval", launcher], { cwd: prepared.directory, windowsHide: true, stdio: ["ignore", onDiagnostic ? "pipe" : 2, onDiagnostic ? "pipe" : 2, "ipc"], env: environment });
|
|
39946
40241
|
if (onDiagnostic) {
|
|
@@ -39974,107 +40269,9 @@ async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic) {
|
|
|
39974
40269
|
}
|
|
39975
40270
|
|
|
39976
40271
|
// src/local-identity.ts
|
|
39977
|
-
import { readFileSync as
|
|
40272
|
+
import { readFileSync as readFileSync19, statSync as statSync2 } from "node:fs";
|
|
39978
40273
|
import { resolve as resolve15 } from "node:path";
|
|
39979
|
-
|
|
39980
|
-
// ../sdk/dist/local-identity.js
|
|
39981
|
-
import { createHash as createHash12, randomBytes as randomBytes4 } from "node:crypto";
|
|
39982
|
-
function createLocalIdentityProvider(options) {
|
|
39983
|
-
const serverOnly = () => {
|
|
39984
|
-
if (typeof window !== "undefined")
|
|
39985
|
-
throw new Error("Local development identities are server-only");
|
|
39986
|
-
};
|
|
39987
|
-
serverOnly();
|
|
39988
|
-
if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
|
|
39989
|
-
throw new Error("Local Backify identities must not run in production");
|
|
39990
|
-
const uuid5 = (value) => typeof value === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
39991
|
-
const text3 = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
|
|
39992
|
-
if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid5(options.scope.organizationId) || !uuid5(options.scope.applicationId) || !uuid5(options.scope.environmentId) || !text3(options.organizationName, 200) || !Array.isArray(options.users) || options.users.length < 1 || options.users.length > 32 || !Array.isArray(options.requestOrigins) || options.requestOrigins.length < 1 || options.requestOrigins.length > 8)
|
|
39993
|
-
throw new Error("Invalid local identity configuration");
|
|
39994
|
-
const scope = { ...options.scope }, organizationName = options.organizationName;
|
|
39995
|
-
const users = /* @__PURE__ */ new Map();
|
|
39996
|
-
for (const user of options.users) {
|
|
39997
|
-
if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid5(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
|
|
39998
|
-
throw new Error("Invalid local identity user");
|
|
39999
|
-
if (user.roles !== void 0 && (!Array.isArray(user.roles) || user.roles.length > 32 || user.roles.some((role) => !role || Object.keys(role).some((name2) => !["name", "permissions"].includes(name2)) || !text3(role.name, 100) || !Array.isArray(role.permissions) || role.permissions.length > 128 || role.permissions.some((permission) => !text3(permission, 100)) || new Set(role.permissions).size !== role.permissions.length) || new Set(user.roles.map((role) => role.name)).size !== user.roles.length))
|
|
40000
|
-
throw new Error("Invalid local identity roles");
|
|
40001
|
-
users.set(user.id, structuredClone(user));
|
|
40002
|
-
}
|
|
40003
|
-
const origins = /* @__PURE__ */ new Set();
|
|
40004
|
-
for (const value of options.requestOrigins) {
|
|
40005
|
-
let origin;
|
|
40006
|
-
try {
|
|
40007
|
-
origin = new URL(value);
|
|
40008
|
-
} catch {
|
|
40009
|
-
throw new Error("Invalid local identity origin");
|
|
40010
|
-
}
|
|
40011
|
-
if (!["http:", "https:"].includes(origin.protocol) || !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname) || origin.origin !== value || origin.username || origin.password || origins.has(value))
|
|
40012
|
-
throw new Error("Local identities require exact loopback origins");
|
|
40013
|
-
origins.add(value);
|
|
40014
|
-
}
|
|
40015
|
-
const clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
40016
|
-
const now = () => {
|
|
40017
|
-
serverOnly();
|
|
40018
|
-
const value = clock();
|
|
40019
|
-
if (!Number.isSafeInteger(value) || value < 0 || value > 253402300499)
|
|
40020
|
-
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
40021
|
-
return value;
|
|
40022
|
-
};
|
|
40023
|
-
const sessions = /* @__PURE__ */ new Map();
|
|
40024
|
-
const digest4 = (token) => createHash12("sha256").update(token).digest("hex");
|
|
40025
|
-
const tokenPattern = /^backify-local-user_[a-zA-Z0-9_-]{43}$/;
|
|
40026
|
-
const requestAuth = {
|
|
40027
|
-
forRequest(request) {
|
|
40028
|
-
serverOnly();
|
|
40029
|
-
const authorization = request.headers.get("authorization"), origin = new URL(request.url).origin;
|
|
40030
|
-
const identity = () => {
|
|
40031
|
-
const time3 = now();
|
|
40032
|
-
if (!origins.has(origin))
|
|
40033
|
-
throw new ApplicationAuthenticationError("application_identity_invalid");
|
|
40034
|
-
if (authorization === null)
|
|
40035
|
-
return null;
|
|
40036
|
-
const match = /^Bearer (backify-local-user_[a-zA-Z0-9_-]{43})$/i.exec(authorization);
|
|
40037
|
-
const session = match && tokenPattern.test(match[1]) ? sessions.get(digest4(match[1])) : void 0;
|
|
40038
|
-
if (!session || session.issued > time3 || session.expires <= time3)
|
|
40039
|
-
throw new ApplicationAuthenticationError("application_identity_invalid");
|
|
40040
|
-
const user = users.get(session.userId);
|
|
40041
|
-
return { ...structuredClone(user), roles: structuredClone(user.roles ?? []), claims: { ...scope, localDevelopment: true } };
|
|
40042
|
-
};
|
|
40043
|
-
return { currentUser: async () => identity(), currentOrganization: async () => identity() ? { id: scope.organizationId, name: organizationName } : null };
|
|
40044
|
-
}
|
|
40045
|
-
};
|
|
40046
|
-
return {
|
|
40047
|
-
requestAuth,
|
|
40048
|
-
profiles() {
|
|
40049
|
-
serverOnly();
|
|
40050
|
-
return [...users.values()].map((user) => structuredClone(user));
|
|
40051
|
-
},
|
|
40052
|
-
issue(userId, lifetimeSeconds = 300) {
|
|
40053
|
-
const time3 = now();
|
|
40054
|
-
if (!users.has(userId) || !Number.isInteger(lifetimeSeconds) || lifetimeSeconds < 1 || lifetimeSeconds > 300)
|
|
40055
|
-
throw new Error("Invalid local identity issuance");
|
|
40056
|
-
for (const [hash2, session] of sessions)
|
|
40057
|
-
if (session.expires <= time3)
|
|
40058
|
-
sessions.delete(hash2);
|
|
40059
|
-
if (sessions.size >= 128)
|
|
40060
|
-
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
40061
|
-
const accessToken = "backify-local-user_" + randomBytes4(32).toString("base64url"), expires = time3 + lifetimeSeconds;
|
|
40062
|
-
sessions.set(digest4(accessToken), { userId, issued: time3, expires });
|
|
40063
|
-
return { accessToken, tokenType: "Bearer", expiresAt: new Date(expires * 1e3).toISOString() };
|
|
40064
|
-
},
|
|
40065
|
-
revoke(accessToken) {
|
|
40066
|
-
serverOnly();
|
|
40067
|
-
return typeof accessToken === "string" && tokenPattern.test(accessToken) && sessions.delete(digest4(accessToken));
|
|
40068
|
-
},
|
|
40069
|
-
clear() {
|
|
40070
|
-
serverOnly();
|
|
40071
|
-
sessions.clear();
|
|
40072
|
-
}
|
|
40073
|
-
};
|
|
40074
|
-
}
|
|
40075
|
-
|
|
40076
|
-
// src/local-identity.ts
|
|
40077
|
-
import { randomUUID as randomUUID8 } from "node:crypto";
|
|
40274
|
+
import { randomUUID as randomUUID9 } from "node:crypto";
|
|
40078
40275
|
function prepareLocalIdentity(root, filename2) {
|
|
40079
40276
|
if (filename2 === void 0) return void 0;
|
|
40080
40277
|
const path = resolve15(root, filename2);
|
|
@@ -40082,19 +40279,19 @@ function prepareLocalIdentity(root, filename2) {
|
|
|
40082
40279
|
if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
|
|
40083
40280
|
let input;
|
|
40084
40281
|
try {
|
|
40085
|
-
input = JSON.parse(
|
|
40282
|
+
input = JSON.parse(readFileSync19(path, "utf8"));
|
|
40086
40283
|
} catch {
|
|
40087
40284
|
throw new Error("Invalid local identity profile JSON");
|
|
40088
40285
|
}
|
|
40089
40286
|
if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((name2) => !["version", "organizationName", "users"].includes(name2))) throw new Error("Invalid local identity profiles");
|
|
40090
40287
|
const value = input;
|
|
40091
40288
|
if (value.version !== 1) throw new Error("Invalid local identity profile version");
|
|
40092
|
-
const identity = createLocalIdentityProvider({ scope: { organizationId:
|
|
40289
|
+
const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID9(), applicationId: randomUUID9(), environmentId: randomUUID9() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
|
|
40093
40290
|
return { organizationName: value.organizationName, users: identity.profiles() };
|
|
40094
40291
|
}
|
|
40095
40292
|
function localIdentityCommand(args2) {
|
|
40096
40293
|
const kind = args2[0];
|
|
40097
|
-
if (!["users", "issue", "clear"].includes(kind)) throw new Error("Use backify identity users|issue|clear --local [--json]");
|
|
40294
|
+
if (!["users", "inbox", "issue", "clear"].includes(kind)) throw new Error("Use backify identity users|inbox|issue|clear --local [--json]");
|
|
40098
40295
|
const flags = /* @__PURE__ */ new Set();
|
|
40099
40296
|
let userId;
|
|
40100
40297
|
for (let index = 1; index < args2.length; index++) {
|
|
@@ -40115,7 +40312,7 @@ function localIdentityCommand(args2) {
|
|
|
40115
40312
|
}
|
|
40116
40313
|
|
|
40117
40314
|
// src/local-job-history.ts
|
|
40118
|
-
import { lstatSync as
|
|
40315
|
+
import { lstatSync as lstatSync14, readFileSync as readFileSync20 } from "node:fs";
|
|
40119
40316
|
import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
|
|
40120
40317
|
function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
40121
40318
|
if (filename2 === void 0) return [];
|
|
@@ -40123,9 +40320,9 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
40123
40320
|
if (typeof filename3 !== "string" || !filename3 || isAbsolute11(filename3)) throw new Error();
|
|
40124
40321
|
const path = resolve16(root, filename3);
|
|
40125
40322
|
assertLocalStatePath(root, path);
|
|
40126
|
-
const metadata =
|
|
40323
|
+
const metadata = lstatSync14(path);
|
|
40127
40324
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
40128
|
-
const bytes =
|
|
40325
|
+
const bytes = readFileSync20(path);
|
|
40129
40326
|
if (bytes.length > maximum) throw new Error();
|
|
40130
40327
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
40131
40328
|
};
|
|
@@ -40171,14 +40368,14 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
40171
40368
|
}
|
|
40172
40369
|
|
|
40173
40370
|
// src/local-secrets.ts
|
|
40174
|
-
import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as
|
|
40175
|
-
import { closeSync as closeSync3, existsSync as
|
|
40176
|
-
import { dirname as dirname11, isAbsolute as isAbsolute12, join as
|
|
40371
|
+
import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID10 } from "node:crypto";
|
|
40372
|
+
import { closeSync as closeSync3, existsSync as existsSync13, fsyncSync as fsyncSync3, lstatSync as lstatSync15, mkdirSync as mkdirSync5, openSync as openSync3, readFileSync as readFileSync21, realpathSync as realpathSync4, writeFileSync as writeFileSync11 } from "node:fs";
|
|
40373
|
+
import { dirname as dirname11, isAbsolute as isAbsolute12, join as join15, relative as relative6, resolve as resolve17 } from "node:path";
|
|
40177
40374
|
var maximumBytes2 = 1048576;
|
|
40178
40375
|
var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
|
|
40179
40376
|
var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
|
|
40180
40377
|
function vaultPath(root) {
|
|
40181
|
-
return
|
|
40378
|
+
return join15(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
|
|
40182
40379
|
}
|
|
40183
40380
|
function inside(root, filename2) {
|
|
40184
40381
|
const part = relative6(root, filename2);
|
|
@@ -40186,12 +40383,12 @@ function inside(root, filename2) {
|
|
|
40186
40383
|
}
|
|
40187
40384
|
function privateFile(filename2, limit) {
|
|
40188
40385
|
for (let current = resolve17(filename2); ; current = dirname11(current)) {
|
|
40189
|
-
if (
|
|
40386
|
+
if (lstatSync15(current).isSymbolicLink()) throw failure();
|
|
40190
40387
|
if (dirname11(current) === current) break;
|
|
40191
40388
|
}
|
|
40192
|
-
const stat =
|
|
40389
|
+
const stat = lstatSync15(filename2);
|
|
40193
40390
|
if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
|
|
40194
|
-
return
|
|
40391
|
+
return readFileSync21(filename2);
|
|
40195
40392
|
}
|
|
40196
40393
|
function externalKey(root, filename2) {
|
|
40197
40394
|
const keyFile = resolve17(filename2);
|
|
@@ -40223,22 +40420,22 @@ function encrypt(root, application, key, secrets) {
|
|
|
40223
40420
|
function writePrivate2(filename2, value) {
|
|
40224
40421
|
const descriptor2 = openSync3(filename2, "wx", 384);
|
|
40225
40422
|
try {
|
|
40226
|
-
|
|
40423
|
+
writeFileSync11(descriptor2, value);
|
|
40227
40424
|
fsyncSync3(descriptor2);
|
|
40228
40425
|
} finally {
|
|
40229
40426
|
closeSync3(descriptor2);
|
|
40230
40427
|
}
|
|
40231
40428
|
}
|
|
40232
40429
|
function ensureIgnored(root) {
|
|
40233
|
-
const filename2 =
|
|
40430
|
+
const filename2 = join15(root, ".gitignore");
|
|
40234
40431
|
assertLocalStatePath(root, filename2);
|
|
40235
|
-
const current =
|
|
40236
|
-
if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/"))
|
|
40432
|
+
const current = existsSync13(filename2) ? readFileSync21(filename2, "utf8") : "";
|
|
40433
|
+
if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
|
|
40237
40434
|
}
|
|
40238
40435
|
function readLocalSecrets(root, application, keyFile) {
|
|
40239
40436
|
const filename2 = vaultPath(root);
|
|
40240
40437
|
assertLocalStatePath(root, filename2);
|
|
40241
|
-
if (!
|
|
40438
|
+
if (!existsSync13(filename2) && keyFile === void 0) return {};
|
|
40242
40439
|
if (!keyFile) throw new Error("Encrypted local secrets require --local-secrets-key <external-key-file>");
|
|
40243
40440
|
let key, plaintext;
|
|
40244
40441
|
try {
|
|
@@ -40268,10 +40465,10 @@ function readLocalSecrets(root, application, keyFile) {
|
|
|
40268
40465
|
function initializeLocalSecrets(root, application, keyFile) {
|
|
40269
40466
|
const filename2 = vaultPath(root), external = resolve17(keyFile);
|
|
40270
40467
|
assertLocalStatePath(root, filename2);
|
|
40271
|
-
if (
|
|
40468
|
+
if (existsSync13(filename2) || existsSync13(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
|
|
40272
40469
|
if (inside(realpathSync4(root), external) || inside(realpathSync4(root), realpathSync4(dirname11(external)))) throw new Error("Local secret key must be outside the repository in an existing private directory");
|
|
40273
40470
|
for (let current = dirname11(external); ; current = dirname11(current)) {
|
|
40274
|
-
const stat =
|
|
40471
|
+
const stat = lstatSync15(current);
|
|
40275
40472
|
if (stat.isSymbolicLink()) throw failure();
|
|
40276
40473
|
if (current === dirname11(external) && process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
|
|
40277
40474
|
if (dirname11(current) === current) break;
|
|
@@ -40280,7 +40477,7 @@ function initializeLocalSecrets(root, application, keyFile) {
|
|
|
40280
40477
|
const release2 = acquireLocalLease(root, ".backify/dev/secrets.lock");
|
|
40281
40478
|
const key = randomBytes5(32);
|
|
40282
40479
|
try {
|
|
40283
|
-
if (
|
|
40480
|
+
if (existsSync13(filename2)) throw failure();
|
|
40284
40481
|
mkdirSync5(dirname11(filename2), { recursive: true, mode: 448 });
|
|
40285
40482
|
writePrivate2(external, key.toString("hex"));
|
|
40286
40483
|
writePrivate2(filename2, encrypt(root, application, key, {}));
|
|
@@ -40300,7 +40497,7 @@ function setLocalSecret(root, application, keyFile, name2, value) {
|
|
|
40300
40497
|
const secrets = readLocalSecrets(root, application, keyFile);
|
|
40301
40498
|
secrets[name2] = value;
|
|
40302
40499
|
key = externalKey(root, keyFile);
|
|
40303
|
-
const temporary = filename2 + "." +
|
|
40500
|
+
const temporary = filename2 + "." + randomUUID10() + ".tmp";
|
|
40304
40501
|
assertLocalStatePath(root, temporary);
|
|
40305
40502
|
writePrivate2(temporary, encrypt(root, application, key, secrets));
|
|
40306
40503
|
renameLocalFile(temporary, filename2);
|
|
@@ -40337,11 +40534,11 @@ async function localSecretsCommand(args2, root, application, input = process.std
|
|
|
40337
40534
|
|
|
40338
40535
|
// src/local-development.ts
|
|
40339
40536
|
function localManifest(root = process.cwd()) {
|
|
40340
|
-
const filename2 =
|
|
40341
|
-
if (!
|
|
40342
|
-
const manifest = parseApplicationManifest(
|
|
40537
|
+
const filename2 = join16(root, "backify.yaml");
|
|
40538
|
+
if (!existsSync14(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
|
|
40539
|
+
const manifest = parseApplicationManifest(readFileSync22(filename2, "utf8"));
|
|
40343
40540
|
const entry = resolve18(root, manifest.runtime.entrypoint);
|
|
40344
|
-
if (!
|
|
40541
|
+
if (!existsSync14(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
|
|
40345
40542
|
const discovered = analyzeSources(repositorySources(root));
|
|
40346
40543
|
const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
|
|
40347
40544
|
if (diagnostics.length) throw new Error(diagnostics.map((diagnostic) => diagnostic.message).join("; "));
|
|
@@ -40352,12 +40549,12 @@ function inside2(root, path) {
|
|
|
40352
40549
|
return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
|
|
40353
40550
|
}
|
|
40354
40551
|
function sessionPath(root) {
|
|
40355
|
-
return
|
|
40552
|
+
return join16(root, ".backify", "dev", "session.json");
|
|
40356
40553
|
}
|
|
40357
40554
|
async function localRequest(path, input, root = process.cwd()) {
|
|
40358
40555
|
if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
|
|
40359
|
-
if (!
|
|
40360
|
-
const session = JSON.parse(
|
|
40556
|
+
if (!existsSync14(sessionPath(root))) throw new Error("Start backify dev before using local commands");
|
|
40557
|
+
const session = JSON.parse(readFileSync22(sessionPath(root), "utf8"));
|
|
40361
40558
|
if (session.version !== 1 || !Number.isInteger(session.port) || session.port < 1 || session.port > 65535 || !/^[a-f0-9]{64}$/.test(session.token)) throw new Error("Invalid local session");
|
|
40362
40559
|
const response = await fetch("http://127.0.0.1:" + session.port + path, { method: input === void 0 ? "GET" : "POST", headers: { authorization: "Bearer " + session.token, "content-type": "application/json" }, body: input === void 0 ? void 0 : JSON.stringify(input), redirect: "error", signal: AbortSignal.timeout(35e3) });
|
|
40363
40560
|
if (!response.ok) {
|
|
@@ -40408,17 +40605,17 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40408
40605
|
const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
|
|
40409
40606
|
if (identityProfiles && (!manifest.capabilities.auth || manifest.capabilities.auth.enabled === false || options.backendPort === void 0)) throw new Error("Explicit local identities require capabilities.auth and --backend-port");
|
|
40410
40607
|
const preparedFrontend = prepareLocalFrontend(root, options, options.localSecretsKey ? [realpathSync5(resolve18(options.localSecretsKey))] : []);
|
|
40411
|
-
const ignorePath =
|
|
40412
|
-
if (
|
|
40413
|
-
const ignore =
|
|
40414
|
-
if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/"))
|
|
40608
|
+
const ignorePath = join16(root, ".gitignore");
|
|
40609
|
+
if (existsSync14(ignorePath) && lstatSync16(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
|
|
40610
|
+
const ignore = existsSync14(ignorePath) ? readFileSync22(ignorePath, "utf8") : "";
|
|
40611
|
+
if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync12(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
|
|
40415
40612
|
if (options.port !== void 0 && (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)) throw new Error("Dashboard port must be 0-65535");
|
|
40416
|
-
const directory2 =
|
|
40613
|
+
const directory2 = join16(root, ".backify", "dev");
|
|
40417
40614
|
assertLocalStatePath(root, directory2);
|
|
40418
|
-
for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root,
|
|
40615
|
+
for (const filename2 of ["session.json", "session.json.tmp", "worker.mjs", "worker.mjs.map", "state.json", "state.json.tmp"]) assertLocalStatePath(root, join16(directory2, filename2));
|
|
40419
40616
|
mkdirSync6(directory2, { recursive: true });
|
|
40420
40617
|
if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
|
|
40421
|
-
if (
|
|
40618
|
+
if (existsSync14(sessionPath(root))) {
|
|
40422
40619
|
try {
|
|
40423
40620
|
await localRequest("/v1/status", void 0, root);
|
|
40424
40621
|
throw new Error("Backify dev is already running for this repository");
|
|
@@ -40432,14 +40629,15 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40432
40629
|
if (jobWorker && mode !== "full") throw new Error("Native jobs require full-fidelity local mode");
|
|
40433
40630
|
const backendPort = options.backendPort === void 0 ? void 0 : await allocateLocalPort(options.backendPort);
|
|
40434
40631
|
const backendUrl = backendPort === void 0 ? void 0 : "http://127.0.0.1:" + backendPort;
|
|
40435
|
-
|
|
40632
|
+
let dashboardPort = await allocateLocalPort(options.port);
|
|
40633
|
+
const explicitPorts = [dashboardPort, backendPort, options.frontendPort, options.hcrPort, options.databasePort].filter((port) => port !== void 0 && port !== 0);
|
|
40436
40634
|
if (new Set(explicitPorts).size !== explicitPorts.length) throw new Error("Local service ports must be distinct");
|
|
40437
40635
|
const releaseLease = acquireLocalLease(root);
|
|
40438
40636
|
let services;
|
|
40439
40637
|
let frontend;
|
|
40440
40638
|
try {
|
|
40441
40639
|
if (mode === "full") services = await startLocalServices(root, manifest, { ...options, jobArtifacts, jobIdentityScope: jobWorker?.authTrust?.scope });
|
|
40442
|
-
if (preparedFrontend) frontend = await startLocalFrontend(preparedFrontend, options.frontendPort, backendUrl, options.onDiagnostic);
|
|
40640
|
+
if (preparedFrontend) frontend = await startLocalFrontend(preparedFrontend, options.frontendPort, backendUrl, options.onDiagnostic, identityProfiles ? "http://127.0.0.1:" + dashboardPort : void 0);
|
|
40443
40641
|
} catch (error2) {
|
|
40444
40642
|
try {
|
|
40445
40643
|
await services?.stop();
|
|
@@ -40449,14 +40647,14 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40449
40647
|
throw error2;
|
|
40450
40648
|
}
|
|
40451
40649
|
const token = randomBytes6(32).toString("hex");
|
|
40452
|
-
const identityScope = services?.identityScope ?? { organizationId:
|
|
40650
|
+
const identityScope = services?.identityScope ?? { organizationId: randomUUID11(), applicationId: randomUUID11(), environmentId: randomUUID11() };
|
|
40453
40651
|
const workerEnvironment = (worker) => {
|
|
40454
40652
|
if (!worker.authTrust) return worker;
|
|
40455
40653
|
const { renewal, ...authTrust } = worker.authTrust;
|
|
40456
40654
|
return { ...worker, authTrust };
|
|
40457
40655
|
};
|
|
40458
40656
|
const identityEnvironment = () => ({ BACKIFY_LOCAL_IDENTITY: identityProfiles ? JSON.stringify({ ...identityProfiles, scope: identityScope, requestOrigins: [backendUrl, frontend?.url].filter(Boolean) }) : "", BACKIFY_LOCAL_JOB_WORKER: jobWorker ? JSON.stringify({ ...workerEnvironment(jobWorker), scope: identityScope, historicalWorkers: historicalWorkers.map(workerEnvironment) }) : "", BACKIFY_LOCAL_JOBS: services?.jobs ? "postgres-jobs" : "snapshot-emulator" });
|
|
40459
|
-
const outfile =
|
|
40657
|
+
const outfile = join16(directory2, "worker.mjs");
|
|
40460
40658
|
let child;
|
|
40461
40659
|
const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
|
|
40462
40660
|
if (child?.connected) child.send({ type: "trust-renewed", workers: activeWorkers.filter((worker) => worker.authTrust).map((worker) => ({ artifactVersion: worker.artifact.artifactVersion, revision: worker.authTrust.revision, trustDigest: worker.authTrust.trustDigest })) }, (error2) => {
|
|
@@ -40465,7 +40663,6 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40465
40663
|
} });
|
|
40466
40664
|
let buildContext;
|
|
40467
40665
|
let stopping = false;
|
|
40468
|
-
let dashboardPort = options.port ?? 0;
|
|
40469
40666
|
let dashboardOpened = false;
|
|
40470
40667
|
let restarting = Promise.resolve();
|
|
40471
40668
|
let resolveStartup = () => {
|
|
@@ -40494,8 +40691,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40494
40691
|
}
|
|
40495
40692
|
await stopChild(child);
|
|
40496
40693
|
if (stopping) return;
|
|
40497
|
-
const version2 = createHash13("sha256").update(
|
|
40498
|
-
const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", options.onDiagnostic ? "pipe" : 2, options.onDiagnostic ? "pipe" : 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE:
|
|
40694
|
+
const version2 = createHash13("sha256").update(readFileSync22(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
|
|
40695
|
+
const worker = spawn4(process.execPath, [outfile], { cwd: root, windowsHide: true, stdio: ["ignore", options.onDiagnostic ? "pipe" : 2, options.onDiagnostic ? "pipe" : 2, "ipc"], env: { ...process.env, ...identityEnvironment(), BACKIFY_LOCAL_SECRETS_IPC: "1", HOST: "127.0.0.1", ...backendPort === void 0 ? {} : { PORT: String(backendPort) }, BACKIFY_LOCAL_BACKEND_URL: backendUrl ?? "", BACKIFY_LOCAL_FRONTEND_URL: frontend?.url ?? "", BACKIFY_LOCAL_DATABASE_ENABLED: manifest.capabilities.database && manifest.capabilities.database.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_ENABLED: manifest.capabilities.storage && manifest.capabilities.storage.enabled !== false ? "1" : "0", BACKIFY_LOCAL_STORAGE_BUCKETS: JSON.stringify(manifest.capabilities.storage?.buckets?.map((bucket) => bucket.name) ?? (manifest.capabilities.storage ? ["default"] : [])), BACKIFY_LOCAL_TOKEN: token, BACKIFY_LOCAL_PORT: String(dashboardPort), BACKIFY_LOCAL_STATE: join16(directory2, "state.json"), BACKIFY_LOCAL_VERSION: version2, BACKIFY_LOCAL_HCR_URL: services?.runtimeUrl ?? "", BACKIFY_LOCAL_WORKLOAD_TOKEN_PATH: services?.tokenPath ?? "", BACKIFY_LOCAL_DATABASE: services ? services.database ? "postgres" : "disabled" : "document-emulator", BACKIFY_LOCAL_EVENTS: services?.events ? "postgres-events" : services ? "disabled" : "snapshot-emulator", BACKIFY_LOCAL_STORAGE: services ? services.storage ? "filesystem" : "disabled" : "snapshot-emulator" } });
|
|
40499
40696
|
if (options.onDiagnostic) {
|
|
40500
40697
|
worker.stdout?.on("data", (chunk) => options.onDiagnostic(chunk.toString()));
|
|
40501
40698
|
worker.stderr?.on("data", (chunk) => options.onDiagnostic(chunk.toString()));
|
|
@@ -40521,7 +40718,7 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40521
40718
|
workerReady = true;
|
|
40522
40719
|
const session = { version: 1, port: message.port, token, pid: worker.pid };
|
|
40523
40720
|
const temp = sessionPath(root) + ".tmp";
|
|
40524
|
-
|
|
40721
|
+
writeFileSync12(temp, JSON.stringify(session), { mode: 384 });
|
|
40525
40722
|
renameLocalFile(temp, sessionPath(root));
|
|
40526
40723
|
const url2 = "http://127.0.0.1:" + message.port;
|
|
40527
40724
|
options.onReady?.(url2, { frontendUrl: frontend?.url, backendUrl });
|
|
@@ -40541,9 +40738,9 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40541
40738
|
if (services && JSON.stringify(updated.capabilities) !== JSON.stringify(manifest.capabilities)) throw new Error("Full-fidelity capability or migration intent changed; restart backify dev to review and apply it");
|
|
40542
40739
|
if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
|
|
40543
40740
|
} catch (error2) {
|
|
40544
|
-
return { errors: [{ text: error2 instanceof Error ? error2.message : "Manifest validation failed" }], watchFiles: [
|
|
40741
|
+
return { errors: [{ text: error2 instanceof Error ? error2.message : "Manifest validation failed" }], watchFiles: [join16(root, "backify.yaml")] };
|
|
40545
40742
|
}
|
|
40546
|
-
return { contents:
|
|
40743
|
+
return { contents: readFileSync22(input.path, "utf8"), loader: input.path.endsWith(".tsx") ? "tsx" : /\.(ts|mts|cts)$/.test(input.path) ? "ts" : input.path.endsWith(".jsx") ? "jsx" : "js", watchFiles: [join16(root, "backify.yaml")] };
|
|
40547
40744
|
});
|
|
40548
40745
|
build3.onEnd((result) => {
|
|
40549
40746
|
if (options.onDiagnostic) {
|
|
@@ -40602,8 +40799,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40602
40799
|
}
|
|
40603
40800
|
}
|
|
40604
40801
|
}
|
|
40605
|
-
if (
|
|
40606
|
-
const session = JSON.parse(
|
|
40802
|
+
if (existsSync14(sessionPath(root))) {
|
|
40803
|
+
const session = JSON.parse(readFileSync22(sessionPath(root), "utf8"));
|
|
40607
40804
|
if (session.token === token) unlinkSync5(sessionPath(root));
|
|
40608
40805
|
}
|
|
40609
40806
|
};
|
|
@@ -40617,11 +40814,11 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40617
40814
|
}
|
|
40618
40815
|
async function runLocalTests(root = process.cwd()) {
|
|
40619
40816
|
const manifest = localManifest(root);
|
|
40620
|
-
const project = JSON.parse(
|
|
40817
|
+
const project = JSON.parse(readFileSync22(join16(root, "package.json"), "utf8"));
|
|
40621
40818
|
if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
|
|
40622
40819
|
const result = await new Promise((resolveResult, reject) => {
|
|
40623
|
-
const npmPath = process.platform === "win32" ? process.env.npm_execpath ??
|
|
40624
|
-
if (npmPath && !
|
|
40820
|
+
const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join16(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
|
|
40821
|
+
if (npmPath && !existsSync14(npmPath)) {
|
|
40625
40822
|
reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
|
|
40626
40823
|
return;
|
|
40627
40824
|
}
|
|
@@ -40648,7 +40845,7 @@ function digest3(contents) {
|
|
|
40648
40845
|
}
|
|
40649
40846
|
function packageDirectory(filename2) {
|
|
40650
40847
|
for (let current = dirname13(filename2); ; current = dirname13(current)) {
|
|
40651
|
-
if (
|
|
40848
|
+
if (existsSync15(join17(current, "package.json"))) return current;
|
|
40652
40849
|
if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
|
|
40653
40850
|
}
|
|
40654
40851
|
}
|
|
@@ -40760,11 +40957,11 @@ async function prepareWorkload(options) {
|
|
|
40760
40957
|
context3.onResolve({ filter: /./ }, async (input) => {
|
|
40761
40958
|
if (input.pluginData?.backifyResolved) return;
|
|
40762
40959
|
if (input.path === "@backifydev/sdk/local" || input.path === "@backifydev/sdk/runtime" && input.namespace !== "backify-workload-host") return { errors: [{ text: "Production application code must not import local emulators or host-only runtime configuration" }] };
|
|
40763
|
-
const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ?
|
|
40960
|
+
const resolved = await context3.resolve(input.path, { importer: input.namespace === "backify-workload-host" ? join17(root, input.importer) : input.importer, resolveDir: input.resolveDir, kind: input.kind, pluginData: { backifyResolved: true } });
|
|
40764
40961
|
if (!resolved.external && !resolved.errors.length && resolved.path) {
|
|
40765
40962
|
const directory2 = realpathSync6(packageDirectory(resolved.path));
|
|
40766
40963
|
const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
|
|
40767
|
-
if (JSON.parse(
|
|
40964
|
+
if (JSON.parse(readFileSync23(join17(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
|
|
40768
40965
|
if (/^(src|dist)\/local\.(ts|js)$/.test(target) || /^(src|dist)\/runtime\.(ts|js)$/.test(target) && input.namespace !== "backify-workload-host" && !inside3(directory2, realpathSync6(input.importer))) return { errors: [{ text: "Production application code must not import local emulators or host-only runtime configuration" }] };
|
|
40769
40966
|
}
|
|
40770
40967
|
if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
|
|
@@ -40828,28 +41025,28 @@ async function packageWorkload(options) {
|
|
|
40828
41025
|
const files = { "workload.mjs": bundle, "artifact.json": JSON.stringify(plan, null, 2) + "\n", "Dockerfile": dockerfile, ".dockerignore": "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n" };
|
|
40829
41026
|
const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
|
|
40830
41027
|
assertLocalStatePath(root, output);
|
|
40831
|
-
if (
|
|
41028
|
+
if (existsSync15(output)) {
|
|
40832
41029
|
if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
|
|
40833
|
-
assertLocalStatePath(root,
|
|
40834
|
-
return !
|
|
41030
|
+
assertLocalStatePath(root, join17(output, name2));
|
|
41031
|
+
return !readFileSync23(join17(output, name2)).equals(Buffer.from(value));
|
|
40835
41032
|
})) throw new Error("Refusing to overwrite an existing workload artifact directory");
|
|
40836
41033
|
} else {
|
|
40837
41034
|
mkdirSync7(output, { recursive: true });
|
|
40838
|
-
for (const [name2, value] of Object.entries(files))
|
|
41035
|
+
for (const [name2, value] of Object.entries(files)) writeFileSync13(join17(output, name2), value, { flag: "wx", mode: 384 });
|
|
40839
41036
|
}
|
|
40840
41037
|
return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
|
|
40841
41038
|
}
|
|
40842
41039
|
|
|
40843
41040
|
// src/workload-provenance.ts
|
|
40844
41041
|
import { execFileSync } from "node:child_process";
|
|
40845
|
-
import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as
|
|
41042
|
+
import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync14 } from "node:fs";
|
|
40846
41043
|
import { tmpdir } from "node:os";
|
|
40847
|
-
import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as
|
|
41044
|
+
import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join19, relative as relative9, resolve as resolve21 } from "node:path";
|
|
40848
41045
|
|
|
40849
41046
|
// src/workload-provenance-oci.ts
|
|
40850
41047
|
import { createHash as createHash15 } from "node:crypto";
|
|
40851
|
-
import { createReadStream, lstatSync as
|
|
40852
|
-
import { dirname as dirname14, join as
|
|
41048
|
+
import { createReadStream, lstatSync as lstatSync17, readFileSync as readFileSync24 } from "node:fs";
|
|
41049
|
+
import { dirname as dirname14, join as join18, parse as parse3, resolve as resolve20 } from "node:path";
|
|
40853
41050
|
import { Transform, Writable } from "node:stream";
|
|
40854
41051
|
import { pipeline } from "node:stream/promises";
|
|
40855
41052
|
import { createGunzip } from "node:zlib";
|
|
@@ -40866,12 +41063,12 @@ function provenanceRef(value) {
|
|
|
40866
41063
|
function provenanceFile(filename2, maximum) {
|
|
40867
41064
|
const absolute = resolve20(filename2);
|
|
40868
41065
|
for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
|
|
40869
|
-
if (
|
|
41066
|
+
if (lstatSync17(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
|
|
40870
41067
|
if (ancestor === parse3(absolute).root) break;
|
|
40871
41068
|
}
|
|
40872
|
-
const stat =
|
|
41069
|
+
const stat = lstatSync17(absolute);
|
|
40873
41070
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
|
|
40874
|
-
const bytes =
|
|
41071
|
+
const bytes = readFileSync24(absolute);
|
|
40875
41072
|
if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
|
|
40876
41073
|
return bytes;
|
|
40877
41074
|
}
|
|
@@ -40880,7 +41077,7 @@ function descriptor(value) {
|
|
|
40880
41077
|
return value;
|
|
40881
41078
|
}
|
|
40882
41079
|
function blobPath(root, value) {
|
|
40883
|
-
return
|
|
41080
|
+
return join18(root, "blobs", "sha256", descriptor(value).digest.slice(7));
|
|
40884
41081
|
}
|
|
40885
41082
|
function jsonBlob(root, value) {
|
|
40886
41083
|
const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
|
|
@@ -40889,8 +41086,8 @@ function jsonBlob(root, value) {
|
|
|
40889
41086
|
}
|
|
40890
41087
|
async function inspectProvenanceImage(root, architecture, requestedDigest) {
|
|
40891
41088
|
if (!["amd64", "arm64"].includes(architecture) || requestedDigest && !digestPattern.test(requestedDigest)) throw new Error("Invalid OCI platform or digest");
|
|
40892
|
-
if (JSON.parse(provenanceFile(
|
|
40893
|
-
const indexBytes = provenanceFile(
|
|
41089
|
+
if (JSON.parse(provenanceFile(join18(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
|
|
41090
|
+
const indexBytes = provenanceFile(join18(root, "index.json"), 1024 * 1024);
|
|
40894
41091
|
let current = JSON.parse(indexBytes.toString());
|
|
40895
41092
|
let selected;
|
|
40896
41093
|
let manifestDigest = provenanceHash(indexBytes);
|
|
@@ -40949,10 +41146,10 @@ async function inspectProvenanceImage(root, architecture, requestedDigest) {
|
|
|
40949
41146
|
function provenanceFileMetadata(filename2, expectedSize) {
|
|
40950
41147
|
const absolute = resolve20(filename2);
|
|
40951
41148
|
for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
|
|
40952
|
-
if (
|
|
41149
|
+
if (lstatSync17(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
|
|
40953
41150
|
if (ancestor === parse3(absolute).root) break;
|
|
40954
41151
|
}
|
|
40955
|
-
const stat =
|
|
41152
|
+
const stat = lstatSync17(absolute);
|
|
40956
41153
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size !== expectedSize) throw new Error("Invalid OCI layer file");
|
|
40957
41154
|
}
|
|
40958
41155
|
function verifyBaseLineage(base, image2) {
|
|
@@ -41019,17 +41216,17 @@ async function captureWorkloadProvenance(options) {
|
|
|
41019
41216
|
if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
|
|
41020
41217
|
const origin = git2(root, ["remote", "get-url", "origin"]);
|
|
41021
41218
|
if (!["https://github.com/" + options.repository, "https://github.com/" + options.repository + ".git", "git@github.com:" + options.repository + ".git"].includes(origin)) throw new Error("Source repository does not match origin");
|
|
41022
|
-
const lockBytes = provenanceFile(
|
|
41219
|
+
const lockBytes = provenanceFile(join19(root, "package-lock.json"), 16 * 1024 * 1024);
|
|
41023
41220
|
const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
|
|
41024
41221
|
const context3 = resolve21(root, options.context);
|
|
41025
41222
|
if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
|
|
41026
41223
|
const contextDigests = {};
|
|
41027
|
-
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(
|
|
41028
|
-
const plan = boundedJson(
|
|
41224
|
+
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join19(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
|
|
41225
|
+
const plan = boundedJson(join19(context3, "artifact.json"));
|
|
41029
41226
|
const baseDigest = provenanceRef(options.baseImage);
|
|
41030
41227
|
if (plan.schemaVersion !== 1 || plan.kind !== "worker" || plan.baseImage !== options.baseImage || !/^[a-f0-9]{64}$/.test(plan.artifactVersion) || !/^[a-f0-9]{64}$/.test(plan.manifestVersion) || contextDigests["workload.mjs"] !== "sha256:" + plan.artifactVersion || typeof plan.entrypoint !== "string") throw new Error("Worker context does not match artifact metadata");
|
|
41031
41228
|
const dockerfile = ["FROM " + options.baseImage, "WORKDIR /app", "COPY --chown=1000:1000 workload.mjs artifact.json ./", "ENV NODE_ENV=production PORT=8080 BACKIFY_ARTIFACT_SHA256=" + plan.artifactVersion + " BACKIFY_WORKLOAD_TOKEN_FILE=/run/backify/workload/token", "USER 1000:1000", "STOPSIGNAL SIGTERM", 'ENTRYPOINT ["node", "workload.mjs"]', ""].join("\n");
|
|
41032
|
-
if (!provenanceFile(
|
|
41229
|
+
if (!provenanceFile(join19(context3, "Dockerfile"), 65536).equals(Buffer.from(dockerfile)) || provenanceFile(join19(context3, ".dockerignore"), 65536).toString() !== "**\n!Dockerfile\n!workload.mjs\n!artifact.json\n!.dockerignore\n") throw new Error("Unreviewed workload build recipe");
|
|
41033
41230
|
const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
|
|
41034
41231
|
const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
|
|
41035
41232
|
verifyBaseLineage(base, image2);
|
|
@@ -41105,16 +41302,16 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
|
|
|
41105
41302
|
evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
|
|
41106
41303
|
}
|
|
41107
41304
|
const scratchRoot = resolve21(tmpdir());
|
|
41108
|
-
const scratch = mkdtempSync2(
|
|
41305
|
+
const scratch = mkdtempSync2(join19(scratchRoot, "backify-provenance-"));
|
|
41109
41306
|
if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
|
|
41110
41307
|
try {
|
|
41111
|
-
mkdirSync8(
|
|
41112
|
-
const trustedRoot =
|
|
41113
|
-
|
|
41308
|
+
mkdirSync8(join19(scratch, "evidence"), { mode: 448 });
|
|
41309
|
+
const trustedRoot = join19(scratch, "evidence", "trusted-root.jsonl");
|
|
41310
|
+
writeFileSync14(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
|
|
41114
41311
|
for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
|
|
41115
|
-
const report =
|
|
41116
|
-
|
|
41117
|
-
|
|
41312
|
+
const report = join19(scratch, "evidence", "report-" + index + ".json"), bundle = join19(scratch, "evidence", "bundle-" + index + ".jsonl");
|
|
41313
|
+
writeFileSync14(report, bytes, { flag: "wx", mode: 384 });
|
|
41314
|
+
writeFileSync14(bundle, bundleBytes, { flag: "wx", mode: 384 });
|
|
41118
41315
|
try {
|
|
41119
41316
|
const result = execFileSync("gh", ["attestation", "verify", report, "--bundle", bundle, "--custom-trusted-root", trustedRoot, "--hostname", "github.com", "--repo", identity.repository, "--signer-workflow", identity.signerWorkflow, "--signer-digest", identity.signerDigest, "--source-digest", identity.sourceCommit, "--source-ref", identity.sourceRef, "--deny-self-hosted-runners", "--predicate-type", "https://slsa.dev/provenance/v1", "--format", "json"], { encoding: "utf8", windowsHide: true, timeout: 12e4, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
41120
41317
|
if (!Array.isArray(JSON.parse(result)) || !JSON.parse(result).length) throw new Error();
|
|
@@ -41145,12 +41342,12 @@ async function workloadProvenanceCommand(args2) {
|
|
|
41145
41342
|
return verifyWorkloadProvenance({ policy: required2("--policy"), firstReport: options.get("--report") ?? required2("--first-report"), firstBundle: options.get("--bundle") ?? required2("--first-bundle"), secondReport: options.get("--second-report"), secondBundle: options.get("--second-bundle"), baseSubject: options.get("--base-subject"), baseBundle: options.get("--base-bundle"), trustedRoot: required2("--trusted-root") });
|
|
41146
41343
|
}
|
|
41147
41344
|
const result = await captureWorkloadProvenance({ root: options.get("--root"), repository: required2("--repository"), application: required2("--application"), context: required2("--context"), baseLayout: required2("--base-layout"), imageLayout: required2("--image-layout"), baseImage: required2("--base-image"), architecture: required2("--architecture"), replica: options.get("--replica") ?? "first" });
|
|
41148
|
-
|
|
41345
|
+
writeFileSync14(resolve21(required2("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
|
|
41149
41346
|
return { schemaVersion: 1, status: "captured-unsigned", deploymentReady: false, reportDigest: provenanceHash(JSON.stringify(result, null, 2) + "\n") };
|
|
41150
41347
|
}
|
|
41151
41348
|
|
|
41152
41349
|
// src/workload-trust-state.ts
|
|
41153
|
-
import { lstatSync as
|
|
41350
|
+
import { lstatSync as lstatSync18, readFileSync as readFileSync25 } from "node:fs";
|
|
41154
41351
|
import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
|
|
41155
41352
|
function parseWorkloadTrustState(args2) {
|
|
41156
41353
|
const action = args2[0];
|
|
@@ -41176,9 +41373,9 @@ function workloadTrustState(options) {
|
|
|
41176
41373
|
if (!["plan", "initialize"].includes(options.action) || !isAbsolute16(options.trustFile) || !isAbsolute16(options.stateFile) || resolve22(options.trustFile) === resolve22(options.stateFile) || !Number.isSafeInteger(options.expectedRevision) || options.expectedRevision < 1) throw new Error("Specify separate absolute trust/state paths and a positive reviewed revision");
|
|
41177
41374
|
let trust;
|
|
41178
41375
|
try {
|
|
41179
|
-
const metadata =
|
|
41376
|
+
const metadata = lstatSync18(options.trustFile);
|
|
41180
41377
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
|
|
41181
|
-
const bytes =
|
|
41378
|
+
const bytes = readFileSync25(options.trustFile);
|
|
41182
41379
|
if (bytes.length > 131072) throw new Error();
|
|
41183
41380
|
trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
41184
41381
|
} catch {
|
|
@@ -41194,8 +41391,8 @@ function workloadTrustState(options) {
|
|
|
41194
41391
|
}
|
|
41195
41392
|
|
|
41196
41393
|
// src/scaffold.ts
|
|
41197
|
-
import { existsSync as
|
|
41198
|
-
import { dirname as dirname16, join as
|
|
41394
|
+
import { existsSync as existsSync16, lstatSync as lstatSync19, mkdirSync as mkdirSync9, readFileSync as readFileSync26, readdirSync as readdirSync8, realpathSync as realpathSync7, writeFileSync as writeFileSync15 } from "node:fs";
|
|
41395
|
+
import { dirname as dirname16, join as join20, relative as relative10, resolve as resolve23 } from "node:path";
|
|
41199
41396
|
|
|
41200
41397
|
// src/task-template.ts
|
|
41201
41398
|
function json2(value) {
|
|
@@ -41603,20 +41800,20 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
|
|
|
41603
41800
|
function scaffoldFullStack(options) {
|
|
41604
41801
|
const files = fullStackTemplate(options.appId, options.name, options.template);
|
|
41605
41802
|
const root = resolve23(options.root ?? process.cwd());
|
|
41606
|
-
if (!
|
|
41803
|
+
if (!existsSync16(root) || !lstatSync19(root).isDirectory() || lstatSync19(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
|
|
41607
41804
|
const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
|
|
41608
41805
|
if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
|
|
41609
41806
|
const canonicalRoot = realpathSync7(root);
|
|
41610
41807
|
const pending = [];
|
|
41611
41808
|
for (const [filename2, content] of Object.entries(files)) {
|
|
41612
|
-
const destination =
|
|
41809
|
+
const destination = join20(root, filename2);
|
|
41613
41810
|
let current = destination;
|
|
41614
41811
|
while (current !== root) {
|
|
41615
41812
|
try {
|
|
41616
|
-
const stat =
|
|
41813
|
+
const stat = lstatSync19(current);
|
|
41617
41814
|
if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
|
|
41618
41815
|
if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
|
|
41619
|
-
if (current === destination && (!stat.isFile() ||
|
|
41816
|
+
if (current === destination && (!stat.isFile() || readFileSync26(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
|
|
41620
41817
|
} catch (error2) {
|
|
41621
41818
|
if (!(error2 instanceof Error) || !("code" in error2) || error2.code !== "ENOENT") throw error2;
|
|
41622
41819
|
if (current === destination) pending.push(filename2);
|
|
@@ -41625,9 +41822,9 @@ function scaffoldFullStack(options) {
|
|
|
41625
41822
|
}
|
|
41626
41823
|
}
|
|
41627
41824
|
for (const filename2 of pending) {
|
|
41628
|
-
const destination =
|
|
41825
|
+
const destination = join20(root, filename2);
|
|
41629
41826
|
mkdirSync9(dirname16(destination), { recursive: true });
|
|
41630
|
-
|
|
41827
|
+
writeFileSync15(destination, files[filename2], { flag: "wx" });
|
|
41631
41828
|
}
|
|
41632
41829
|
return { template: options.template === "tasks" ? "react-vite-hono-tasks" : "react-vite-hono", created: pending, unchanged: Object.keys(files).length - pending.length, installed: false, deployed: false };
|
|
41633
41830
|
}
|
|
@@ -41671,16 +41868,16 @@ function localInspectionCommand(args2) {
|
|
|
41671
41868
|
}
|
|
41672
41869
|
|
|
41673
41870
|
// src/index.ts
|
|
41674
|
-
import { readFileSync as
|
|
41871
|
+
import { readFileSync as readFileSync29, existsSync as existsSync18, rmSync as rmSync3 } from "node:fs";
|
|
41675
41872
|
import { homedir as homedir3 } from "node:os";
|
|
41676
|
-
import { join as
|
|
41873
|
+
import { join as join23 } from "node:path";
|
|
41677
41874
|
import { spawn as spawn5 } from "node:child_process";
|
|
41678
41875
|
var [command2, ...args] = process.argv.slice(2);
|
|
41679
|
-
var configPath =
|
|
41680
|
-
var userConfig = command2 !== "mcp" &&
|
|
41876
|
+
var configPath = join23(homedir3(), ".backify.json");
|
|
41877
|
+
var userConfig = command2 !== "mcp" && existsSync18(configPath) ? JSON.parse(readFileSync29(configPath, "utf8")) : {};
|
|
41681
41878
|
async function call(path, init) {
|
|
41682
41879
|
let appId = option("--app");
|
|
41683
|
-
if (!appId &&
|
|
41880
|
+
if (!appId && existsSync18(join23(process.cwd(), "backify.json"))) appId = projectApplication();
|
|
41684
41881
|
const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
|
|
41685
41882
|
const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
|
|
41686
41883
|
return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
|
|
@@ -41843,7 +42040,7 @@ async function main() {
|
|
|
41843
42040
|
const name2 = option("--name");
|
|
41844
42041
|
if (!name2) throw new Error("Specify --name <job>");
|
|
41845
42042
|
const payload = option("--payload");
|
|
41846
|
-
console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(
|
|
42043
|
+
console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync29(payload, "utf8")) : null }), null, 2));
|
|
41847
42044
|
} else if (["retry", "cancel"].includes(args[0])) {
|
|
41848
42045
|
const id = option("--id");
|
|
41849
42046
|
if (!id) throw new Error("Specify --id <run>");
|
|
@@ -41866,7 +42063,7 @@ async function main() {
|
|
|
41866
42063
|
const environmentId = option("--environment");
|
|
41867
42064
|
const packagePath = option("--package");
|
|
41868
42065
|
if (!environmentId || !packagePath || !args.includes("--confirm")) throw new Error("Use backify functions deploy --environment <environment-id> --package <functions.zip> --confirm. This replaces the complete function project.");
|
|
41869
|
-
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(
|
|
42066
|
+
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync29(packagePath)), { progress: (message) => console.log(message) });
|
|
41870
42067
|
console.log("Functions deployed.");
|
|
41871
42068
|
} else throw new Error("Use backify functions package or backify functions deploy");
|
|
41872
42069
|
break;
|
|
@@ -41885,6 +42082,11 @@ async function main() {
|
|
|
41885
42082
|
synchronize(process.cwd(), option("--agent"), option("--instruction-file"));
|
|
41886
42083
|
console.log("Backify instructions synchronized to version " + INSTRUCTION_VERSION);
|
|
41887
42084
|
break;
|
|
42085
|
+
case "upgrade": {
|
|
42086
|
+
if (args.some((value) => value !== "--json")) throw new Error("Use backify upgrade [--json]. Only stable compatible SDK releases are selected automatically.");
|
|
42087
|
+
console.log(JSON.stringify(upgradeSdk(), null, 2));
|
|
42088
|
+
break;
|
|
42089
|
+
}
|
|
41888
42090
|
case "doctor": {
|
|
41889
42091
|
if (args.includes("--environment")) {
|
|
41890
42092
|
const result2 = await diagnoseEnvironment(process.cwd(), { network: args.includes("--network"), capability: option("--capability") });
|
|
@@ -41902,7 +42104,7 @@ async function main() {
|
|
|
41902
42104
|
userConfig.token = args[0];
|
|
41903
42105
|
userConfig.organizationId = args[1] ?? userConfig.organizationId;
|
|
41904
42106
|
saveUserConfig(configPath, userConfig);
|
|
41905
|
-
} else await browserLogin(args.includes("--organization-access") ? void 0 : option("--app") ?? (
|
|
42107
|
+
} else await browserLogin(args.includes("--organization-access") ? void 0 : option("--app") ?? (existsSync18(join23(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
|
|
41906
42108
|
console.log("Logged in to Backify");
|
|
41907
42109
|
break;
|
|
41908
42110
|
case "logout":
|
|
@@ -41941,7 +42143,7 @@ async function main() {
|
|
|
41941
42143
|
userConfig.sessions[key] ??= session;
|
|
41942
42144
|
saveUserConfig(configPath, userConfig);
|
|
41943
42145
|
if (args.includes("--clone")) await cloneProject(client, appId);
|
|
41944
|
-
else if (
|
|
42146
|
+
else if (existsSync18(join23(process.cwd(), ".git"))) {
|
|
41945
42147
|
const update = await pullProject(client, appId);
|
|
41946
42148
|
console.log(JSON.stringify(update, null, 2));
|
|
41947
42149
|
if (update.status === "blocked") throw new Error(update.reason);
|
|
@@ -42004,7 +42206,7 @@ async function main() {
|
|
|
42004
42206
|
} else if (args[0] === "install") {
|
|
42005
42207
|
const version2 = option("--version"), sha256 = option("--sha256");
|
|
42006
42208
|
if (!version2 || !sha256) throw new Error("Use backify runtime install --version vX.Y.Z --sha256 <reviewed-digest> [--archive <local-zip>]");
|
|
42007
|
-
const bytes = option("--archive") ?
|
|
42209
|
+
const bytes = option("--archive") ? readFileSync29(option("--archive")) : await downloadLocalRuntime(version2);
|
|
42008
42210
|
console.log(JSON.stringify(installLocalRuntime(bytes, { version: version2, sha256 }), null, 2));
|
|
42009
42211
|
} else throw new Error("Use backify runtime install or backify runtime doctor");
|
|
42010
42212
|
break;
|
|
@@ -42019,7 +42221,7 @@ async function main() {
|
|
|
42019
42221
|
case "request": {
|
|
42020
42222
|
const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
|
|
42021
42223
|
if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");
|
|
42022
|
-
const configuration = configurationFile ? JSON.parse(
|
|
42224
|
+
const configuration = configurationFile ? JSON.parse(readFileSync29(configurationFile, "utf8")) : void 0;
|
|
42023
42225
|
console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
|
|
42024
42226
|
break;
|
|
42025
42227
|
}
|
|
@@ -42037,7 +42239,7 @@ async function main() {
|
|
|
42037
42239
|
else if (args[0] === "test") {
|
|
42038
42240
|
const name2 = option("--name"), payload = option("--payload");
|
|
42039
42241
|
if (!name2 || !payload) throw new Error("Specify --name and --payload <json-file>. Never include secrets in event payloads.");
|
|
42040
|
-
console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(
|
|
42242
|
+
console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync29(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
|
|
42041
42243
|
} else throw new Error("Use backify events environments|inspect|test");
|
|
42042
42244
|
break;
|
|
42043
42245
|
}
|
|
@@ -42048,7 +42250,7 @@ async function main() {
|
|
|
42048
42250
|
console.log(await call("/apps/" + applicationGuid(args[0]) + "/deployments/preview", { method: "POST", body: JSON.stringify({ sourceRevision: args[1] ?? "latest" }) }));
|
|
42049
42251
|
break;
|
|
42050
42252
|
default:
|
|
42051
|
-
console.log("backify tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | connect | init | doctor | sync | mcp [--project <directory>] [--app <application-id>] [--allow-preview] | login | logout | disconnect | status | dev | secrets local init|set|list --key-file <external-file> | test --json | inspect tables|rows|buckets|objects|preview|events --local [--json] | identity users|issue|clear --local [--json] | jobs | pull | report [--check] | prompt record --stdin --id <UUID> | ship [--production-deploy] | request | events environments|inspect|test | integrations list|catalog|search|describe|contract|types | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
|
|
42253
|
+
console.log("backify tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | connect | init | doctor | upgrade [--json] | sync | mcp [--project <directory>] [--app <application-id>] [--allow-preview] | login | logout | disconnect | status | dev | secrets local init|set|list --key-file <external-file> | test --json | inspect tables|rows|buckets|objects|preview|events --local [--json] | identity users|inbox|issue|clear --local [--json] | jobs | pull | report [--check] | prompt record --stdin --id <UUID> | ship [--production-deploy] | request | events environments|inspect|test | integrations list|catalog|search|describe|contract|types | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
|
|
42052
42254
|
}
|
|
42053
42255
|
}
|
|
42054
42256
|
main().catch((error2) => {
|