@backifydev/cli 0.3.19 → 0.3.21
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 +380 -352
- package/dist/index.js +1345 -845
- 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
|
/**
|
|
@@ -17360,7 +17360,7 @@ function datetime(args2) {
|
|
|
17360
17360
|
const timeRegex = `${time3}(?:${opts.join("|")})`;
|
|
17361
17361
|
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
|
|
17362
17362
|
}
|
|
17363
|
-
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid,
|
|
17363
|
+
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid6, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname2, e164, dateSource, date, string, bigint, integer3, number, boolean, _null, lowercase, uppercase;
|
|
17364
17364
|
var init_regexes = __esm({
|
|
17365
17365
|
"../../node_modules/zod/v4/core/regexes.js"() {
|
|
17366
17366
|
cuid = /^[cC][^\s-]{8,}$/;
|
|
@@ -17371,7 +17371,7 @@ var init_regexes = __esm({
|
|
|
17371
17371
|
nanoid = /^[a-zA-Z0-9_-]{21}$/;
|
|
17372
17372
|
duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
17373
17373
|
guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
|
|
17374
|
-
|
|
17374
|
+
uuid6 = (version2) => {
|
|
17375
17375
|
if (!version2)
|
|
17376
17376
|
return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;
|
|
17377
17377
|
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
|
|
@@ -18175,9 +18175,9 @@ var init_schemas = __esm({
|
|
|
18175
18175
|
const v = versionMap[def.version];
|
|
18176
18176
|
if (v === void 0)
|
|
18177
18177
|
throw new Error(`Invalid UUID version: "${def.version}"`);
|
|
18178
|
-
def.pattern ?? (def.pattern =
|
|
18178
|
+
def.pattern ?? (def.pattern = uuid6(v));
|
|
18179
18179
|
} else
|
|
18180
|
-
def.pattern ?? (def.pattern =
|
|
18180
|
+
def.pattern ?? (def.pattern = uuid6());
|
|
18181
18181
|
$ZodStringFormat.init(inst, def);
|
|
18182
18182
|
});
|
|
18183
18183
|
$ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
|
|
@@ -25548,8 +25548,8 @@ var require_keyword = __commonJS({
|
|
|
25548
25548
|
var _a2;
|
|
25549
25549
|
const { gen, keyword, schema, parentSchema, $data, it } = cxt;
|
|
25550
25550
|
checkAsyncKeyword(it, def);
|
|
25551
|
-
const
|
|
25552
|
-
const validateRef = useKeyword(gen, keyword,
|
|
25551
|
+
const validate2 = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
|
|
25552
|
+
const validateRef = useKeyword(gen, keyword, validate2);
|
|
25553
25553
|
const valid = gen.let("valid");
|
|
25554
25554
|
cxt.block$data(valid, validateKeyword);
|
|
25555
25555
|
cxt.ok((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid);
|
|
@@ -26622,28 +26622,28 @@ var require_compile = __commonJS({
|
|
|
26622
26622
|
if (this.opts.code.process)
|
|
26623
26623
|
sourceCode = this.opts.code.process(sourceCode, sch);
|
|
26624
26624
|
const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
|
|
26625
|
-
const
|
|
26626
|
-
this.scope.value(validateName2, { ref:
|
|
26627
|
-
|
|
26628
|
-
|
|
26629
|
-
|
|
26625
|
+
const validate2 = makeValidate(this, this.scope.get());
|
|
26626
|
+
this.scope.value(validateName2, { ref: validate2 });
|
|
26627
|
+
validate2.errors = null;
|
|
26628
|
+
validate2.schema = sch.schema;
|
|
26629
|
+
validate2.schemaEnv = sch;
|
|
26630
26630
|
if (sch.$async)
|
|
26631
|
-
|
|
26631
|
+
validate2.$async = true;
|
|
26632
26632
|
if (this.opts.code.source === true) {
|
|
26633
|
-
|
|
26633
|
+
validate2.source = { validateName: validateName2, validateCode, scopeValues: gen._values };
|
|
26634
26634
|
}
|
|
26635
26635
|
if (this.opts.unevaluated) {
|
|
26636
26636
|
const { props, items } = schemaCxt;
|
|
26637
|
-
|
|
26637
|
+
validate2.evaluated = {
|
|
26638
26638
|
props: props instanceof codegen_1.Name ? void 0 : props,
|
|
26639
26639
|
items: items instanceof codegen_1.Name ? void 0 : items,
|
|
26640
26640
|
dynamicProps: props instanceof codegen_1.Name,
|
|
26641
26641
|
dynamicItems: items instanceof codegen_1.Name
|
|
26642
26642
|
};
|
|
26643
|
-
if (
|
|
26644
|
-
|
|
26643
|
+
if (validate2.source)
|
|
26644
|
+
validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated);
|
|
26645
26645
|
}
|
|
26646
|
-
sch.validate =
|
|
26646
|
+
sch.validate = validate2;
|
|
26647
26647
|
return sch;
|
|
26648
26648
|
} catch (e) {
|
|
26649
26649
|
delete sch.validate;
|
|
@@ -30566,8 +30566,8 @@ var require_formats = __commonJS({
|
|
|
30566
30566
|
"use strict";
|
|
30567
30567
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
30568
30568
|
exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
|
|
30569
|
-
function fmtDef(
|
|
30570
|
-
return { validate, compare };
|
|
30569
|
+
function fmtDef(validate2, compare) {
|
|
30570
|
+
return { validate: validate2, compare };
|
|
30571
30571
|
}
|
|
30572
30572
|
exports.fullFormats = {
|
|
30573
30573
|
// date: http://tools.ietf.org/html/rfc3339#section-5.6
|
|
@@ -33104,13 +33104,13 @@ var init_streamableHttp = __esm({
|
|
|
33104
33104
|
this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
|
|
33105
33105
|
return;
|
|
33106
33106
|
}
|
|
33107
|
-
const
|
|
33107
|
+
const delay3 = this._getNextReconnectionDelay(attemptCount);
|
|
33108
33108
|
this._reconnectionTimeout = setTimeout(() => {
|
|
33109
33109
|
this._startOrAuthSse(options).catch((error2) => {
|
|
33110
33110
|
this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`));
|
|
33111
33111
|
this._scheduleReconnection(options, attemptCount + 1);
|
|
33112
33112
|
});
|
|
33113
|
-
},
|
|
33113
|
+
}, delay3);
|
|
33114
33114
|
}
|
|
33115
33115
|
_handleSseStream(stream, options, isReconnectable) {
|
|
33116
33116
|
if (!stream) {
|
|
@@ -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 randomUUID13 } 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 + "." + randomUUID13() + ".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: 16
|
|
35471
|
+
Versioned guide: https://agent.backify.dev/v16/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/v16 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/v16 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 = 16;
|
|
35531
35584
|
var SDK_PACKAGE = "@backifydev/sdk";
|
|
35532
35585
|
var DOCS_URL = "https://docs.backify.dev";
|
|
35533
35586
|
var MAIL_LIMITS = Object.freeze({
|
|
@@ -35587,6 +35640,7 @@ Before dependent setup operations, follow the environment checks and permission
|
|
|
35587
35640
|
- Server functions: \`defineFunction\`; background work and schedules: \`jobs\` and \`jobs.schedule\`.
|
|
35588
35641
|
- Events and event tracking, outbound HTTP, and AI: \`events\` (\`events.track\` records application events), \`http.fetch\`, and \`ai\`.
|
|
35589
35642
|
- Server-side secrets, configuration, and logs: \`secrets\`, \`config\`, and \`logs\`.
|
|
35643
|
+
- External system integrations: \`integrations\`. Discover organization-permitted definitions and pinned revisions before building a direct integration. Use \`backify integrations connect <provider>\` with the selected environment and requested operations to open browser review and wait for provider setup. The CLI never receives provider tokens. Coding tools may prepare adoption requests; an authorized application manager reviews operations and each account authorizes independently. Never infer readiness from a provider name, bypass organization access, or request credentials in chat. See https://docs.backify.dev/capabilities/integrations/ for discovery, preparation, connection and local-fixture workflows.
|
|
35590
35644
|
|
|
35591
35645
|
Verify API signatures against the installed SDK types and the relevant guide at ${DOCS_URL}/capabilities/. Never invent SDK methods. Use \`@backifydev/sdk/local\` for tests and local development; \`@backifydev/sdk/runtime\` is for runtime hosts, not application code.
|
|
35592
35646
|
|
|
@@ -35596,6 +35650,11 @@ Keep secrets server-side. Never commit or log credentials, expose secrets to bro
|
|
|
35596
35650
|
Scope cookies to the exact application hostname by omitting the \`Domain\` attribute. Never use a parent-domain cookie unless explicitly required.
|
|
35597
35651
|
Require explicit confirmation before destructive data operations or removing stateful resources. Removing a capability declaration does not authorize deleting its data.
|
|
35598
35652
|
|
|
35653
|
+
## Application defaults
|
|
35654
|
+
|
|
35655
|
+
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.
|
|
35656
|
+
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.
|
|
35657
|
+
|
|
35599
35658
|
## Implementation workflow
|
|
35600
35659
|
|
|
35601
35660
|
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 +35777,13 @@ async function probeEndpoint(url2, transport = fetch) {
|
|
|
35718
35777
|
}
|
|
35719
35778
|
function workspaceProbe(root) {
|
|
35720
35779
|
const directory2 = resolve2(root);
|
|
35721
|
-
const filename2 =
|
|
35780
|
+
const filename2 = join2(directory2, ".backify-environment-" + randomUUID());
|
|
35722
35781
|
const content = randomUUID();
|
|
35723
35782
|
let created = false;
|
|
35724
35783
|
try {
|
|
35725
|
-
|
|
35784
|
+
writeFileSync3(filename2, content, { flag: "wx" });
|
|
35726
35785
|
created = true;
|
|
35727
|
-
if (
|
|
35786
|
+
if (readFileSync2(filename2, "utf8") !== content) throw new Error("Workspace read/write failed.");
|
|
35728
35787
|
} finally {
|
|
35729
35788
|
if (created) unlinkSync(filename2);
|
|
35730
35789
|
}
|
|
@@ -35754,7 +35813,7 @@ function environmentProbes(root) {
|
|
|
35754
35813
|
const windowsNpm = name2 === "npm" && process.platform === "win32";
|
|
35755
35814
|
const executable = windowsNpm ? process.env.ComSpec ?? "cmd.exe" : name2;
|
|
35756
35815
|
const argumentsList = windowsNpm ? ["/d", "/s", "/c", "npm.cmd --version"] : ["--version"];
|
|
35757
|
-
const result =
|
|
35816
|
+
const result = spawnSync2(executable, argumentsList, { timeout: 5e3, stdio: "ignore", windowsHide: true });
|
|
35758
35817
|
if (result.error) throw result.error;
|
|
35759
35818
|
if (result.status !== 0) throw Object.assign(new Error("Prerequisite command failed."), { code: result.status === 127 || result.status === 9009 ? "ENOENT" : void 0 });
|
|
35760
35819
|
},
|
|
@@ -35800,12 +35859,22 @@ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes =
|
|
|
35800
35859
|
|
|
35801
35860
|
// src/integrations.ts
|
|
35802
35861
|
function integrationDiscoveryPath(command3, options) {
|
|
35803
|
-
const
|
|
35804
|
-
if (!
|
|
35862
|
+
const uuid7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
35863
|
+
if (!uuid7.test(options.applicationId)) throw new Error("An application UUID is required");
|
|
35805
35864
|
const base = "/apps/" + options.applicationId + "/integrations/connectors";
|
|
35806
35865
|
if (command3 === "list") return base;
|
|
35807
35866
|
if (command3 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
|
|
35808
|
-
if (
|
|
35867
|
+
if (command3 === "discover") return "/apps/" + options.applicationId + "/integrations/discover?" + new URLSearchParams({ query: options.query ?? "" });
|
|
35868
|
+
if (command3 === "prepare") return "/apps/" + options.applicationId + "/integrations/prepare";
|
|
35869
|
+
if (command3 === "contract" && options.revisionId) {
|
|
35870
|
+
if (!uuid7.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
|
|
35871
|
+
return "/apps/" + options.applicationId + "/integrations/definitions/" + options.revisionId;
|
|
35872
|
+
}
|
|
35873
|
+
if (command3 === "status") {
|
|
35874
|
+
if (!options.adoptionId || !uuid7.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
|
|
35875
|
+
return "/apps/" + options.applicationId + "/integrations/adoptions/" + options.adoptionId;
|
|
35876
|
+
}
|
|
35877
|
+
if (!options.connectionId || !uuid7.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
|
|
35809
35878
|
const connection = base + "/" + options.connectionId;
|
|
35810
35879
|
if (command3 === "contract" || command3 === "types") return connection + "/" + command3;
|
|
35811
35880
|
if (command3 === "describe") {
|
|
@@ -35817,7 +35886,256 @@ function integrationDiscoveryPath(command3, options) {
|
|
|
35817
35886
|
const query = new URLSearchParams({ query: options.query ?? "", offset: String(options.offset ?? 0), limit: "50" });
|
|
35818
35887
|
return connection + "/operations?" + query;
|
|
35819
35888
|
}
|
|
35820
|
-
throw new Error("Use backify integrations list|catalog|search|describe|contract|types");
|
|
35889
|
+
throw new Error("Use backify integrations discover|prepare|status|list|catalog|search|describe|contract|types");
|
|
35890
|
+
}
|
|
35891
|
+
function integrationPreparation(input) {
|
|
35892
|
+
for (const value of [input.definitionId, input.revisionId, input.environmentId]) if (!value || !/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(value)) throw new Error("Use --definition, --revision and --environment with discovered UUIDs");
|
|
35893
|
+
const mode = input.mode ?? "application";
|
|
35894
|
+
const operations = input.operations?.split(",").map((value) => value.trim()).filter(Boolean) ?? [];
|
|
35895
|
+
if (!["application", "user"].includes(mode) || !operations.length || operations.length > 500 || new Set(operations).size !== operations.length) throw new Error("Use --mode application|user and distinct --operations separated by commas");
|
|
35896
|
+
return { definitionId: input.definitionId, revisionId: input.revisionId, environmentId: input.environmentId, mode, operations };
|
|
35897
|
+
}
|
|
35898
|
+
|
|
35899
|
+
// src/integration-connect.ts
|
|
35900
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
35901
|
+
var integrationConnectHelp = `backify integrations connect <provider> [--app <application>] [--definition <UUID>] [--environment <UUID|name>] [--operations <comma-separated-IDs>] [--mode application|user]
|
|
35902
|
+
backify integrations connect --adoption <UUID> [--app <application>]
|
|
35903
|
+
Options: --no-browser --no-wait --timeout <seconds, 1-1800> --json
|
|
35904
|
+
Requests read operations by default. Browser review and consent remain required; provider credentials stay server-side.
|
|
35905
|
+
Pending setup returns exit code 2. Rerun with --adoption to resume.`;
|
|
35906
|
+
var uuid = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
|
35907
|
+
function validateStatus(status) {
|
|
35908
|
+
if (!uuid.test(status.id) || !["application", "user"].includes(status.mode) || !["review_required", "connection_required", "ready", "reconnect_required", "blocked"].includes(status.state) || status.installationId !== null && !uuid.test(status.installationId) || status.state === "ready" && !status.installationId) throw new Error("The server returned invalid integration readiness metadata.");
|
|
35909
|
+
}
|
|
35910
|
+
function portalOrigin(value) {
|
|
35911
|
+
const url2 = new URL(value);
|
|
35912
|
+
if (url2.protocol !== "https:" && !(url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname)) || url2.username || url2.password || url2.search || url2.hash || url2.pathname !== "/") throw new Error("Integration review requires a trusted HTTPS portal origin (or an explicit loopback development origin).");
|
|
35913
|
+
return url2.origin;
|
|
35914
|
+
}
|
|
35915
|
+
function reviewUrl(origin, app, status) {
|
|
35916
|
+
const url2 = new URL(status.reviewPath, origin);
|
|
35917
|
+
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/cli/integrations/" + app + "/" + status.id.toLowerCase() || [...url2.searchParams.keys()].join() !== "organization" || !uuid.test(url2.searchParams.get("organization")) || url2.username || url2.password || url2.hash) throw new Error("The server returned an invalid application integration review link.");
|
|
35918
|
+
return url2.href;
|
|
35919
|
+
}
|
|
35920
|
+
async function connectIntegration(call2, options) {
|
|
35921
|
+
const app = options.applicationId.toLowerCase();
|
|
35922
|
+
if (!uuid.test(app) || options.adoptionId && !uuid.test(options.adoptionId) || options.definitionId && !uuid.test(options.definitionId)) throw new Error("Use valid application, definition and adoption UUIDs.");
|
|
35923
|
+
if (options.mode && !["application", "user"].includes(options.mode)) throw new Error("Use --mode application|user.");
|
|
35924
|
+
const timeout = options.timeoutMs ?? 10 * 6e4;
|
|
35925
|
+
if (!Number.isFinite(timeout) || timeout < 1e3 || timeout > 30 * 6e4) throw new Error("Use --timeout between 1 and 1800 seconds.");
|
|
35926
|
+
const origin = portalOrigin(options.portalUrl), now = options.now ?? Date.now, deadline = now() + timeout;
|
|
35927
|
+
const prefix = "/apps/" + app + "/integrations";
|
|
35928
|
+
let status;
|
|
35929
|
+
if (options.adoptionId) status = await call2(prefix + "/adoptions/" + options.adoptionId + "?compact=true");
|
|
35930
|
+
else {
|
|
35931
|
+
const query = options.provider?.trim() ?? "";
|
|
35932
|
+
if (!query && !options.definitionId || query.length > 200 || /[\x00-\x1f\x7f]/.test(query)) throw new Error("Use backify integrations connect <provider> or --definition <UUID>.");
|
|
35933
|
+
let definitions = await call2(integrationDiscoveryPath("discover", { applicationId: app, query }));
|
|
35934
|
+
if (options.definitionId) definitions = definitions.filter((value) => value.definitionId.toLowerCase() === options.definitionId.toLowerCase());
|
|
35935
|
+
if (definitions.length === 0) return { state: "blocked", nextAction: "No permitted definition matches. Ask an organization administrator to enable or review it and allow this application." };
|
|
35936
|
+
if (definitions.length > 1) return { state: "selection_required", nextAction: "Choose --definition with one of the permitted definition IDs.", definitions: definitions.map(({ definitionId, name: name2, providerId }) => ({ definitionId, name: name2, providerId })) };
|
|
35937
|
+
const definition = definitions[0];
|
|
35938
|
+
const mode = options.mode ?? "application";
|
|
35939
|
+
if (!definition.connectionModes.includes(mode)) throw new Error("This definition does not support the requested connection mode.");
|
|
35940
|
+
const environments = (await call2(prefix + "/environments")).filter((value) => !value.expiresAt || Date.parse(value.expiresAt) > now());
|
|
35941
|
+
const selected = options.environment ? environments.filter((value) => value.id.toLowerCase() === options.environment.toLowerCase() || value.name.toLowerCase() === options.environment.toLowerCase()) : environments;
|
|
35942
|
+
if (selected.length !== 1) return { state: "selection_required", nextAction: "Choose --environment with an active environment UUID. No environment was selected automatically.", environments: environments.map(({ id, name: name2 }) => ({ id, name: name2 })) };
|
|
35943
|
+
const operations = options.operations ?? definition.operations.filter((operation) => operation.readOnly).map((operation) => operation.id).join(",");
|
|
35944
|
+
if (!operations) return { state: "selection_required", nextAction: "Specify the requested --operations. This definition has no read operations to use as the default.", operations: definition.operations };
|
|
35945
|
+
const preparation = integrationPreparation({ definitionId: definition.definitionId, revisionId: definition.revisionId, environmentId: selected[0].id, mode, operations });
|
|
35946
|
+
options.progress?.("Preparing reviewed integration access. Requested operations: " + operations);
|
|
35947
|
+
status = await call2(prefix + "/prepare", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(preparation) });
|
|
35948
|
+
}
|
|
35949
|
+
validateStatus(status);
|
|
35950
|
+
const link = reviewUrl(origin, app, status);
|
|
35951
|
+
async function result(reason) {
|
|
35952
|
+
const approved = status.state === "ready" || status.mode === "user" && !status.providerSetupRequired && status.state === "connection_required" && status.installationId;
|
|
35953
|
+
const binding = approved && status.installationId ? await call2(integrationDiscoveryPath("types", { applicationId: app, connectionId: status.installationId })) : void 0;
|
|
35954
|
+
return {
|
|
35955
|
+
state: status.state,
|
|
35956
|
+
adoptionId: status.id,
|
|
35957
|
+
connectionId: status.installationId,
|
|
35958
|
+
mode: status.mode,
|
|
35959
|
+
reviewUrl: link,
|
|
35960
|
+
nextAction: status.nextAction,
|
|
35961
|
+
...reason ? { reason } : {},
|
|
35962
|
+
...binding ? { bindings: binding.source } : {},
|
|
35963
|
+
...approved && status.mode === "user" ? { userConnectionFlowRequired: true } : {}
|
|
35964
|
+
};
|
|
35965
|
+
}
|
|
35966
|
+
if (status.state === "ready" || status.state === "blocked") return result();
|
|
35967
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
35968
|
+
options.progress?.("Open your browser to review access and complete provider setup:\n" + link);
|
|
35969
|
+
if (!options.noBrowser) {
|
|
35970
|
+
try {
|
|
35971
|
+
options.openBrowser(link);
|
|
35972
|
+
} catch {
|
|
35973
|
+
options.progress?.("Open the review URL above manually; automatic browser launch failed.");
|
|
35974
|
+
}
|
|
35975
|
+
}
|
|
35976
|
+
if (status.mode === "user" && !status.providerSetupRequired && status.installationId && status.state === "connection_required") return result();
|
|
35977
|
+
if (options.noWait) return result("waiting_in_browser");
|
|
35978
|
+
let previous = "";
|
|
35979
|
+
while (true) {
|
|
35980
|
+
if (status.state !== previous) {
|
|
35981
|
+
options.progress?.("Integration setup: " + status.state + ". " + status.nextAction);
|
|
35982
|
+
previous = status.state;
|
|
35983
|
+
}
|
|
35984
|
+
if (status.state === "ready" || status.state === "blocked" || status.mode === "user" && !status.providerSetupRequired && status.installationId && status.state === "connection_required") return result();
|
|
35985
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
35986
|
+
if (now() >= deadline) return result("timed_out");
|
|
35987
|
+
try {
|
|
35988
|
+
await (options.sleep ?? ((ms) => delay(ms, void 0, { signal: options.signal })))(Math.min(2e3, deadline - now()));
|
|
35989
|
+
} catch (error2) {
|
|
35990
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
35991
|
+
throw error2;
|
|
35992
|
+
}
|
|
35993
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
35994
|
+
status = await call2(prefix + "/adoptions/" + status.id + "?compact=true");
|
|
35995
|
+
validateStatus(status);
|
|
35996
|
+
if (reviewUrl(origin, app, status) !== link) throw new Error("The integration review identity changed while waiting.");
|
|
35997
|
+
}
|
|
35998
|
+
}
|
|
35999
|
+
function integrationConnectArguments(args2) {
|
|
36000
|
+
const values = {}, flags = /* @__PURE__ */ new Set();
|
|
36001
|
+
let provider;
|
|
36002
|
+
const booleans = ["--no-browser", "--no-wait", "--json"];
|
|
36003
|
+
const valued = ["--app", "--definition", "--environment", "--operations", "--mode", "--adoption", "--timeout"];
|
|
36004
|
+
for (let i = 0; i < args2.length; i++) {
|
|
36005
|
+
const value = args2[i];
|
|
36006
|
+
if (booleans.includes(value)) {
|
|
36007
|
+
if (flags.has(value)) throw new Error("Duplicate connect option: " + value);
|
|
36008
|
+
flags.add(value);
|
|
36009
|
+
} else if (valued.includes(value)) {
|
|
36010
|
+
if (value in values || !args2[i + 1] || args2[i + 1].startsWith("--")) throw new Error("Specify one value for " + value);
|
|
36011
|
+
values[value] = args2[++i];
|
|
36012
|
+
} else if (value.startsWith("--") || provider) throw new Error("Unknown integration connect argument: " + value);
|
|
36013
|
+
else provider = value;
|
|
36014
|
+
}
|
|
36015
|
+
if (values["--adoption"] && (provider || ["--definition", "--environment", "--operations", "--mode"].some((key) => values[key]))) throw new Error("Resume with --adoption and --app only, plus browser/wait options.");
|
|
36016
|
+
return {
|
|
36017
|
+
provider,
|
|
36018
|
+
definitionId: values["--definition"],
|
|
36019
|
+
environment: values["--environment"],
|
|
36020
|
+
operations: values["--operations"],
|
|
36021
|
+
mode: values["--mode"],
|
|
36022
|
+
adoptionId: values["--adoption"],
|
|
36023
|
+
noBrowser: flags.has("--no-browser"),
|
|
36024
|
+
noWait: flags.has("--no-wait"),
|
|
36025
|
+
timeoutMs: values["--timeout"] === void 0 ? void 0 : Number(values["--timeout"]) * 1e3
|
|
36026
|
+
};
|
|
36027
|
+
}
|
|
36028
|
+
|
|
36029
|
+
// src/domain-connect.ts
|
|
36030
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
36031
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
36032
|
+
import { domainToASCII } from "node:url";
|
|
36033
|
+
var domainConnectHelp = `backify domains connect [hostname] [--app <application>] [--environment preview|production]
|
|
36034
|
+
backify domains connect --request <UUID> [--app <application>]
|
|
36035
|
+
Options: --hostname <hostname> --no-browser --no-wait --timeout <seconds, 1-3600> --json
|
|
36036
|
+
Opens a setup page where an authorized user signs in and confirms the hostname and environment, then returns as soon
|
|
36037
|
+
as the domain is confirmed. It does not wait for DNS: Backify verifies the DNS records, issues managed HTTPS and starts
|
|
36038
|
+
routing automatically once the user adds them. Exit code 0 means confirmed; 2 means not yet confirmed or blocked.
|
|
36039
|
+
Re-run with --request to read the current status without reopening the browser.`;
|
|
36040
|
+
var uuid2 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
|
36041
|
+
var confirmedStates = ["dns_required", "certificate_pending", "ready"];
|
|
36042
|
+
function customHostname(input) {
|
|
36043
|
+
const hostname3 = domainToASCII(input.trim().replace(/\.$/, "")).toLowerCase(), labels = hostname3.split(".");
|
|
36044
|
+
if (/[\s:/\\@?#%*]/.test(input.trim()) || hostname3.length > 253 || labels.length < 2 || labels.some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) || !/^[a-z][a-z0-9-]*$/.test(labels.at(-1)) || ["backify.dev", "backify.site"].some((suffix) => hostname3 === suffix || hostname3.endsWith("." + suffix))) throw new Error("Use a custom DNS hostname without a URL, path, port or wildcard.");
|
|
36045
|
+
return hostname3;
|
|
36046
|
+
}
|
|
36047
|
+
function portalOrigin2(input) {
|
|
36048
|
+
const url2 = new URL(input);
|
|
36049
|
+
if (url2.protocol !== "https:" && !(url2.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url2.hostname)) || url2.username || url2.password || url2.search || url2.hash || url2.pathname !== "/") throw new Error("Use a trusted HTTPS portal origin, or an explicit loopback development origin.");
|
|
36050
|
+
return url2.origin;
|
|
36051
|
+
}
|
|
36052
|
+
function validate(status, app) {
|
|
36053
|
+
if (!uuid2.test(status.id) || status.applicationId !== app || !["review_required", "dns_required", "certificate_pending", "ready", "blocked"].includes(status.state) || status.domainId !== null && !uuid2.test(status.domainId)) throw new Error("The server returned invalid domain setup metadata.");
|
|
36054
|
+
if (["dns_required", "certificate_pending"].includes(status.state) && (!status.domainId || !status.hostname || !["preview", "production"].includes(status.environment ?? ""))) throw new Error("The server returned invalid domain setup metadata.");
|
|
36055
|
+
if (status.state === "ready" && (!status.domainId || !status.hostname || customHostname(status.hostname) !== status.hostname || status.verificationStatus !== "verified" || status.certificateStatus !== "managed" || status.bindingStatus !== "ready" || !["preview", "production"].includes(status.environment ?? "") || status.url !== "https://" + status.hostname)) throw new Error("The server has not established verified DNS, managed HTTPS and routing for this domain.");
|
|
36056
|
+
}
|
|
36057
|
+
function reviewUrl2(origin, app, status) {
|
|
36058
|
+
const url2 = new URL(status.reviewPath, origin);
|
|
36059
|
+
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/cli/domains/" + app + "/" + status.id.toLowerCase() || [...url2.searchParams.keys()].join() !== "organization" || !uuid2.test(url2.searchParams.get("organization")) || url2.username || url2.password || url2.hash) throw new Error("The server returned an invalid application domain setup link.");
|
|
36060
|
+
return url2.href;
|
|
36061
|
+
}
|
|
36062
|
+
async function connectDomain(call2, options) {
|
|
36063
|
+
const app = options.applicationId.toLowerCase(), timeout = options.timeoutMs ?? 6e5;
|
|
36064
|
+
if (!uuid2.test(app) || options.requestId && !uuid2.test(options.requestId)) throw new Error("Use valid application and domain setup request IDs.");
|
|
36065
|
+
if (options.environment && !["preview", "production"].includes(options.environment)) throw new Error("Use --environment preview|production, or choose in the browser.");
|
|
36066
|
+
if (!Number.isFinite(timeout) || timeout < 1e3 || timeout > 36e5) throw new Error("Use --timeout between 1 and 3600 seconds.");
|
|
36067
|
+
const hostname3 = options.hostname === void 0 ? void 0 : customHostname(options.hostname), origin = portalOrigin2(options.portalUrl), now = options.now ?? Date.now, deadline = now() + timeout;
|
|
36068
|
+
const base = "/apps/" + app + "/domains/connections";
|
|
36069
|
+
let status = options.requestId ? await call2(base + "/" + options.requestId) : await call2(base, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ hostname: hostname3 ?? null, environment: options.environment ?? null, requestKey: randomUUID2() }) });
|
|
36070
|
+
validate(status, app);
|
|
36071
|
+
const link = reviewUrl2(origin, app, status);
|
|
36072
|
+
const result = (reason) => ({
|
|
36073
|
+
state: status.state,
|
|
36074
|
+
confirmed: confirmedStates.includes(status.state),
|
|
36075
|
+
requestId: status.id,
|
|
36076
|
+
applicationId: app,
|
|
36077
|
+
domainId: status.domainId,
|
|
36078
|
+
hostname: status.hostname,
|
|
36079
|
+
environment: status.environment,
|
|
36080
|
+
verificationStatus: status.verificationStatus,
|
|
36081
|
+
certificateStatus: status.certificateStatus,
|
|
36082
|
+
bindingStatus: status.bindingStatus,
|
|
36083
|
+
setupUrl: link,
|
|
36084
|
+
nextAction: status.nextAction,
|
|
36085
|
+
// The address the domain will serve once DNS is verified; `url` is set only when it already does.
|
|
36086
|
+
expectedUrl: status.hostname ? "https://" + status.hostname : null,
|
|
36087
|
+
url: status.state === "ready" ? status.url : null,
|
|
36088
|
+
...reason ? { reason } : {}
|
|
36089
|
+
});
|
|
36090
|
+
if (status.state !== "review_required") return result();
|
|
36091
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
36092
|
+
options.progress?.("Open this page to sign in and confirm the custom domain:\n" + link);
|
|
36093
|
+
if (!options.noBrowser) {
|
|
36094
|
+
try {
|
|
36095
|
+
options.openBrowser(link);
|
|
36096
|
+
} catch {
|
|
36097
|
+
options.progress?.("Automatic browser launch failed. Open the setup URL manually.");
|
|
36098
|
+
}
|
|
36099
|
+
}
|
|
36100
|
+
if (options.noWait) return result("waiting_in_browser");
|
|
36101
|
+
options.progress?.("Waiting for confirmation in the browser\u2026");
|
|
36102
|
+
while (true) {
|
|
36103
|
+
if (status.state !== "review_required") {
|
|
36104
|
+
options.progress?.(status.nextAction);
|
|
36105
|
+
return result();
|
|
36106
|
+
}
|
|
36107
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
36108
|
+
if (now() >= deadline) return result("timed_out");
|
|
36109
|
+
try {
|
|
36110
|
+
await (options.sleep ?? ((ms) => delay2(ms, void 0, { signal: options.signal })))(Math.min(3e3, deadline - now()));
|
|
36111
|
+
} catch (error2) {
|
|
36112
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
36113
|
+
throw error2;
|
|
36114
|
+
}
|
|
36115
|
+
if (options.signal?.aborted) return result("cancelled");
|
|
36116
|
+
status = await call2(base + "/" + status.id);
|
|
36117
|
+
validate(status, app);
|
|
36118
|
+
if (reviewUrl2(origin, app, status) !== link) throw new Error("The domain setup request changed while waiting.");
|
|
36119
|
+
}
|
|
36120
|
+
}
|
|
36121
|
+
function domainConnectArguments(args2) {
|
|
36122
|
+
const values = {}, flags = /* @__PURE__ */ new Set();
|
|
36123
|
+
let hostname3;
|
|
36124
|
+
for (let i = 0; i < args2.length; i++) {
|
|
36125
|
+
const value = args2[i];
|
|
36126
|
+
if (["--json", "--no-browser", "--no-wait"].includes(value)) {
|
|
36127
|
+
if (flags.has(value)) throw new Error("Duplicate domain option: " + value);
|
|
36128
|
+
flags.add(value);
|
|
36129
|
+
} else if (["--app", "--hostname", "--environment", "--request", "--timeout"].includes(value)) {
|
|
36130
|
+
if (value in values || !args2[i + 1] || args2[i + 1].startsWith("--")) throw new Error("Specify one value for " + value);
|
|
36131
|
+
values[value] = args2[++i];
|
|
36132
|
+
} else if (value.startsWith("--") || hostname3) throw new Error("Unknown domains connect argument: " + value);
|
|
36133
|
+
else hostname3 = value;
|
|
36134
|
+
}
|
|
36135
|
+
if (hostname3 && values["--hostname"]) throw new Error("Specify the hostname once.");
|
|
36136
|
+
hostname3 ??= values["--hostname"];
|
|
36137
|
+
if (values["--request"] && (hostname3 || values["--environment"])) throw new Error("Resume with --request; do not change its hostname or environment.");
|
|
36138
|
+
return { hostname: hostname3, environment: values["--environment"], requestId: values["--request"], noBrowser: flags.has("--no-browser"), noWait: flags.has("--no-wait"), timeoutMs: values["--timeout"] === void 0 ? void 0 : Number(values["--timeout"]) * 1e3 };
|
|
35821
36139
|
}
|
|
35822
36140
|
|
|
35823
36141
|
// src/pairing.ts
|
|
@@ -35852,7 +36170,7 @@ import { hostname, platform, release, arch } from "node:os";
|
|
|
35852
36170
|
// package.json
|
|
35853
36171
|
var package_default = {
|
|
35854
36172
|
name: "@backifydev/cli",
|
|
35855
|
-
version: "0.3.
|
|
36173
|
+
version: "0.3.21",
|
|
35856
36174
|
description: "Command-line setup and diagnostics for Backify applications",
|
|
35857
36175
|
type: "module",
|
|
35858
36176
|
bin: {
|
|
@@ -35887,7 +36205,7 @@ var package_default = {
|
|
|
35887
36205
|
dependencies: {
|
|
35888
36206
|
"@modelcontextprotocol/sdk": "^1.31.0",
|
|
35889
36207
|
"@azure/functions": "^4.7.2",
|
|
35890
|
-
"@backifydev/sdk": "^0.1.
|
|
36208
|
+
"@backifydev/sdk": "^0.1.13",
|
|
35891
36209
|
esbuild: "^0.25.10",
|
|
35892
36210
|
fflate: "^0.8.2",
|
|
35893
36211
|
typescript: "^5.9.2"
|
|
@@ -35917,60 +36235,60 @@ import { randomBytes } from "node:crypto";
|
|
|
35917
36235
|
import { createServer as createServer2 } from "node:http";
|
|
35918
36236
|
|
|
35919
36237
|
// src/development.ts
|
|
35920
|
-
import { existsSync as
|
|
35921
|
-
import { dirname as dirname4, join as
|
|
35922
|
-
import { spawnSync as
|
|
35923
|
-
import { randomUUID as
|
|
36238
|
+
import { existsSync as existsSync7, readFileSync as readFileSync7, readdirSync as readdirSync2, writeFileSync as writeFileSync6, renameSync, rmSync, mkdtempSync, lstatSync as lstatSync3, cpSync } from "node:fs";
|
|
36239
|
+
import { dirname as dirname4, join as join7, resolve as resolve4 } from "node:path";
|
|
36240
|
+
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
36241
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
35924
36242
|
|
|
35925
36243
|
// src/setup.ts
|
|
35926
|
-
import { existsSync as
|
|
35927
|
-
import { basename, dirname as dirname3, join as
|
|
35928
|
-
import { spawnSync as
|
|
36244
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5, mkdirSync as mkdirSync2, readdirSync, lstatSync as lstatSync2 } from "node:fs";
|
|
36245
|
+
import { basename, dirname as dirname3, join as join5, resolve as resolve3, isAbsolute } from "node:path";
|
|
36246
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
35929
36247
|
|
|
35930
36248
|
// src/delivery.ts
|
|
35931
|
-
import { existsSync as
|
|
35932
|
-
import { dirname as dirname2, join as
|
|
36249
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";
|
|
36250
|
+
import { dirname as dirname2, join as join3, relative as relativePath } from "node:path";
|
|
35933
36251
|
import { createHash } from "node:crypto";
|
|
35934
36252
|
var previousGeneratedWorkflowHashes = /* @__PURE__ */ new Set(["33e962274e8493f7cbac2afbac05a4e96afeec49ee08cf2bf82f8add9081b28b", "578dfb4c771c623fd04454e8a604efd701d5563d11e11191324862369bd24718", "6eb280ae7bdb14c390011686c41400f59c023304c3015d8440b7e80aaafa1c11", "545e03a1d5b996ade179e0e60ed5c86accdadc1982c1c25efd094e34f72f47ee"]);
|
|
35935
36253
|
function validateDeliveryInstructions(root) {
|
|
35936
36254
|
for (const filename2 of ["BACKIFY.md", "BACKIFY-WORKFLOW.md"]) {
|
|
35937
|
-
const path =
|
|
35938
|
-
if (
|
|
35939
|
-
const existing =
|
|
36255
|
+
const path = join3(root, filename2);
|
|
36256
|
+
if (existsSync3(path)) {
|
|
36257
|
+
const existing = readFileSync3(path, "utf8").replace(/\r\n/g, "\n");
|
|
35940
36258
|
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
36259
|
}
|
|
35942
36260
|
}
|
|
35943
36261
|
}
|
|
35944
36262
|
function installDeliveryInstructions(root, instructionFiles2) {
|
|
35945
36263
|
validateDeliveryInstructions(root);
|
|
35946
|
-
|
|
36264
|
+
writeFileSync4(join3(root, "BACKIFY.md"), deliveryInstructions);
|
|
35947
36265
|
for (const relative11 of instructionFiles2) {
|
|
35948
|
-
const instructionPath =
|
|
35949
|
-
const link = relativePath(dirname2(instructionPath),
|
|
35950
|
-
const legacyLink = relativePath(dirname2(instructionPath),
|
|
36266
|
+
const instructionPath = join3(root, relative11), content = readFileSync3(instructionPath, "utf8");
|
|
36267
|
+
const link = relativePath(dirname2(instructionPath), join3(root, "BACKIFY.md")).replaceAll("\\", "/");
|
|
36268
|
+
const legacyLink = relativePath(dirname2(instructionPath), join3(root, "BACKIFY-WORKFLOW.md")).replaceAll("\\", "/");
|
|
35951
36269
|
const legacy = "For application delivery and recording each user request, follow [BACKIFY-WORKFLOW.md](" + legacyLink + ").";
|
|
35952
36270
|
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"))
|
|
36271
|
+
if (content.includes(legacy)) writeFileSync4(instructionPath, content.replace(legacy, guidance));
|
|
36272
|
+
else if (!content.includes("## Backify delivery")) writeFileSync4(instructionPath, content.trimEnd() + "\n\n## Backify delivery\n\n" + guidance + "\n");
|
|
35955
36273
|
}
|
|
35956
36274
|
}
|
|
35957
36275
|
|
|
35958
36276
|
// src/application-support.ts
|
|
35959
|
-
import { existsSync as
|
|
35960
|
-
import { join as
|
|
36277
|
+
import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
|
|
36278
|
+
import { join as join4 } from "node:path";
|
|
35961
36279
|
function applicationSupport(root) {
|
|
35962
|
-
const manifestPath =
|
|
35963
|
-
const manifest =
|
|
36280
|
+
const manifestPath = join4(root, "package.json");
|
|
36281
|
+
const manifest = existsSync4(manifestPath) ? JSON.parse(readFileSync4(manifestPath, "utf8")) : {};
|
|
35964
36282
|
const dependencies = { ...manifest.devDependencies, ...manifest.dependencies };
|
|
35965
36283
|
const framework = ["next", "astro", "@sveltejs/kit", "nuxt", "express", "vite", "react"].find((name2) => dependencies[name2]) ?? "unknown";
|
|
35966
|
-
if (
|
|
36284
|
+
if (existsSync4(join4(root, "Dockerfile"))) {
|
|
35967
36285
|
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
36286
|
}
|
|
35969
36287
|
if (framework === "vite" && dependencies.react) {
|
|
35970
36288
|
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
36289
|
}
|
|
35972
36290
|
return {
|
|
35973
|
-
tier:
|
|
36291
|
+
tier: existsSync4(manifestPath) ? "compatible" : "unassessed",
|
|
35974
36292
|
framework,
|
|
35975
36293
|
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
36294
|
};
|
|
@@ -35978,9 +36296,9 @@ function applicationSupport(root) {
|
|
|
35978
36296
|
|
|
35979
36297
|
// src/setup.ts
|
|
35980
36298
|
var instructionFiles = ["AGENTS.md"];
|
|
35981
|
-
var agentInstructionFiles = { codex: "AGENTS.md", claude: "CLAUDE.md", copilot:
|
|
36299
|
+
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
36300
|
function instructionSelection(root, agent, instructionFile) {
|
|
35983
|
-
const configPath2 =
|
|
36301
|
+
const configPath2 = join5(root, "backify.json"), configured = existsSync5(configPath2) ? JSON.parse(readFileSync5(configPath2, "utf8")) : {};
|
|
35984
36302
|
const custom2 = instructionFile ?? (agent === void 0 ? configured.instructionFile : void 0);
|
|
35985
36303
|
const selected = instructionFile !== void 0 ? "custom" : agent ?? configured.agent ?? "codex";
|
|
35986
36304
|
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 +36307,9 @@ function instructionSelection(root, agent, instructionFile) {
|
|
|
35989
36307
|
const normalized = filename2.replaceAll("\\", "/"), parts = normalized.split("/");
|
|
35990
36308
|
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
36309
|
for (let index = 1; index <= parts.length; index++) {
|
|
35992
|
-
const entry =
|
|
36310
|
+
const entry = join5(root, ...parts.slice(0, index));
|
|
35993
36311
|
try {
|
|
35994
|
-
const metadata =
|
|
36312
|
+
const metadata = lstatSync2(entry);
|
|
35995
36313
|
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
36314
|
} catch (reason) {
|
|
35997
36315
|
if (reason.code !== "ENOENT") throw reason;
|
|
@@ -36004,26 +36322,26 @@ function selectedInstructionFiles(root = process.cwd(), agent, instructionFile)
|
|
|
36004
36322
|
}
|
|
36005
36323
|
function isToolWorkspaceEntry(entry, root = process.cwd()) {
|
|
36006
36324
|
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(
|
|
36325
|
+
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
36326
|
}
|
|
36009
36327
|
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 (
|
|
36328
|
+
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
36329
|
return "npm";
|
|
36012
36330
|
}
|
|
36013
36331
|
function updateInstructions(root = process.cwd(), agent, instructionFile) {
|
|
36014
36332
|
const updates = selectedInstructionFiles(root, agent, instructionFile).map((relative11) => {
|
|
36015
|
-
const path =
|
|
36016
|
-
return { path, content: updateManagedInstructions(
|
|
36333
|
+
const path = join5(root, relative11);
|
|
36334
|
+
return { path, content: updateManagedInstructions(existsSync5(path) ? readFileSync5(path, "utf8") : "") };
|
|
36017
36335
|
});
|
|
36018
36336
|
for (const { path, content } of updates) {
|
|
36019
36337
|
mkdirSync2(dirname3(path), { recursive: true });
|
|
36020
|
-
|
|
36338
|
+
writeFileSync5(path, content);
|
|
36021
36339
|
}
|
|
36022
36340
|
}
|
|
36023
36341
|
function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
36024
|
-
const path =
|
|
36025
|
-
if (!
|
|
36026
|
-
const value = JSON.parse(
|
|
36342
|
+
const path = join5(root, "backify.json");
|
|
36343
|
+
if (!existsSync5(path)) throw new Error("backify.json is missing; run backify init --app app_xxxxx");
|
|
36344
|
+
const value = JSON.parse(readFileSync5(path, "utf8")), issues = validateConfig(value);
|
|
36027
36345
|
if (issues.length) throw new Error(issues.join("; "));
|
|
36028
36346
|
if (value.instructionVersion > INSTRUCTION_VERSION) throw new Error("This app uses newer instructions. Install a matching or newer CLI before syncing.");
|
|
36029
36347
|
const selected = instructionSelection(root, agent, instructionFile);
|
|
@@ -36033,11 +36351,11 @@ function synchronize(root = process.cwd(), agent, instructionFile) {
|
|
|
36033
36351
|
value.agent = selected.agent;
|
|
36034
36352
|
value.instructionFile = selected.instructionFile;
|
|
36035
36353
|
value.instructionVersion = INSTRUCTION_VERSION;
|
|
36036
|
-
|
|
36354
|
+
writeFileSync5(path, JSON.stringify(value, null, 2) + "\n");
|
|
36037
36355
|
}
|
|
36038
36356
|
function sdkInstalled(root = process.cwd()) {
|
|
36039
36357
|
try {
|
|
36040
|
-
const pkg = JSON.parse(
|
|
36358
|
+
const pkg = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
|
|
36041
36359
|
return Boolean(pkg.dependencies?.[SDK_PACKAGE] || pkg.devDependencies?.[SDK_PACKAGE]);
|
|
36042
36360
|
} catch {
|
|
36043
36361
|
return false;
|
|
@@ -36045,29 +36363,29 @@ function sdkInstalled(root = process.cwd()) {
|
|
|
36045
36363
|
}
|
|
36046
36364
|
function installSdk(root = process.cwd()) {
|
|
36047
36365
|
if (sdkInstalled(root)) return;
|
|
36048
|
-
const manager = detectPackageManager(root), args2 = manager === "npm" ? ["install", SDK_PACKAGE] : ["add", SDK_PACKAGE], result =
|
|
36366
|
+
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
36367
|
if (result.status !== 0) throw new Error(`Could not install ${SDK_PACKAGE} with ${manager}`);
|
|
36050
36368
|
}
|
|
36051
36369
|
function ensurePackageManifest(root) {
|
|
36052
|
-
const path =
|
|
36053
|
-
if (
|
|
36370
|
+
const path = join5(root, "package.json");
|
|
36371
|
+
if (existsSync5(path)) return;
|
|
36054
36372
|
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
36373
|
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
36374
|
const name2 = basename(resolve3(root)).toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "backify-app";
|
|
36057
|
-
|
|
36375
|
+
writeFileSync5(path, JSON.stringify({ name: name2, version: "0.0.0", private: true, type: "module" }, null, 2) + "\n", { flag: "wx" });
|
|
36058
36376
|
}
|
|
36059
36377
|
function initialize(appId, root = process.cwd(), install = true, agent, instructionFile) {
|
|
36060
36378
|
if (!/^app_[A-Za-z0-9_-]+$/.test(appId)) throw new Error("Provide an application ID using --app app_xxxxx");
|
|
36061
36379
|
const selected = instructionSelection(root, agent, instructionFile), files = selected.files;
|
|
36062
36380
|
validateDeliveryInstructions(root);
|
|
36063
|
-
for (const relative11 of files) if (
|
|
36064
|
-
const customContainer = !
|
|
36381
|
+
for (const relative11 of files) if (existsSync5(join5(root, relative11))) updateManagedInstructions(readFileSync5(join5(root, relative11), "utf8"));
|
|
36382
|
+
const customContainer = !existsSync5(join5(root, "package.json")) && existsSync5(join5(root, "Dockerfile"));
|
|
36065
36383
|
if (!customContainer) {
|
|
36066
36384
|
ensurePackageManifest(root);
|
|
36067
36385
|
if (install) installSdk(root);
|
|
36068
36386
|
}
|
|
36069
|
-
const configPath2 =
|
|
36070
|
-
|
|
36387
|
+
const configPath2 = join5(root, "backify.json"), existing = existsSync5(configPath2) ? JSON.parse(readFileSync5(configPath2, "utf8")) : {};
|
|
36388
|
+
writeFileSync5(configPath2, JSON.stringify({ ...existing, ...createConfig(appId), agent: selected.agent, instructionFile: selected.instructionFile }, null, 2) + "\n");
|
|
36071
36389
|
updateInstructions(root, selected.agent, selected.instructionFile);
|
|
36072
36390
|
installDeliveryInstructions(root, files);
|
|
36073
36391
|
}
|
|
@@ -36081,17 +36399,17 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
36081
36399
|
issues.push("package.json is invalid JSON");
|
|
36082
36400
|
}
|
|
36083
36401
|
if (!sdkInstalled(root)) {
|
|
36084
|
-
if (!
|
|
36402
|
+
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
36403
|
else issues.push(`${SDK_PACKAGE} is not installed`);
|
|
36086
36404
|
}
|
|
36087
36405
|
let config2;
|
|
36088
36406
|
try {
|
|
36089
|
-
config2 = JSON.parse(
|
|
36407
|
+
config2 = JSON.parse(readFileSync5(join5(root, "backify.json"), "utf8"));
|
|
36090
36408
|
issues.push(...validateConfig(config2));
|
|
36091
36409
|
} catch {
|
|
36092
36410
|
issues.push("backify.json is missing or invalid JSON");
|
|
36093
36411
|
}
|
|
36094
|
-
if (config2 && config2.instructionVersion
|
|
36412
|
+
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
36413
|
let files = instructionFiles;
|
|
36096
36414
|
try {
|
|
36097
36415
|
files = selectedInstructionFiles(root, agent, instructionFile);
|
|
@@ -36099,16 +36417,24 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
36099
36417
|
issues.push(reason instanceof Error ? reason.message : String(reason));
|
|
36100
36418
|
}
|
|
36101
36419
|
for (const relative11 of files) {
|
|
36102
|
-
const path =
|
|
36103
|
-
if (!
|
|
36420
|
+
const path = join5(root, relative11);
|
|
36421
|
+
if (!existsSync5(path)) {
|
|
36104
36422
|
issues.push(`${relative11} is missing`);
|
|
36105
36423
|
continue;
|
|
36106
36424
|
}
|
|
36107
|
-
|
|
36425
|
+
const content = readFileSync5(path, "utf8");
|
|
36426
|
+
const managed = managedInstructionIssues(content);
|
|
36427
|
+
if (config2 && config2.instructionVersion < INSTRUCTION_VERSION) {
|
|
36428
|
+
const declared = content.match(/Instruction version:\s*(\d+)/)?.[1];
|
|
36429
|
+
const structural = managed.filter((issue2) => !issue2.includes("stale or inconsistent"));
|
|
36430
|
+
issues.push(...structural.map((issue2) => relative11 + " " + issue2));
|
|
36431
|
+
if (Number(declared) !== config2.instructionVersion || !content.includes("https://agent.backify.dev/v" + config2.instructionVersion)) issues.push(relative11 + " does not match the repository instruction version");
|
|
36432
|
+
else warnings.push(relative11 + " uses supported older instructions; follow the versioned guide. Run backify sync only when intentionally upgrading instructions.");
|
|
36433
|
+
} else issues.push(...managed.map((issue2) => relative11 + " " + issue2));
|
|
36108
36434
|
}
|
|
36109
36435
|
let version2 = "unknown";
|
|
36110
36436
|
try {
|
|
36111
|
-
const pkg = JSON.parse(
|
|
36437
|
+
const pkg = JSON.parse(readFileSync5(join5(root, "package.json"), "utf8"));
|
|
36112
36438
|
version2 = pkg.dependencies?.[SDK_PACKAGE] ?? pkg.devDependencies?.[SDK_PACKAGE] ?? "missing";
|
|
36113
36439
|
} catch {
|
|
36114
36440
|
}
|
|
@@ -36116,14 +36442,14 @@ function doctor(root = process.cwd(), agent, instructionFile) {
|
|
|
36116
36442
|
}
|
|
36117
36443
|
|
|
36118
36444
|
// src/container-build.ts
|
|
36119
|
-
import { existsSync as
|
|
36120
|
-
import { join as
|
|
36445
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6 } from "node:fs";
|
|
36446
|
+
import { join as join6 } from "node:path";
|
|
36121
36447
|
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) =>
|
|
36448
|
+
if (existsSync6(join6(root, "Dockerfile"))) return { adapter: "custom-container", issue: null };
|
|
36449
|
+
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." };
|
|
36450
|
+
const manifest = JSON.parse(readFileSync6(join6(root, "package.json"), "utf8"));
|
|
36451
|
+
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." };
|
|
36452
|
+
if (typeof manifest.scripts?.start !== "string" || !manifest.scripts.start || manifest.workspaces || ["pnpm-lock.yaml", "yarn.lock"].some((name2) => existsSync6(join6(root, name2)))) {
|
|
36127
36453
|
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
36454
|
}
|
|
36129
36455
|
return { adapter: "node-npm", issue: null };
|
|
@@ -36141,10 +36467,10 @@ function promptContext(root = process.cwd()) {
|
|
|
36141
36467
|
function installedSdkVersion(root) {
|
|
36142
36468
|
let directory2 = resolve4(root);
|
|
36143
36469
|
while (true) {
|
|
36144
|
-
const manifest =
|
|
36145
|
-
if (
|
|
36470
|
+
const manifest = join7(directory2, "node_modules", "@backifydev", "sdk", "package.json");
|
|
36471
|
+
if (existsSync7(manifest)) {
|
|
36146
36472
|
try {
|
|
36147
|
-
const sdk = JSON.parse(
|
|
36473
|
+
const sdk = JSON.parse(readFileSync7(manifest, "utf8"));
|
|
36148
36474
|
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
36475
|
} catch {
|
|
36150
36476
|
return null;
|
|
@@ -36186,8 +36512,8 @@ function applicationGuid(appId) {
|
|
|
36186
36512
|
return [value.slice(0, 8), value.slice(8, 12), value.slice(12, 16), value.slice(16, 20), value.slice(20)].join("-");
|
|
36187
36513
|
}
|
|
36188
36514
|
function projectApplication(root = process.cwd()) {
|
|
36189
|
-
if (!
|
|
36190
|
-
return JSON.parse(
|
|
36515
|
+
if (!existsSync7(join7(root, "backify.json"))) throw new Error("Run backify connect --app <application-id>, then backify init.");
|
|
36516
|
+
return JSON.parse(readFileSync7(join7(root, "backify.json"), "utf8")).appId;
|
|
36191
36517
|
}
|
|
36192
36518
|
function apiAddress(value) {
|
|
36193
36519
|
const address = new URL(value);
|
|
@@ -36220,13 +36546,13 @@ function apiClient(session, transport = fetch) {
|
|
|
36220
36546
|
};
|
|
36221
36547
|
}
|
|
36222
36548
|
function saveUserConfig(path, config2) {
|
|
36223
|
-
const temporary = path + "." +
|
|
36549
|
+
const temporary = path + "." + randomUUID3() + ".tmp";
|
|
36224
36550
|
try {
|
|
36225
|
-
|
|
36551
|
+
writeFileSync6(temporary, JSON.stringify(config2, null, 2) + "\n", { mode: 384, flag: "wx" });
|
|
36226
36552
|
if (process.platform === "win32") {
|
|
36227
36553
|
const account = [process.env.USERDOMAIN, process.env.USERNAME].filter(Boolean).join("\\");
|
|
36228
36554
|
if (!account) throw new Error("Cannot identify the account to protect CLI credentials.");
|
|
36229
|
-
const secured =
|
|
36555
|
+
const secured = spawnSync4("icacls", [temporary, "/inheritance:r", "/grant:r", account + ":(F)"], { windowsHide: true, encoding: "utf8" });
|
|
36230
36556
|
if (secured.status !== 0) throw new Error("Could not restrict CLI credential file permissions.");
|
|
36231
36557
|
}
|
|
36232
36558
|
renameSync(temporary, path);
|
|
@@ -36240,7 +36566,7 @@ function repositoryName(remote) {
|
|
|
36240
36566
|
return match[1].toLowerCase();
|
|
36241
36567
|
}
|
|
36242
36568
|
function git(args2, root = process.cwd(), environment = process.env) {
|
|
36243
|
-
const result =
|
|
36569
|
+
const result = spawnSync4("git", args2, { cwd: root, env: environment, encoding: "utf8", windowsHide: true, maxBuffer: 2 * 1024 * 1024 });
|
|
36244
36570
|
if (result.status !== 0) throw new Error("Git " + args2[0] + " failed. Check repository access, branch protection, and local changes.");
|
|
36245
36571
|
return result.stdout.trim();
|
|
36246
36572
|
}
|
|
@@ -36250,15 +36576,15 @@ function gitEnvironment(repository, token) {
|
|
|
36250
36576
|
}
|
|
36251
36577
|
function validateCloneMerge(source, target) {
|
|
36252
36578
|
for (const entry of readdirSync2(source, { withFileTypes: true })) {
|
|
36253
|
-
const destination =
|
|
36579
|
+
const destination = join7(target, entry.name);
|
|
36254
36580
|
let existing;
|
|
36255
36581
|
try {
|
|
36256
|
-
existing =
|
|
36582
|
+
existing = lstatSync3(destination);
|
|
36257
36583
|
} catch (reason) {
|
|
36258
36584
|
if (reason.code === "ENOENT") continue;
|
|
36259
36585
|
throw reason;
|
|
36260
36586
|
}
|
|
36261
|
-
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(
|
|
36587
|
+
if (entry.isDirectory() && existing.isDirectory() && !existing.isSymbolicLink()) validateCloneMerge(join7(source, entry.name), destination);
|
|
36262
36588
|
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
36589
|
}
|
|
36264
36590
|
}
|
|
@@ -36268,18 +36594,18 @@ async function cloneProject(call2, appId, root = process.cwd()) {
|
|
|
36268
36594
|
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
36595
|
const credential = await call2("/apps/" + applicationGuid(appId) + "/developer/git-credential", { method: "POST" });
|
|
36270
36596
|
if (credential.repository.toLowerCase() !== status.repository.toLowerCase()) throw new Error("Repository changed. Run connect again.");
|
|
36271
|
-
const staging = mkdtempSync(
|
|
36597
|
+
const staging = mkdtempSync(join7(dirname4(resolve4(root)), ".backify-clone-"));
|
|
36272
36598
|
try {
|
|
36273
36599
|
git(["clone", "--single-branch", "--branch", status.branch, "--", "https://github.com/" + status.repository + ".git", "."], staging, gitEnvironment(status.repository, credential.token));
|
|
36274
36600
|
validateCloneMerge(staging, root);
|
|
36275
|
-
for (const entry of readdirSync2(staging)) cpSync(
|
|
36601
|
+
for (const entry of readdirSync2(staging)) cpSync(join7(staging, entry), join7(root, entry), { recursive: true, force: false, errorOnExist: true, dereference: false });
|
|
36276
36602
|
} finally {
|
|
36277
|
-
if (dirname4(staging) !== dirname4(resolve4(root)) || !staging.startsWith(
|
|
36603
|
+
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
36604
|
rmSync(staging, { recursive: true, force: true });
|
|
36279
36605
|
}
|
|
36280
36606
|
}
|
|
36281
36607
|
async function pullProject(call2, appId, root = process.cwd()) {
|
|
36282
|
-
if (
|
|
36608
|
+
if (existsSync7(join7(root, "backify.json")) && applicationGuid(projectApplication(root)) !== applicationGuid(appId)) throw new Error("Local application ID does not match the connected application.");
|
|
36283
36609
|
const prefix = "/apps/" + applicationGuid(appId);
|
|
36284
36610
|
const status = await call2(prefix + "/developer");
|
|
36285
36611
|
if (!status.repository || !status.branch) throw new Error("Connect the repository and branch in Backify before pulling.");
|
|
@@ -36322,15 +36648,15 @@ function attachmentNames(values) {
|
|
|
36322
36648
|
}))];
|
|
36323
36649
|
}
|
|
36324
36650
|
function localReport(runChecks, root = process.cwd()) {
|
|
36325
|
-
const pkg =
|
|
36651
|
+
const pkg = existsSync7(join7(root, "package.json")) ? JSON.parse(readFileSync7(join7(root, "package.json"), "utf8")) : {};
|
|
36326
36652
|
const dependencies = { ...pkg.devDependencies, ...pkg.dependencies };
|
|
36327
|
-
const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (
|
|
36653
|
+
const framework = ["next", "vite", "astro", "@sveltejs/kit", "nuxt", "react", "express"].find((name2) => dependencies[name2]) ?? (existsSync7(join7(root, "Dockerfile")) ? "custom-container" : "unknown");
|
|
36328
36654
|
const setup = doctor(root);
|
|
36329
36655
|
const checks = [{ name: "backify doctor", status: setup.valid ? "passed" : "failed" }];
|
|
36330
36656
|
const manager = detectPackageManager(root);
|
|
36331
36657
|
for (const name2 of ["typecheck", "lint", "test", "build"]) {
|
|
36332
36658
|
if (!pkg.scripts?.[name2]) continue;
|
|
36333
|
-
const result = runChecks ?
|
|
36659
|
+
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
36660
|
checks.push({ name: name2, status: result ? result.status === 0 ? "passed" : "failed" : "not-run" });
|
|
36335
36661
|
}
|
|
36336
36662
|
let branch = null, commitSha = null, dirty = true;
|
|
@@ -36340,8 +36666,8 @@ function localReport(runChecks, root = process.cwd()) {
|
|
|
36340
36666
|
dirty = Boolean(git(["status", "--porcelain"], root));
|
|
36341
36667
|
} catch {
|
|
36342
36668
|
}
|
|
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:
|
|
36669
|
+
const outputDirectory = ["dist", "build", "out", "."].find((directory2) => existsSync7(join7(root, directory2, "index.html"))) ?? null;
|
|
36670
|
+
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
36671
|
}
|
|
36346
36672
|
function matchesSource(release2, commit) {
|
|
36347
36673
|
return release2?.commitSha === commit || release2?.sourceCommitSha === commit;
|
|
@@ -36363,7 +36689,7 @@ function pushSource(appId, commit, branch, destination, root, environment) {
|
|
|
36363
36689
|
}
|
|
36364
36690
|
async function waitForPreview(call2, prefix, commit, options = {}) {
|
|
36365
36691
|
const deadline = Date.now() + (options.timeoutMs ?? 20 * 6e4);
|
|
36366
|
-
const sleep = options.sleep ?? ((
|
|
36692
|
+
const sleep = options.sleep ?? ((delay3) => new Promise((resolve25) => setTimeout(resolve25, delay3)));
|
|
36367
36693
|
do {
|
|
36368
36694
|
const deployments = await call2(prefix + "/deployments");
|
|
36369
36695
|
const matching = deployments.find((release2) => release2.kind === "preview" && matchesSource(release2, commit) && !options.previousDeploymentIds?.includes(release2.id));
|
|
@@ -36557,11 +36883,11 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
|
|
|
36557
36883
|
}
|
|
36558
36884
|
|
|
36559
36885
|
// src/local-runtime.ts
|
|
36560
|
-
import { createHash as createHash2, randomUUID as
|
|
36561
|
-
import { chmodSync, existsSync as
|
|
36562
|
-
import { dirname as dirname5, join as
|
|
36886
|
+
import { createHash as createHash2, randomUUID as randomUUID4 } from "node:crypto";
|
|
36887
|
+
import { chmodSync, existsSync as existsSync8, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync8, readdirSync as readdirSync3, writeFileSync as writeFileSync7 } from "node:fs";
|
|
36888
|
+
import { dirname as dirname5, join as join8, resolve as resolve5, sep } from "node:path";
|
|
36563
36889
|
import { homedir } from "node:os";
|
|
36564
|
-
import { spawnSync as
|
|
36890
|
+
import { spawnSync as spawnSync5 } from "node:child_process";
|
|
36565
36891
|
|
|
36566
36892
|
// src/local-state.ts
|
|
36567
36893
|
import { renameSync as renameSync2 } from "node:fs";
|
|
@@ -36594,7 +36920,7 @@ function checkedPath(root, filename2) {
|
|
|
36594
36920
|
if (target !== resolve5(root) && !target.startsWith(resolve5(root) + sep)) throw new Error("Runtime path escapes its installation");
|
|
36595
36921
|
let current = target;
|
|
36596
36922
|
while (true) {
|
|
36597
|
-
if (
|
|
36923
|
+
if (existsSync8(current) && lstatSync4(current).isSymbolicLink()) throw new Error("Runtime installation must not follow links");
|
|
36598
36924
|
if (dirname5(current) === current) break;
|
|
36599
36925
|
current = dirname5(current);
|
|
36600
36926
|
}
|
|
@@ -36602,25 +36928,25 @@ function checkedPath(root, filename2) {
|
|
|
36602
36928
|
}
|
|
36603
36929
|
function verifyInstallationFiles(root, expected, directory2 = root) {
|
|
36604
36930
|
for (const entry of readdirSync3(directory2, { withFileTypes: true })) {
|
|
36605
|
-
const path = checkedPath(root,
|
|
36931
|
+
const path = checkedPath(root, join8(directory2, entry.name));
|
|
36606
36932
|
if (entry.isDirectory()) verifyInstallationFiles(root, expected, path);
|
|
36607
36933
|
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
36934
|
}
|
|
36609
36935
|
}
|
|
36610
|
-
function installedLocalRuntime(base =
|
|
36936
|
+
function installedLocalRuntime(base = join8(homedir(), ".backify")) {
|
|
36611
36937
|
const pointer = checkedPath(base, "runtime.json");
|
|
36612
|
-
if (!
|
|
36613
|
-
const installed = JSON.parse(
|
|
36938
|
+
if (!existsSync8(pointer)) return void 0;
|
|
36939
|
+
const installed = JSON.parse(readFileSync8(pointer, "utf8"));
|
|
36614
36940
|
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,
|
|
36941
|
+
const root = checkedPath(base, join8("runtimes", installed.version, installed.rid));
|
|
36616
36942
|
verifyInstallationFiles(root, installed.files);
|
|
36617
36943
|
for (const [filename2, digest4] of Object.entries(installed.files)) {
|
|
36618
36944
|
const path = checkedPath(root, filename2);
|
|
36619
|
-
if (!/^[a-f0-9]{64}$/.test(digest4) || !
|
|
36945
|
+
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
36946
|
}
|
|
36621
36947
|
const executableName = installed.rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
36622
36948
|
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:
|
|
36949
|
+
return { path: join8(root, "Backify.Hcr.dll"), executable: join8(root, executableName), version: installed.version, rid: installed.rid };
|
|
36624
36950
|
}
|
|
36625
36951
|
function installLocalRuntime(archive, options) {
|
|
36626
36952
|
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 +36960,28 @@ function installLocalRuntime(archive, options) {
|
|
|
36634
36960
|
const rid = runtimeIdentifier();
|
|
36635
36961
|
const executable = rid.startsWith("win-") ? "Backify.Hcr.exe" : "Backify.Hcr";
|
|
36636
36962
|
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,
|
|
36963
|
+
const base = options.base ?? join8(homedir(), ".backify");
|
|
36964
|
+
const parent = checkedPath(base, join8("runtimes", options.version));
|
|
36639
36965
|
mkdirSync3(parent, { recursive: true, mode: 448 });
|
|
36640
36966
|
const destination = checkedPath(parent, rid);
|
|
36641
36967
|
const receipt = { version: options.version, rid, files: Object.fromEntries(Object.entries(files).map(([name2, bytes]) => [name2, hash(bytes)])) };
|
|
36642
|
-
if (!
|
|
36643
|
-
const staging = checkedPath(parent, ".install-" +
|
|
36968
|
+
if (!existsSync8(destination)) {
|
|
36969
|
+
const staging = checkedPath(parent, ".install-" + randomUUID4());
|
|
36644
36970
|
mkdirSync3(staging, { mode: 448 });
|
|
36645
36971
|
for (const [name2, bytes] of Object.entries(files)) {
|
|
36646
36972
|
const filename2 = checkedPath(staging, name2);
|
|
36647
36973
|
mkdirSync3(dirname5(filename2), { recursive: true, mode: 448 });
|
|
36648
|
-
|
|
36974
|
+
writeFileSync7(filename2, bytes, { flag: "wx", mode: name2 === executable ? 448 : 384 });
|
|
36649
36975
|
}
|
|
36650
|
-
if (process.platform !== "win32") chmodSync(
|
|
36976
|
+
if (process.platform !== "win32") chmodSync(join8(staging, executable), 448);
|
|
36651
36977
|
renameLocalFile(staging, destination);
|
|
36652
36978
|
} else {
|
|
36653
36979
|
verifyInstallationFiles(destination, receipt.files);
|
|
36654
|
-
for (const [name2, digest4] of Object.entries(receipt.files)) if (hash(
|
|
36980
|
+
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
36981
|
}
|
|
36656
36982
|
const pointer = checkedPath(base, "runtime.json");
|
|
36657
|
-
const temporary = checkedPath(base, ".runtime-" +
|
|
36658
|
-
|
|
36983
|
+
const temporary = checkedPath(base, ".runtime-" + randomUUID4() + ".json");
|
|
36984
|
+
writeFileSync7(temporary, JSON.stringify(receipt), { flag: "wx", mode: 384 });
|
|
36659
36985
|
renameLocalFile(temporary, pointer);
|
|
36660
36986
|
return installedLocalRuntime(base);
|
|
36661
36987
|
}
|
|
@@ -36683,10 +37009,10 @@ async function downloadLocalRuntime(version2) {
|
|
|
36683
37009
|
}
|
|
36684
37010
|
function localPrerequisites() {
|
|
36685
37011
|
const runtime = installedLocalRuntime();
|
|
36686
|
-
const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
37012
|
+
const directory2 = process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join8(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
|
|
36687
37013
|
const checks = ["initdb", "pg_ctl", "psql"].map((name2) => {
|
|
36688
|
-
const executable = directory2 ?
|
|
36689
|
-
const result =
|
|
37014
|
+
const executable = directory2 ? join8(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
37015
|
+
const result = spawnSync5(executable, ["--version"], { windowsHide: true, timeout: 1e4, encoding: "utf8" });
|
|
36690
37016
|
return { name: name2, available: result.status === 0 };
|
|
36691
37017
|
});
|
|
36692
37018
|
return { rid: runtimeIdentifier(), runtime: runtime ? { installed: true, version: runtime.version } : { installed: false }, postgres: checks, ready: !!runtime && checks.every((check2) => check2.available) };
|
|
@@ -36695,20 +37021,20 @@ function localPrerequisites() {
|
|
|
36695
37021
|
// src/workload.ts
|
|
36696
37022
|
import { build as build2 } from "esbuild";
|
|
36697
37023
|
import { createHash as createHash14 } from "node:crypto";
|
|
36698
|
-
import { existsSync as
|
|
36699
|
-
import { dirname as dirname13, isAbsolute as isAbsolute14, join as
|
|
37024
|
+
import { existsSync as existsSync15, mkdirSync as mkdirSync7, readFileSync as readFileSync23, realpathSync as realpathSync6, readdirSync as readdirSync6, writeFileSync as writeFileSync13 } from "node:fs";
|
|
37025
|
+
import { dirname as dirname13, isAbsolute as isAbsolute14, join as join17, relative as relative8, resolve as resolve19 } from "node:path";
|
|
36700
37026
|
|
|
36701
37027
|
// src/local-development.ts
|
|
36702
37028
|
import { context as context2, formatMessagesSync } from "esbuild";
|
|
36703
37029
|
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
|
|
37030
|
+
import { randomBytes as randomBytes6, randomUUID as randomUUID12, createHash as createHash13 } from "node:crypto";
|
|
37031
|
+
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";
|
|
37032
|
+
import { resolve as resolve18, join as join16, relative as relative7, isAbsolute as isAbsolute13, dirname as dirname12 } from "node:path";
|
|
36707
37033
|
|
|
36708
37034
|
// ../analyzer/dist/index.js
|
|
36709
37035
|
import ts3 from "typescript";
|
|
36710
|
-
import { readFileSync as
|
|
36711
|
-
import { join as
|
|
37036
|
+
import { readFileSync as readFileSync9, readdirSync as readdirSync4, existsSync as existsSync9 } from "node:fs";
|
|
37037
|
+
import { join as join9, extname } from "node:path";
|
|
36712
37038
|
|
|
36713
37039
|
// ../analyzer/dist/authentication.js
|
|
36714
37040
|
import ts from "typescript";
|
|
@@ -37125,230 +37451,18 @@ function repositorySources(root) {
|
|
|
37125
37451
|
for (const entry of readdirSync4(dir, { withFileTypes: true })) {
|
|
37126
37452
|
if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".backify" || entry.name.startsWith(".git"))
|
|
37127
37453
|
continue;
|
|
37128
|
-
const path =
|
|
37454
|
+
const path = join9(dir, entry.name);
|
|
37129
37455
|
if (entry.isDirectory())
|
|
37130
37456
|
walk(path);
|
|
37131
37457
|
else if ([".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs"].includes(extname(path)))
|
|
37132
|
-
result.push({ path, content:
|
|
37458
|
+
result.push({ path, content: readFileSync9(path, "utf8") });
|
|
37133
37459
|
}
|
|
37134
37460
|
};
|
|
37135
|
-
if (
|
|
37461
|
+
if (existsSync9(root))
|
|
37136
37462
|
walk(root);
|
|
37137
37463
|
return result;
|
|
37138
37464
|
}
|
|
37139
37465
|
|
|
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
37466
|
// ../sdk/dist/schedules.js
|
|
37353
37467
|
var import_cron_parser = __toESM(require_dist2(), 1);
|
|
37354
37468
|
function nextSchedule(input, after, creating = false) {
|
|
@@ -37391,6 +37505,9 @@ function declarationInput(declaration) {
|
|
|
37391
37505
|
return { ...base, kind: "cron", expression: schedule.kind === "hourly" ? "0 * * * *" : schedule.kind === "daily" ? minute + " " + hour + " * * *" : minute + " " + hour + " * * " + day };
|
|
37392
37506
|
}
|
|
37393
37507
|
|
|
37508
|
+
// ../sdk/dist/local-identity.js
|
|
37509
|
+
import { createHash as createHash3, randomBytes as randomBytes2, randomUUID as randomUUID5 } from "node:crypto";
|
|
37510
|
+
|
|
37394
37511
|
// ../sdk/dist/application-auth.js
|
|
37395
37512
|
import { createPublicKey, verify } from "node:crypto";
|
|
37396
37513
|
var ApplicationAuthenticationError = class extends Error {
|
|
@@ -37403,7 +37520,7 @@ var ApplicationAuthenticationError = class extends Error {
|
|
|
37403
37520
|
this.status = code === "application_identity_unavailable" ? 503 : code === "application_identity_forbidden" ? 403 : 401;
|
|
37404
37521
|
}
|
|
37405
37522
|
};
|
|
37406
|
-
var
|
|
37523
|
+
var uuid3 = (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";
|
|
37407
37524
|
var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
37408
37525
|
var text = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
|
|
37409
37526
|
function invalid() {
|
|
@@ -37449,7 +37566,7 @@ function json(segment) {
|
|
|
37449
37566
|
}
|
|
37450
37567
|
}
|
|
37451
37568
|
function scopeValid(scope) {
|
|
37452
|
-
return object2(scope) && Object.keys(scope).length === 3 &&
|
|
37569
|
+
return object2(scope) && Object.keys(scope).length === 3 && uuid3(scope.organizationId) && uuid3(scope.applicationId) && uuid3(scope.environmentId);
|
|
37453
37570
|
}
|
|
37454
37571
|
function sameScope(left, right) {
|
|
37455
37572
|
return left.organizationId === right.organizationId && left.applicationId === right.applicationId && left.environmentId === right.environmentId;
|
|
@@ -37480,86 +37597,495 @@ function createApplicationAuthProvider(source, options) {
|
|
|
37480
37597
|
unavailable();
|
|
37481
37598
|
return value;
|
|
37482
37599
|
};
|
|
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;
|
|
37600
|
+
let current;
|
|
37601
|
+
const load = () => {
|
|
37602
|
+
try {
|
|
37603
|
+
if (typeof window !== "undefined")
|
|
37604
|
+
unavailable();
|
|
37605
|
+
const input = structuredClone(typeof source === "function" ? source() : source);
|
|
37606
|
+
const content = JSON.stringify(input);
|
|
37607
|
+
const time3 = now();
|
|
37608
|
+
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)
|
|
37609
|
+
unavailable();
|
|
37610
|
+
const issuer = new URL(input.issuer);
|
|
37611
|
+
if (issuer.protocol !== "https:" || issuer.username || issuer.password || issuer.search || issuer.hash)
|
|
37612
|
+
unavailable();
|
|
37613
|
+
if (current && (input.revision < current.trust.revision || input.revision === current.trust.revision && content !== current.content))
|
|
37614
|
+
unavailable();
|
|
37615
|
+
if (current?.content === content) {
|
|
37616
|
+
options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
|
|
37617
|
+
return current;
|
|
37618
|
+
}
|
|
37619
|
+
const keys = /* @__PURE__ */ new Map();
|
|
37620
|
+
for (const entry of input.keys) {
|
|
37621
|
+
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))
|
|
37622
|
+
unavailable();
|
|
37623
|
+
const key = createPublicKey(entry.publicKeyPem);
|
|
37624
|
+
const bits2 = key.asymmetricKeyDetails?.modulusLength ?? 0;
|
|
37625
|
+
if (key.asymmetricKeyType !== "rsa" || bits2 < 2048 || bits2 > 8192)
|
|
37626
|
+
unavailable();
|
|
37627
|
+
keys.set(entry.id, key);
|
|
37628
|
+
}
|
|
37629
|
+
options.checkpoint?.({ revision: input.revision, scope: structuredClone(expectedScope), content });
|
|
37630
|
+
current = { trust: input, content, keys };
|
|
37631
|
+
return current;
|
|
37632
|
+
} catch {
|
|
37633
|
+
return unavailable();
|
|
37634
|
+
}
|
|
37635
|
+
};
|
|
37636
|
+
load();
|
|
37637
|
+
return {
|
|
37638
|
+
forRequest(request) {
|
|
37639
|
+
const authorization = request.headers.get("authorization");
|
|
37640
|
+
const identity = () => {
|
|
37641
|
+
const { trust, keys } = load();
|
|
37642
|
+
if (authorization === null)
|
|
37643
|
+
return null;
|
|
37644
|
+
if (authorization.length > 16384)
|
|
37645
|
+
invalid();
|
|
37646
|
+
const match = /^Bearer ([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/i.exec(authorization);
|
|
37647
|
+
if (!match)
|
|
37648
|
+
invalid();
|
|
37649
|
+
const header = json(match[1]);
|
|
37650
|
+
fields(header, ["alg", "typ", "kid"]);
|
|
37651
|
+
if (header.alg !== "RS256" || header.typ !== "backify-user+jwt" || typeof header.kid !== "string")
|
|
37652
|
+
invalid();
|
|
37653
|
+
const key = keys.get(header.kid);
|
|
37654
|
+
if (!key)
|
|
37655
|
+
invalid();
|
|
37656
|
+
const signature = Buffer.from(match[3], "base64url");
|
|
37657
|
+
if (signature.toString("base64url") !== match[3] || signature.length !== key.asymmetricKeyDetails.modulusLength / 8 || !verify("RSA-SHA256", Buffer.from(match[1] + "." + match[2]), key, signature))
|
|
37658
|
+
invalid();
|
|
37659
|
+
const payload = json(match[2]);
|
|
37660
|
+
fields(payload, ["ver", "iss", "aud", "sub", "organization_id", "application_id", "environment_id", "iat", "nbf", "exp", "jti", "display_name", "email", "organization_name", "roles"]);
|
|
37661
|
+
const time3 = now();
|
|
37662
|
+
if (payload.ver !== 1 || payload.iss !== trust.issuer || payload.aud !== trust.audience || !uuid3(payload.sub) || payload.organization_id !== expectedScope.organizationId || payload.application_id !== expectedScope.applicationId || payload.environment_id !== expectedScope.environmentId || !uuid3(payload.jti) || !Number.isSafeInteger(payload.iat) || !Number.isSafeInteger(payload.nbf) || !Number.isSafeInteger(payload.exp))
|
|
37663
|
+
invalid();
|
|
37664
|
+
const issued = payload.iat, notBefore = payload.nbf, expires = payload.exp;
|
|
37665
|
+
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))
|
|
37666
|
+
invalid();
|
|
37667
|
+
return {
|
|
37668
|
+
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 } },
|
|
37669
|
+
organization: { id: expectedScope.organizationId, name: payload.organization_name }
|
|
37670
|
+
};
|
|
37671
|
+
};
|
|
37672
|
+
return { currentUser: async () => identity()?.user ?? null, currentOrganization: async () => identity()?.organization ?? null };
|
|
37673
|
+
}
|
|
37674
|
+
};
|
|
37675
|
+
}
|
|
37676
|
+
|
|
37677
|
+
// ../sdk/dist/local-identity.js
|
|
37678
|
+
function createLocalIdentityProvider(options) {
|
|
37679
|
+
const serverOnly = () => {
|
|
37680
|
+
if (typeof window !== "undefined")
|
|
37681
|
+
throw new Error("Local development identities are server-only");
|
|
37682
|
+
};
|
|
37683
|
+
serverOnly();
|
|
37684
|
+
if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
|
|
37685
|
+
throw new Error("Local Backify identities must not run in production");
|
|
37686
|
+
const uuid7 = (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";
|
|
37687
|
+
const text3 = (value, maximum) => typeof value === "string" && value.length > 0 && value.length <= maximum && !/[\x00-\x1f\x7f]/.test(value);
|
|
37688
|
+
if (!options.scope || Object.keys(options.scope).length !== 3 || !uuid7(options.scope.organizationId) || !uuid7(options.scope.applicationId) || !uuid7(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)
|
|
37689
|
+
throw new Error("Invalid local identity configuration");
|
|
37690
|
+
const scope = { ...options.scope }, organizationName = options.organizationName;
|
|
37691
|
+
const users = /* @__PURE__ */ new Map();
|
|
37692
|
+
for (const user of options.users) {
|
|
37693
|
+
if (!user || Object.keys(user).some((name2) => !["id", "displayName", "email", "roles"].includes(name2)) || !uuid7(user.id) || users.has(user.id) || !text3(user.displayName, 200) || user.email !== void 0 && !text3(user.email, 320))
|
|
37694
|
+
throw new Error("Invalid local identity user");
|
|
37695
|
+
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))
|
|
37696
|
+
throw new Error("Invalid local identity roles");
|
|
37697
|
+
users.set(user.id, structuredClone(user));
|
|
37698
|
+
}
|
|
37699
|
+
const origins = /* @__PURE__ */ new Set();
|
|
37700
|
+
for (const value of options.requestOrigins) {
|
|
37701
|
+
let origin;
|
|
37702
|
+
try {
|
|
37703
|
+
origin = new URL(value);
|
|
37704
|
+
} catch {
|
|
37705
|
+
throw new Error("Invalid local identity origin");
|
|
37706
|
+
}
|
|
37707
|
+
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))
|
|
37708
|
+
throw new Error("Local identities require exact loopback origins");
|
|
37709
|
+
origins.add(value);
|
|
37710
|
+
}
|
|
37711
|
+
const clock = options.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
37712
|
+
const now = () => {
|
|
37713
|
+
serverOnly();
|
|
37714
|
+
const value = clock();
|
|
37715
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > 253402300499)
|
|
37716
|
+
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
37717
|
+
return value;
|
|
37718
|
+
};
|
|
37719
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
37720
|
+
const digest4 = (token) => createHash3("sha256").update(token).digest("hex");
|
|
37721
|
+
const tokenPattern = /^backify-local-user_[a-zA-Z0-9_-]{43}$/;
|
|
37722
|
+
const requestAuth = {
|
|
37723
|
+
forRequest(request) {
|
|
37724
|
+
serverOnly();
|
|
37725
|
+
const authorization = request.headers.get("authorization"), origin = new URL(request.url).origin;
|
|
37726
|
+
const identity = () => {
|
|
37727
|
+
const time3 = now();
|
|
37728
|
+
if (!origins.has(origin))
|
|
37729
|
+
throw new ApplicationAuthenticationError("application_identity_invalid");
|
|
37730
|
+
if (authorization === null)
|
|
37731
|
+
return null;
|
|
37732
|
+
const match = /^Bearer (backify-local-user_[a-zA-Z0-9_-]{43})$/i.exec(authorization);
|
|
37733
|
+
const session = match && tokenPattern.test(match[1]) ? sessions.get(digest4(match[1])) : void 0;
|
|
37734
|
+
if (!session || session.issued > time3 || session.expires <= time3)
|
|
37735
|
+
throw new ApplicationAuthenticationError("application_identity_invalid");
|
|
37736
|
+
const user = users.get(session.userId);
|
|
37737
|
+
return { ...structuredClone(user), roles: structuredClone(user.roles ?? []), claims: { ...scope, localDevelopment: true } };
|
|
37738
|
+
};
|
|
37739
|
+
return { currentUser: async () => identity(), currentOrganization: async () => identity() ? { id: scope.organizationId, name: organizationName } : null };
|
|
37740
|
+
}
|
|
37741
|
+
};
|
|
37742
|
+
return {
|
|
37743
|
+
requestAuth,
|
|
37744
|
+
profiles() {
|
|
37745
|
+
serverOnly();
|
|
37746
|
+
return [...users.values()].map((user) => structuredClone(user));
|
|
37747
|
+
},
|
|
37748
|
+
issue(userId, lifetimeSeconds = 300) {
|
|
37749
|
+
const time3 = now();
|
|
37750
|
+
if (!users.has(userId) || !Number.isInteger(lifetimeSeconds) || lifetimeSeconds < 1 || lifetimeSeconds > 300)
|
|
37751
|
+
throw new Error("Invalid local identity issuance");
|
|
37752
|
+
for (const [hash2, session] of sessions)
|
|
37753
|
+
if (session.expires <= time3)
|
|
37754
|
+
sessions.delete(hash2);
|
|
37755
|
+
if (sessions.size >= 128)
|
|
37756
|
+
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
37757
|
+
const accessToken = "backify-local-user_" + randomBytes2(32).toString("base64url"), expires = time3 + lifetimeSeconds;
|
|
37758
|
+
sessions.set(digest4(accessToken), { userId, issued: time3, expires });
|
|
37759
|
+
return { accessToken, tokenType: "Bearer", expiresAt: new Date(expires * 1e3).toISOString() };
|
|
37760
|
+
},
|
|
37761
|
+
revoke(accessToken) {
|
|
37762
|
+
serverOnly();
|
|
37763
|
+
return typeof accessToken === "string" && tokenPattern.test(accessToken) && sessions.delete(digest4(accessToken));
|
|
37764
|
+
},
|
|
37765
|
+
clear() {
|
|
37766
|
+
serverOnly();
|
|
37767
|
+
sessions.clear();
|
|
37768
|
+
}
|
|
37769
|
+
};
|
|
37770
|
+
}
|
|
37771
|
+
function createLocalEmailAuth(options, crypto2 = { createHash: createHash3, randomBytes: randomBytes2, randomUUID: randomUUID5 }) {
|
|
37772
|
+
const { createHash: createHash17, randomBytes: randomBytes7, randomUUID: randomUUID14 } = crypto2;
|
|
37773
|
+
const origin = new URL(options.origin);
|
|
37774
|
+
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)
|
|
37775
|
+
throw new Error("Local email authentication requires an exact loopback origin outside production");
|
|
37776
|
+
const clock = options.now ?? (() => Date.now());
|
|
37777
|
+
const challenges = /* @__PURE__ */ new Map();
|
|
37778
|
+
const inbox = [];
|
|
37779
|
+
const starts = /* @__PURE__ */ new Map();
|
|
37780
|
+
const hash2 = (value) => createHash17("sha256").update(value).digest("hex");
|
|
37781
|
+
const random2 = () => randomBytes7(32).toString("base64url");
|
|
37782
|
+
const cookie = (name2, value, seconds) => name2 + "=" + value + "; HttpOnly; SameSite=Strict; Path=/; Max-Age=" + seconds + (origin.protocol === "https:" ? "; Secure" : "");
|
|
37783
|
+
const readCookie = (request, name2) => request.headers.get("cookie")?.split(";").map((item) => item.trim()).find((item) => item.startsWith(name2 + "="))?.slice(name2.length + 1) ?? "";
|
|
37784
|
+
const json4 = (value, status = 200, headers = {}) => Response.json(value, { status, headers: { "cache-control": "no-store", ...headers } });
|
|
37785
|
+
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 } });
|
|
37786
|
+
const tokenPattern = /^[A-Za-z0-9_-]{43}$/;
|
|
37787
|
+
return {
|
|
37788
|
+
inbox() {
|
|
37789
|
+
return structuredClone(inbox);
|
|
37790
|
+
},
|
|
37791
|
+
async handle(request) {
|
|
37792
|
+
const url2 = new URL(request.url);
|
|
37793
|
+
if (url2.origin !== origin.origin || !url2.pathname.startsWith("/.backify/auth/"))
|
|
37794
|
+
return json4({ error: "invalid_local_origin" }, 403);
|
|
37795
|
+
if (request.method === "POST" && request.headers.get("origin") !== origin.origin)
|
|
37796
|
+
return json4({ error: "invalid_local_origin" }, 403);
|
|
37797
|
+
const path = url2.pathname.slice("/.backify/auth/".length);
|
|
37798
|
+
const ticket = readCookie(request, "backify_local_session");
|
|
37799
|
+
let user = null;
|
|
37800
|
+
try {
|
|
37801
|
+
user = await options.identity.requestAuth.forRequest(new Request(origin.origin, { headers: ticket ? { authorization: "Bearer " + ticket } : {} })).currentUser();
|
|
37802
|
+
} catch {
|
|
37803
|
+
}
|
|
37804
|
+
if (request.method === "GET" && path === "me")
|
|
37805
|
+
return json4(user);
|
|
37806
|
+
if (request.method === "GET" && path === "organization")
|
|
37807
|
+
return json4(user ? { id: user.claims?.organizationId, name: "Local development" } : null);
|
|
37808
|
+
if (request.method === "POST" && path === "access-token")
|
|
37809
|
+
return user ? json4({ accessToken: ticket, tokenType: "Bearer", expiresAt: new Date(clock() + 6e4).toISOString() }) : json4({ error: "authentication_required" }, 401);
|
|
37810
|
+
if (request.method === "POST" && path === "signout") {
|
|
37811
|
+
options.identity.revoke(ticket);
|
|
37812
|
+
return new Response(null, { status: 204, headers: { "set-cookie": cookie("backify_local_session", "", 0), "cache-control": "no-store" } });
|
|
37813
|
+
}
|
|
37814
|
+
if (request.method === "GET" && path === "login")
|
|
37815
|
+
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>");
|
|
37816
|
+
if (request.method === "POST" && (path === "email/start" || path === "email/request")) {
|
|
37817
|
+
if (Number(request.headers.get("content-length") ?? 0) > 4096)
|
|
37818
|
+
return json4({ error: "request_too_large" }, 413);
|
|
37819
|
+
const body = await request.text();
|
|
37820
|
+
if (body.length > 4096)
|
|
37821
|
+
return json4({ error: "request_too_large" }, 413);
|
|
37822
|
+
let input;
|
|
37823
|
+
try {
|
|
37824
|
+
input = path === "email/request" ? Object.fromEntries(new URLSearchParams(body)) : JSON.parse(body);
|
|
37825
|
+
} catch {
|
|
37826
|
+
return json4({ error: "invalid_email_request" }, 400);
|
|
37827
|
+
}
|
|
37828
|
+
if (!input || typeof input.email !== "string" || input.email.length > 320 || input.method !== void 0 && input.method !== "magic-link")
|
|
37829
|
+
return json4({ error: "local_magic_links_only" }, 400);
|
|
37830
|
+
const email2 = input.email.trim().toLowerCase();
|
|
37831
|
+
const recent = (starts.get(email2) ?? []).filter((time3) => time3 > clock() - 6e4);
|
|
37832
|
+
if (recent.length >= 5 || starts.size >= 256 && !starts.has(email2))
|
|
37833
|
+
return json4({ error: "rate_limited" }, 429);
|
|
37834
|
+
starts.set(email2, [...recent, clock()]);
|
|
37835
|
+
for (const [id2, challenge] of challenges)
|
|
37836
|
+
if (challenge.expires <= clock())
|
|
37837
|
+
challenges.delete(id2);
|
|
37838
|
+
if (challenges.size >= 128)
|
|
37839
|
+
return json4({ error: "rate_limited" }, 429);
|
|
37840
|
+
const id = randomUUID14(), proof = random2(), secret = random2();
|
|
37841
|
+
const profile = options.identity.profiles().find((item) => item.email?.toLowerCase() === email2);
|
|
37842
|
+
if (profile) {
|
|
37843
|
+
challenges.set(id, { userId: profile.id, proof: hash2(proof), token: hash2(secret), expires: clock() + 6e5 });
|
|
37844
|
+
inbox.push({ email: email2, text: origin.origin + "/.backify/auth/email/link?id=" + id + "&code=" + secret, createdAt: new Date(clock()).toISOString() });
|
|
37845
|
+
if (inbox.length > 128)
|
|
37846
|
+
inbox.shift();
|
|
37847
|
+
}
|
|
37848
|
+
const headers = { "set-cookie": cookie("backify_local_email_proof", proof, 600) };
|
|
37849
|
+
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);
|
|
37850
|
+
}
|
|
37851
|
+
if (request.method === "GET" && path === "email/link") {
|
|
37852
|
+
const id = url2.searchParams.get("id") ?? "", secret = url2.searchParams.get("code") ?? "";
|
|
37853
|
+
if (!/^[a-f0-9-]{36}$/.test(id) || !tokenPattern.test(secret))
|
|
37854
|
+
return json4({ error: "invalid_email_link" }, 400);
|
|
37855
|
+
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>");
|
|
37856
|
+
}
|
|
37857
|
+
if (request.method === "POST" && path === "email/confirm") {
|
|
37858
|
+
const body = await request.text();
|
|
37859
|
+
if (body.length > 4096)
|
|
37860
|
+
return json4({ error: "request_too_large" }, 413);
|
|
37861
|
+
const input = new URLSearchParams(body), id = input.get("id") ?? "", secret = input.get("code") ?? "";
|
|
37862
|
+
const challenge = challenges.get(id), proof = readCookie(request, "backify_local_email_proof");
|
|
37863
|
+
if (!challenge || challenge.expires <= clock() || !tokenPattern.test(secret) || !tokenPattern.test(proof) || challenge.proof !== hash2(proof) || challenge.token !== hash2(secret))
|
|
37864
|
+
return json4({ error: "invalid_email_link" }, 400);
|
|
37865
|
+
challenges.delete(id);
|
|
37866
|
+
const identity = options.identity.issue(challenge.userId);
|
|
37867
|
+
return new Response(null, { status: 303, headers: { location: "/", "set-cookie": cookie("backify_local_session", identity.accessToken, 300), "cache-control": "no-store" } });
|
|
37868
|
+
}
|
|
37869
|
+
return json4({ error: "local_auth_route_unavailable" }, 404);
|
|
37870
|
+
}
|
|
37871
|
+
};
|
|
37872
|
+
}
|
|
37873
|
+
|
|
37874
|
+
// src/local-inspection.ts
|
|
37875
|
+
function createLocalDataInspector(runtime, options) {
|
|
37876
|
+
const tableName = (value) => typeof value === "string" && /^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(value) && !/^__backify/i.test(value);
|
|
37877
|
+
const bucketName = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(value);
|
|
37878
|
+
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");
|
|
37879
|
+
const fail = () => {
|
|
37880
|
+
throw new Error("invalid_local_inspection");
|
|
37881
|
+
};
|
|
37882
|
+
const unavailable4 = () => {
|
|
37883
|
+
throw new Error("local_inspection_unavailable");
|
|
37884
|
+
};
|
|
37885
|
+
const providerRequest = async (operation, missingObject = false) => {
|
|
37886
|
+
try {
|
|
37887
|
+
return await operation();
|
|
37888
|
+
} catch (error2) {
|
|
37889
|
+
const status = error2?.status;
|
|
37890
|
+
if (status === 413) throw new Error("local_inspection_too_large");
|
|
37891
|
+
if (status === 400) fail();
|
|
37892
|
+
if (status === 404 && missingObject) throw new Error("local_inspection_not_found");
|
|
37893
|
+
return unavailable4();
|
|
37894
|
+
}
|
|
37895
|
+
};
|
|
37896
|
+
const object7 = (value, fields5) => {
|
|
37897
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some((name2) => !fields5.includes(name2))) fail();
|
|
37898
|
+
return value;
|
|
37899
|
+
};
|
|
37900
|
+
const page = (input) => {
|
|
37901
|
+
const limit = input.limit ?? 25, offset = input.offset ?? 0;
|
|
37902
|
+
if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 50 || typeof offset !== "number" || !Number.isInteger(offset) || offset < 0 || offset > 1e4) fail();
|
|
37903
|
+
return { limit, offset };
|
|
37904
|
+
};
|
|
37905
|
+
const bounded = (value) => {
|
|
37906
|
+
if (Buffer.byteLength(JSON.stringify(value)) > 65536) throw new Error("local_inspection_too_large");
|
|
37907
|
+
return value;
|
|
37908
|
+
};
|
|
37909
|
+
const redact = (value, depth = 0) => {
|
|
37910
|
+
if (depth > 20) return "[DEPTH LIMIT]";
|
|
37911
|
+
if (Array.isArray(value)) return value.map((item) => redact(item, depth + 1));
|
|
37912
|
+
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)]));
|
|
37913
|
+
return value;
|
|
37914
|
+
};
|
|
37915
|
+
const requireBucket = (name2) => {
|
|
37916
|
+
if (!options.storageEnabled) unavailable4();
|
|
37917
|
+
const known = [...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)];
|
|
37918
|
+
if (!bucketName(name2) || !known.includes(name2)) fail();
|
|
37919
|
+
return name2;
|
|
37920
|
+
};
|
|
37921
|
+
return {
|
|
37922
|
+
async tables() {
|
|
37923
|
+
if (!options.databaseEnabled) unavailable4();
|
|
37924
|
+
if (runtime.database.listTables) return bounded(await providerRequest(() => runtime.database.listTables()));
|
|
37925
|
+
if (options.nativeDatabase) unavailable4();
|
|
37926
|
+
const names = runtime.inspect().tables.map((table) => table.name).filter(tableName).sort();
|
|
37927
|
+
return { names: names.slice(0, 100), hasMore: names.length > 100 };
|
|
37928
|
+
},
|
|
37929
|
+
async rows(value) {
|
|
37930
|
+
if (!options.databaseEnabled) unavailable4();
|
|
37931
|
+
const input = object7(value, ["table", "limit", "offset"]), pagination = page(input);
|
|
37932
|
+
if (!tableName(input.table)) fail();
|
|
37933
|
+
if (runtime.database.inspectRows) {
|
|
37934
|
+
const result = await providerRequest(() => runtime.database.inspectRows(input.table, pagination));
|
|
37935
|
+
return bounded({ ...result, rows: result.rows.map((row) => redact(row)) });
|
|
37936
|
+
}
|
|
37937
|
+
if (options.nativeDatabase) unavailable4();
|
|
37938
|
+
const rows = await runtime.database.query(input.table, { filters: [], limit: pagination.limit + 1, offset: pagination.offset });
|
|
37939
|
+
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 });
|
|
37940
|
+
},
|
|
37941
|
+
buckets() {
|
|
37942
|
+
if (!options.storageEnabled) unavailable4();
|
|
37943
|
+
return bounded({ names: [.../* @__PURE__ */ new Set([...options.buckets, ...options.nativeStorage ? [] : runtime.inspect().buckets.map((bucket) => bucket.name)])].filter(bucketName).sort().slice(0, 100) });
|
|
37944
|
+
},
|
|
37945
|
+
async objects(value) {
|
|
37946
|
+
const input = object7(value, ["bucket", "prefix", "limit", "offset"]), pagination = page(input);
|
|
37947
|
+
const name2 = requireBucket(input.bucket);
|
|
37948
|
+
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();
|
|
37949
|
+
const objects = await providerRequest(() => runtime.storage.list(name2, input.prefix));
|
|
37950
|
+
if (objects.length > 1e3) throw new Error("local_inspection_too_large");
|
|
37951
|
+
objects.sort((first, second) => first.key.localeCompare(second.key));
|
|
37952
|
+
return bounded({ objects: objects.slice(pagination.offset, pagination.offset + pagination.limit), ...pagination, nextOffset: objects.length > pagination.offset + pagination.limit ? pagination.offset + pagination.limit : null });
|
|
37953
|
+
},
|
|
37954
|
+
async preview(value) {
|
|
37955
|
+
const input = object7(value, ["bucket", "key"]), name2 = requireBucket(input.bucket);
|
|
37956
|
+
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();
|
|
37957
|
+
if (!options.nativeStorage && !await runtime.storage.exists(name2, input.key)) throw new Error("local_inspection_not_found");
|
|
37958
|
+
const bytes = await providerRequest(() => runtime.storage.download(name2, input.key), true);
|
|
37959
|
+
if (bytes.byteLength > 16384) return { kind: "too-large", size: bytes.byteLength, maximumPreviewBytes: 16384 };
|
|
37960
|
+
try {
|
|
37961
|
+
const text3 = new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
37962
|
+
if (text3.includes("\0")) throw new Error("Binary object");
|
|
37963
|
+
return bounded({ kind: "text", size: bytes.byteLength, text: text3 });
|
|
37964
|
+
} catch (error2) {
|
|
37965
|
+
if (error2 instanceof Error && error2.message === "local_inspection_too_large") throw error2;
|
|
37966
|
+
return { kind: "binary", size: bytes.byteLength, bytes: [...bytes.slice(0, 64)], truncated: bytes.byteLength > 64 };
|
|
37967
|
+
}
|
|
37968
|
+
}
|
|
37969
|
+
};
|
|
37970
|
+
}
|
|
37971
|
+
|
|
37972
|
+
// src/local-dashboard.ts
|
|
37973
|
+
var dashboardHtml = String.raw`<!doctype html>
|
|
37974
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Backify Local</title>
|
|
37975
|
+
<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>
|
|
37976
|
+
<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>
|
|
37977
|
+
<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>
|
|
37978
|
+
<p id="message" role="status" aria-live="polite">Open this dashboard using backify dev --open to authenticate.</p>
|
|
37979
|
+
<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>
|
|
37980
|
+
<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>
|
|
37981
|
+
<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>
|
|
37982
|
+
<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>
|
|
37983
|
+
<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>
|
|
37984
|
+
<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>
|
|
37985
|
+
<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>
|
|
37986
|
+
<script>
|
|
37987
|
+
const token=new URLSearchParams(location.hash.slice(1)).get("session");
|
|
37988
|
+
history.replaceState(null,"",location.pathname);
|
|
37989
|
+
const element=id=>document.getElementById(id);
|
|
37990
|
+
let rowPage=null,objectPage=null,rowTable="",objectBucket="",objectPrefix="",jobsBusy=false,jobView={jobs:[],schedules:[],runs:[]};
|
|
37991
|
+
const jobActions=["run-job","pause-schedule","resume-schedule","retry-run","cancel-run"];
|
|
37992
|
+
function show(id,value){element(id).textContent=JSON.stringify(value,null,2)}
|
|
37993
|
+
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)}}
|
|
37994
|
+
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}
|
|
37995
|
+
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}}}
|
|
37996
|
+
async function status(){show("state",await request("/v1/status"))}
|
|
37997
|
+
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}
|
|
37998
|
+
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=""}
|
|
37999
|
+
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}
|
|
38000
|
+
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}
|
|
38001
|
+
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()}
|
|
38002
|
+
element("schedule-id").onchange=jobControls;element("run-id").onchange=jobControls;
|
|
38003
|
+
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}}
|
|
38004
|
+
action("refresh",status);
|
|
38005
|
+
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});
|
|
38006
|
+
action("load-rows",()=>rows(0));
|
|
38007
|
+
action("next-rows",()=>{if(rowPage===null||rowTable!==element("tables").value)throw new Error("Reload rows after changing the table.");return rows(rowPage)});
|
|
38008
|
+
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});
|
|
38009
|
+
action("load-objects",()=>objects(0));
|
|
38010
|
+
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)});
|
|
38011
|
+
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}))});
|
|
38012
|
+
action("load-jobs",jobs);
|
|
38013
|
+
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()});
|
|
38014
|
+
action("pause-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:false});await jobs()});
|
|
38015
|
+
action("resume-schedule",async()=>{await request("/v1/schedules/enabled",{id:element("schedule-id").value,enabled:true});await jobs()});
|
|
38016
|
+
action("retry-run",async()=>{await request("/v1/jobs/retry",{id:element("run-id").value});await jobs()});
|
|
38017
|
+
action("cancel-run",async()=>{await request("/v1/jobs/cancel",{id:element("run-id").value});await jobs()});
|
|
38018
|
+
action("load-logs",async()=>show("log-state",await request("/v1/logs")));
|
|
38019
|
+
action("load-events",async()=>show("event-state",await request("/v1/events")));
|
|
38020
|
+
if(token)status().then(()=>{element("message").textContent="Local session connected."}).catch(error=>{element("message").textContent=error.message});
|
|
38021
|
+
</script></body></html>`;
|
|
38022
|
+
|
|
38023
|
+
// src/local-native-events.ts
|
|
38024
|
+
function createLocalNativeEvents(local, native) {
|
|
38025
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
38026
|
+
const validateName2 = (name2) => {
|
|
38027
|
+
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");
|
|
38028
|
+
};
|
|
38029
|
+
return {
|
|
38030
|
+
track: (name2, data, options) => {
|
|
38031
|
+
if (!local.track) throw new Error("Upgrade the local SDK to enable event tracking");
|
|
38032
|
+
return local.track(name2, data, options);
|
|
38033
|
+
},
|
|
38034
|
+
async emit(name2, payload, options) {
|
|
38035
|
+
validateName2(name2);
|
|
38036
|
+
if (options?.idempotencyKey !== void 0 && (typeof options.idempotencyKey !== "string" || !options.idempotencyKey || options.idempotencyKey.length > 128)) throw new Error("Invalid idempotency key");
|
|
38037
|
+
if (options?.idempotencyKey !== void 0 && (local.hasIdempotencyKey ? local.hasIdempotencyKey(options.idempotencyKey) : local.snapshot().deliveries.some((item) => item.idempotencyKey === options.idempotencyKey))) {
|
|
38038
|
+
await local.emit(name2, payload, options);
|
|
38039
|
+
return;
|
|
37501
38040
|
}
|
|
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);
|
|
38041
|
+
let accepted;
|
|
38042
|
+
try {
|
|
38043
|
+
accepted = JSON.parse(JSON.stringify(payload ?? null));
|
|
38044
|
+
} catch {
|
|
38045
|
+
throw new Error("Event payload must be JSON serializable");
|
|
37511
38046
|
}
|
|
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 };
|
|
38047
|
+
if (await native.emitAccepted(name2, accepted, options)) {
|
|
38048
|
+
for (const handler of handlers.get(name2) ?? []) await handler(structuredClone(accepted));
|
|
38049
|
+
}
|
|
38050
|
+
},
|
|
38051
|
+
on(name2, handler) {
|
|
38052
|
+
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");
|
|
38053
|
+
handlers.set(name2, [...handlers.get(name2) ?? [], handler]);
|
|
38054
|
+
return () => handlers.set(name2, (handlers.get(name2) ?? []).filter((value) => value !== handler));
|
|
38055
|
+
},
|
|
38056
|
+
async receive(name2, options) {
|
|
38057
|
+
const retained = await local.receive(name2, options);
|
|
38058
|
+
return retained.length ? retained : native.receive(name2, options);
|
|
38059
|
+
},
|
|
38060
|
+
async complete(id, receipt, retry) {
|
|
38061
|
+
if (retry !== void 0 && typeof retry !== "boolean") throw new Error("Invalid local event retry");
|
|
38062
|
+
if (typeof id === "string" && id.startsWith("event_")) await local.complete(id, receipt, retry);
|
|
38063
|
+
else await native.complete(id, receipt, retry);
|
|
38064
|
+
},
|
|
38065
|
+
async inspect() {
|
|
38066
|
+
const retained = local.inspect(), durable = await native.inspect();
|
|
38067
|
+
const counts = { ...retained.counts };
|
|
38068
|
+
for (const status of Object.keys(counts)) {
|
|
38069
|
+
counts[status] += durable.counts[status];
|
|
38070
|
+
if (!Number.isSafeInteger(counts[status])) throw new Error("Local event inspection count exceeds bounds");
|
|
38071
|
+
}
|
|
38072
|
+
const total = Object.values(counts).reduce((sum, count) => sum + count, 0);
|
|
38073
|
+
if (!Number.isSafeInteger(total)) throw new Error("Local event inspection count exceeds bounds");
|
|
38074
|
+
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);
|
|
38075
|
+
return { version: 1, counts, deliveries, hasMore: total > deliveries.length };
|
|
37556
38076
|
}
|
|
37557
38077
|
};
|
|
37558
38078
|
}
|
|
37559
38079
|
|
|
38080
|
+
// src/local-job-executor.ts
|
|
38081
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
38082
|
+
import { createHash as createHash11 } from "node:crypto";
|
|
38083
|
+
import { lstatSync as lstatSync12, readFileSync as readFileSync16 } from "node:fs";
|
|
38084
|
+
import { isAbsolute as isAbsolute8, join as join12, relative as relative3, resolve as resolve12 } from "node:path";
|
|
38085
|
+
|
|
37560
38086
|
// ../sdk/dist/application-auth-state.js
|
|
37561
|
-
import { createHash as
|
|
37562
|
-
import { closeSync, constants, fstatSync, fsyncSync, lstatSync as
|
|
38087
|
+
import { createHash as createHash4, randomUUID as randomUUID6 } from "node:crypto";
|
|
38088
|
+
import { closeSync, constants, fstatSync, fsyncSync, lstatSync as lstatSync5, openSync, readSync, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync8 } from "node:fs";
|
|
37563
38089
|
import { dirname as dirname6, isAbsolute as isAbsolute2, parse, resolve as resolve6, sep as sep2 } from "node:path";
|
|
37564
38090
|
function unavailable2() {
|
|
37565
38091
|
throw new ApplicationAuthenticationError("application_identity_unavailable");
|
|
@@ -37572,14 +38098,14 @@ function safePath(filename2) {
|
|
|
37572
38098
|
const directory2 = dirname6(filename2);
|
|
37573
38099
|
let ancestor = directory2;
|
|
37574
38100
|
for (; ; ) {
|
|
37575
|
-
const metadata =
|
|
38101
|
+
const metadata = lstatSync5(ancestor);
|
|
37576
38102
|
if (!metadata.isDirectory() || metadata.isSymbolicLink())
|
|
37577
38103
|
unavailable2();
|
|
37578
38104
|
if (ancestor === parse(ancestor).root)
|
|
37579
38105
|
break;
|
|
37580
38106
|
ancestor = dirname6(ancestor);
|
|
37581
38107
|
}
|
|
37582
|
-
const parent =
|
|
38108
|
+
const parent = lstatSync5(directory2);
|
|
37583
38109
|
if (process.platform !== "win32" && ((parent.mode & 63) !== 0 || parent.uid !== process.getuid?.()))
|
|
37584
38110
|
unavailable2();
|
|
37585
38111
|
}
|
|
@@ -37598,7 +38124,7 @@ function syncDirectory(filename2) {
|
|
|
37598
38124
|
}
|
|
37599
38125
|
}
|
|
37600
38126
|
function readState(filename2) {
|
|
37601
|
-
const metadata =
|
|
38127
|
+
const metadata = lstatSync5(filename2);
|
|
37602
38128
|
safeFile(metadata);
|
|
37603
38129
|
if (metadata.size > 2048)
|
|
37604
38130
|
unavailable2();
|
|
@@ -37631,10 +38157,10 @@ function readState(filename2) {
|
|
|
37631
38157
|
}
|
|
37632
38158
|
}
|
|
37633
38159
|
function persist(filename2, state) {
|
|
37634
|
-
const temporary = filename2 + "." +
|
|
38160
|
+
const temporary = filename2 + "." + randomUUID6() + ".tmp";
|
|
37635
38161
|
const descriptor2 = openSync(temporary, "wx", 384);
|
|
37636
38162
|
try {
|
|
37637
|
-
|
|
38163
|
+
writeFileSync8(descriptor2, JSON.stringify(state));
|
|
37638
38164
|
fsyncSync(descriptor2);
|
|
37639
38165
|
} finally {
|
|
37640
38166
|
closeSync(descriptor2);
|
|
@@ -37649,12 +38175,12 @@ function checkpoint(filename2, trust, initialize2) {
|
|
|
37649
38175
|
filename2 = resolve6(filename2);
|
|
37650
38176
|
safePath(filename2);
|
|
37651
38177
|
const lock = filename2 + ".lock";
|
|
37652
|
-
const next = { version: 1, scope: trust.scope, revision: trust.revision, digest:
|
|
38178
|
+
const next = { version: 1, scope: trust.scope, revision: trust.revision, digest: createHash4("sha256").update(trust.content).digest("hex") };
|
|
37653
38179
|
if (!initialize2) {
|
|
37654
38180
|
const previous = readState(filename2);
|
|
37655
38181
|
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
38182
|
try {
|
|
37657
|
-
|
|
38183
|
+
lstatSync5(lock);
|
|
37658
38184
|
} catch (error2) {
|
|
37659
38185
|
if (error2.code === "ENOENT")
|
|
37660
38186
|
return;
|
|
@@ -37665,7 +38191,7 @@ function checkpoint(filename2, trust, initialize2) {
|
|
|
37665
38191
|
}
|
|
37666
38192
|
const descriptor2 = openSync(lock, "wx", 384);
|
|
37667
38193
|
try {
|
|
37668
|
-
|
|
38194
|
+
writeFileSync8(descriptor2, "backify-application-auth-state-v1");
|
|
37669
38195
|
fsyncSync(descriptor2);
|
|
37670
38196
|
} finally {
|
|
37671
38197
|
closeSync(descriptor2);
|
|
@@ -37675,7 +38201,7 @@ function checkpoint(filename2, trust, initialize2) {
|
|
|
37675
38201
|
try {
|
|
37676
38202
|
if (initialize2) {
|
|
37677
38203
|
try {
|
|
37678
|
-
|
|
38204
|
+
lstatSync5(filename2);
|
|
37679
38205
|
unavailable2();
|
|
37680
38206
|
} catch (error2) {
|
|
37681
38207
|
if (error2.code !== "ENOENT")
|
|
@@ -37712,8 +38238,8 @@ function createPersistentApplicationAuthProvider(source, options) {
|
|
|
37712
38238
|
}
|
|
37713
38239
|
|
|
37714
38240
|
// ../sdk/dist/application-auth-sync.js
|
|
37715
|
-
import { createHash as
|
|
37716
|
-
import { closeSync as closeSync2, constants as constants2, fsyncSync as fsyncSync2, lstatSync as
|
|
38241
|
+
import { createHash as createHash5, createPublicKey as createPublicKey2, randomUUID as randomUUID7, verify as verify2 } from "node:crypto";
|
|
38242
|
+
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
38243
|
import { dirname as dirname7, isAbsolute as isAbsolute3, parse as parse2, resolve as resolve7, sep as sep3 } from "node:path";
|
|
37718
38244
|
var maximumBytes = 512 * 1024;
|
|
37719
38245
|
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 +38278,7 @@ function prepare(options) {
|
|
|
37752
38278
|
function planApplicationAuthSynchronization(options) {
|
|
37753
38279
|
try {
|
|
37754
38280
|
const prepared = prepare(options);
|
|
37755
|
-
return { schemaVersion: 1, status: "planned", scope: structuredClone(options.expectedScope), agentId: options.agentId, endpoint: prepared.endpoint.href, managementKeySha256:
|
|
38281
|
+
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
38282
|
} catch {
|
|
37757
38283
|
return unavailable3();
|
|
37758
38284
|
}
|
|
@@ -37760,13 +38286,13 @@ function planApplicationAuthSynchronization(options) {
|
|
|
37760
38286
|
function directory(filename2, privateState) {
|
|
37761
38287
|
const parent = dirname7(filename2);
|
|
37762
38288
|
for (let ancestor = parent; ; ancestor = dirname7(ancestor)) {
|
|
37763
|
-
const metadata2 =
|
|
38289
|
+
const metadata2 = lstatSync6(ancestor);
|
|
37764
38290
|
if (!metadata2.isDirectory() || metadata2.isSymbolicLink())
|
|
37765
38291
|
unavailable3();
|
|
37766
38292
|
if (ancestor === parse2(ancestor).root)
|
|
37767
38293
|
break;
|
|
37768
38294
|
}
|
|
37769
|
-
const metadata =
|
|
38295
|
+
const metadata = lstatSync6(parent);
|
|
37770
38296
|
if (process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & (privateState ? 63 : 18)) !== 0))
|
|
37771
38297
|
unavailable3();
|
|
37772
38298
|
}
|
|
@@ -37782,10 +38308,10 @@ function syncDirectory2(filename2) {
|
|
|
37782
38308
|
}
|
|
37783
38309
|
function currentPublicFile(filename2) {
|
|
37784
38310
|
try {
|
|
37785
|
-
const metadata =
|
|
38311
|
+
const metadata = lstatSync6(filename2);
|
|
37786
38312
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072 || process.platform !== "win32" && (metadata.uid !== process.getuid?.() || (metadata.mode & 18) !== 0))
|
|
37787
38313
|
unavailable3();
|
|
37788
|
-
const bytes =
|
|
38314
|
+
const bytes = readFileSync10(filename2);
|
|
37789
38315
|
if (bytes.length > 131072)
|
|
37790
38316
|
unavailable3();
|
|
37791
38317
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
@@ -37852,7 +38378,7 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
|
|
|
37852
38378
|
const lock = prepared.stateFile + ".delivery.lock";
|
|
37853
38379
|
const descriptor2 = openSync2(lock, "wx", 384);
|
|
37854
38380
|
try {
|
|
37855
|
-
|
|
38381
|
+
writeFileSync9(descriptor2, "backify-application-auth-delivery-v1");
|
|
37856
38382
|
fsyncSync2(descriptor2);
|
|
37857
38383
|
} finally {
|
|
37858
38384
|
closeSync2(descriptor2);
|
|
@@ -37863,14 +38389,14 @@ async function synchronizeApplicationAuthTrustWithDigest(options) {
|
|
|
37863
38389
|
const current = currentPublicFile(prepared.trustFile);
|
|
37864
38390
|
createPersistentApplicationAuthProvider(trust, { expectedScope: options.expectedScope, stateFile: prepared.stateFile, now: options.now });
|
|
37865
38391
|
const content = JSON.stringify(trust);
|
|
37866
|
-
const trustDigest =
|
|
38392
|
+
const trustDigest = createHash5("sha256").update(content).digest("hex");
|
|
37867
38393
|
if (current === content)
|
|
37868
38394
|
return { status: "unchanged", revision: trust.revision, validUntil: trust.validUntil, trustDigest };
|
|
37869
38395
|
writePending = true;
|
|
37870
|
-
const temporary = prepared.trustFile + "." +
|
|
38396
|
+
const temporary = prepared.trustFile + "." + randomUUID7() + ".tmp";
|
|
37871
38397
|
const output = openSync2(temporary, "wx", process.platform === "win32" ? 384 : 292);
|
|
37872
38398
|
try {
|
|
37873
|
-
|
|
38399
|
+
writeFileSync9(output, content);
|
|
37874
38400
|
fsyncSync2(output);
|
|
37875
38401
|
} finally {
|
|
37876
38402
|
closeSync2(output);
|
|
@@ -38075,10 +38601,10 @@ function createHcrEventsProvider(options) {
|
|
|
38075
38601
|
}
|
|
38076
38602
|
if (retry !== void 0 && typeof retry !== "boolean")
|
|
38077
38603
|
throw new Error("Invalid event delivery receipt");
|
|
38078
|
-
const
|
|
38079
|
-
if (
|
|
38604
|
+
const delay3 = completeOptions?.retryDelaySeconds;
|
|
38605
|
+
if (delay3 !== void 0 && (!Number.isInteger(delay3) || delay3 < 0 || delay3 > 3600 || !retry && delay3 !== 0))
|
|
38080
38606
|
throw new Error("Invalid event retry delay");
|
|
38081
|
-
await request("/" + id + "/complete", { receipt, retry: retry ?? false, ...
|
|
38607
|
+
await request("/" + id + "/complete", { receipt, retry: retry ?? false, ...delay3 === void 0 ? {} : { retryDelaySeconds: delay3 } });
|
|
38082
38608
|
},
|
|
38083
38609
|
async renew(id, receipt) {
|
|
38084
38610
|
validateId(id);
|
|
@@ -38104,7 +38630,7 @@ var HcrJobsRequestError = class extends Error {
|
|
|
38104
38630
|
this.name = "HcrJobsRequestError";
|
|
38105
38631
|
}
|
|
38106
38632
|
};
|
|
38107
|
-
var
|
|
38633
|
+
var uuid4 = (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}$/i.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
38108
38634
|
var digest = (value) => typeof value === "string" && value.length === 64 && /^[a-f0-9]{64}$/.test(value);
|
|
38109
38635
|
var name = (value) => typeof value === "string" && value.length <= 100 && !value.includes(String.fromCharCode(10)) && !value.includes(String.fromCharCode(13)) && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,99}$/.test(value);
|
|
38110
38636
|
var timestamp = (value) => {
|
|
@@ -38240,7 +38766,7 @@ function createHcrJobsProvider(options) {
|
|
|
38240
38766
|
return value.kind === "cron" && value.at === null && value.intervalSeconds === null && typeof value.expression === "string" && value.expression.length <= 200 && value.expression.trim().split(/\s+/).length === 5 && !/[\r\n]/.test(value.expression);
|
|
38241
38767
|
}
|
|
38242
38768
|
function scheduleMetadata(value) {
|
|
38243
|
-
if (!fields2(value, ["id", "name", "job", "artifactVersion", "sourceVersion", "revision", "kind", "at", "intervalSeconds", "expression", "timeZone", "sourceEnabled", "enabledOverride", "enabled", "nextRunAt", "lastDispatchedAt"]) || !
|
|
38769
|
+
if (!fields2(value, ["id", "name", "job", "artifactVersion", "sourceVersion", "revision", "kind", "at", "intervalSeconds", "expression", "timeZone", "sourceEnabled", "enabledOverride", "enabled", "nextRunAt", "lastDispatchedAt"]) || !uuid4(value.id) || !name(value.name) || !name(value.job) || !digest(value.artifactVersion) || !integer(value.sourceVersion, 1, Number.MAX_SAFE_INTEGER) || !integer(value.revision, 1, Number.MAX_SAFE_INTEGER) || !scheduleTiming(value) || typeof value.sourceEnabled !== "boolean" || value.enabledOverride !== null && typeof value.enabledOverride !== "boolean" || value.enabled !== (value.enabledOverride ?? value.sourceEnabled) || value.nextRunAt !== null && !timestamp(value.nextRunAt) || value.lastDispatchedAt !== null && !timestamp(value.lastDispatchedAt))
|
|
38244
38770
|
invalid2();
|
|
38245
38771
|
return value;
|
|
38246
38772
|
}
|
|
@@ -38269,7 +38795,7 @@ function createHcrJobsProvider(options) {
|
|
|
38269
38795
|
},
|
|
38270
38796
|
async override(id, input) {
|
|
38271
38797
|
serverOnly();
|
|
38272
|
-
if (!
|
|
38798
|
+
if (!uuid4(id) || !fields2(input, ["expectedRevision", "enabled"]) || !integer(input.expectedRevision, 1, Number.MAX_SAFE_INTEGER - 1) || input.enabled !== null && typeof input.enabled !== "boolean")
|
|
38273
38799
|
throw new Error("Invalid durable schedule override");
|
|
38274
38800
|
const result = scheduleMetadata(await request("/schedules/" + id + "/override", input));
|
|
38275
38801
|
if (result.id.toLowerCase() !== id.toLowerCase() || result.enabledOverride !== input.enabled)
|
|
@@ -38323,13 +38849,13 @@ function createHcrJobsProvider(options) {
|
|
|
38323
38849
|
if (typeof serialized !== "string" || new TextEncoder().encode(serialized).length > 1048576)
|
|
38324
38850
|
throw new Error("Job payload exceeds its bound");
|
|
38325
38851
|
const result = await request("/enqueue", { version: 1, job, artifactVersion: producerArtifactVersion, payload: JSON.parse(serialized), delaySeconds, ...input?.retries !== void 0 ? { retries: input.retries } : {}, ...input?.idempotencyKey !== void 0 ? { idempotencyKey: input.idempotencyKey } : {} });
|
|
38326
|
-
if (!fields2(result, ["id", "accepted"]) || !
|
|
38852
|
+
if (!fields2(result, ["id", "accepted"]) || !uuid4(result.id) || typeof result.accepted !== "boolean")
|
|
38327
38853
|
invalid2();
|
|
38328
38854
|
return { id: result.id };
|
|
38329
38855
|
},
|
|
38330
38856
|
async enqueuePinned(input) {
|
|
38331
38857
|
serverOnly();
|
|
38332
|
-
if (!fields2(input, ["version", "runId", "job", "artifactVersion", "scheduledAt", "payload"]) || input.version !== 1 || !
|
|
38858
|
+
if (!fields2(input, ["version", "runId", "job", "artifactVersion", "scheduledAt", "payload"]) || input.version !== 1 || !uuid4(input.runId) || !name(input.job) || !digest(input.artifactVersion) || !timestamp(input.scheduledAt))
|
|
38333
38859
|
throw new Error("Invalid pinned job dispatch");
|
|
38334
38860
|
let payload;
|
|
38335
38861
|
try {
|
|
@@ -38353,7 +38879,7 @@ function createHcrJobsProvider(options) {
|
|
|
38353
38879
|
const identifiers = /* @__PURE__ */ new Set();
|
|
38354
38880
|
let payloadBytes = 0;
|
|
38355
38881
|
for (const row of rows) {
|
|
38356
|
-
if (!fields2(row, ["version", "runId", "job", "artifactVersion", "scheduledAt", "attempt", "payload", "receipt", "leaseExpiresAt", "deploymentId", "imageReference", "sourceCommit", "policy"]) || row.version !== 1 || !
|
|
38882
|
+
if (!fields2(row, ["version", "runId", "job", "artifactVersion", "scheduledAt", "attempt", "payload", "receipt", "leaseExpiresAt", "deploymentId", "imageReference", "sourceCommit", "policy"]) || row.version !== 1 || !uuid4(row.runId) || identifiers.has(row.runId) || row.job !== job || row.artifactVersion !== artifactVersion || !timestamp(row.scheduledAt) || !integer(row.attempt, 1, 101) || !digest(row.receipt) || !timestamp(row.leaseExpiresAt) || !uuid4(row.deploymentId) || !imageReference(row.imageReference) || typeof row.sourceCommit !== "string" || ![40, 64].includes(row.sourceCommit.length) || row.sourceCommit.includes(String.fromCharCode(10)) || row.sourceCommit.includes(String.fromCharCode(13)) || !/^[a-f0-9]+$/.test(row.sourceCommit))
|
|
38357
38883
|
invalid2();
|
|
38358
38884
|
const policy = row.policy;
|
|
38359
38885
|
if (!fields2(policy, ["name", "retries", "timeoutSeconds", "concurrency", "backoff"]) || policy.name !== job || !integer(policy.retries, 0, 100) || !integer(policy.timeoutSeconds, 1, 86400) || !integer(policy.concurrency, 1, 100) || !["fixed", "exponential"].includes(policy.backoff) || row.attempt > policy.retries + 1)
|
|
@@ -38369,28 +38895,28 @@ function createHcrJobsProvider(options) {
|
|
|
38369
38895
|
return rows;
|
|
38370
38896
|
},
|
|
38371
38897
|
async complete(id, receipt, outcome) {
|
|
38372
|
-
if (!
|
|
38898
|
+
if (!uuid4(id) || !digest(receipt) || !["succeeded", "failed", "timed_out", "cancelled"].includes(outcome))
|
|
38373
38899
|
throw new Error("Invalid job receipt or outcome");
|
|
38374
38900
|
if (await request("/" + id + "/complete", { receipt, outcome }, "post", 131072, true) !== null)
|
|
38375
38901
|
invalid2();
|
|
38376
38902
|
},
|
|
38377
38903
|
async cancelPending(id) {
|
|
38378
|
-
if (!
|
|
38904
|
+
if (!uuid4(id))
|
|
38379
38905
|
throw new Error("Invalid job identifier");
|
|
38380
38906
|
if (await request("/" + id + "/cancel", void 0, "empty", 131072, true) !== null)
|
|
38381
38907
|
invalid2();
|
|
38382
38908
|
},
|
|
38383
38909
|
async retryFailed(id, artifactVersion) {
|
|
38384
38910
|
serverOnly();
|
|
38385
|
-
if (!
|
|
38911
|
+
if (!uuid4(id) || !digest(artifactVersion))
|
|
38386
38912
|
throw new Error("Invalid reviewed job retry");
|
|
38387
38913
|
const result = await request("/" + id + "/retry", { version: 1, artifactVersion });
|
|
38388
|
-
if (!fields2(result, ["id", "accepted"]) || !
|
|
38914
|
+
if (!fields2(result, ["id", "accepted"]) || !uuid4(result.id) || result.id.toLowerCase() === id.toLowerCase() || typeof result.accepted !== "boolean")
|
|
38389
38915
|
invalid2();
|
|
38390
38916
|
return { id: result.id, accepted: result.accepted };
|
|
38391
38917
|
},
|
|
38392
38918
|
async attempts(id) {
|
|
38393
|
-
if (!
|
|
38919
|
+
if (!uuid4(id))
|
|
38394
38920
|
throw new Error("Invalid job identifier");
|
|
38395
38921
|
const rows = await request("/" + id + "/attempts", void 0, "get");
|
|
38396
38922
|
if (!Array.isArray(rows) || rows.length > 101)
|
|
@@ -38409,7 +38935,7 @@ function createHcrJobsProvider(options) {
|
|
|
38409
38935
|
invalid2();
|
|
38410
38936
|
const identifiers = /* @__PURE__ */ new Set();
|
|
38411
38937
|
for (const row of value.runs) {
|
|
38412
|
-
if (!fields2(row, ["runId", "job", "artifactVersion", "deploymentId", "status", "attempts", "scheduledAt", "createdAt", "leaseExpiresAt", "finishedAt", "errorCode"]) || !
|
|
38938
|
+
if (!fields2(row, ["runId", "job", "artifactVersion", "deploymentId", "status", "attempts", "scheduledAt", "createdAt", "leaseExpiresAt", "finishedAt", "errorCode"]) || !uuid4(row.runId) || identifiers.has(row.runId) || !name(row.job) || !digest(row.artifactVersion) || !uuid4(row.deploymentId) || !Object.hasOwn(value.counts, row.status) || !integer(row.attempts, 0, 101) || !timestamp(row.scheduledAt) || !timestamp(row.createdAt) || row.leaseExpiresAt !== null && !timestamp(row.leaseExpiresAt) || row.finishedAt !== null && !timestamp(row.finishedAt) || !errorCode(row.errorCode))
|
|
38413
38939
|
invalid2();
|
|
38414
38940
|
identifiers.add(row.runId);
|
|
38415
38941
|
}
|
|
@@ -38481,10 +39007,10 @@ function jsonValue(value) {
|
|
|
38481
39007
|
|
|
38482
39008
|
// src/local-services.ts
|
|
38483
39009
|
import { spawn, execFile } from "node:child_process";
|
|
38484
|
-
import { createHash as
|
|
39010
|
+
import { createHash as createHash7, generateKeyPairSync, randomBytes as randomBytes4, randomUUID as randomUUID9, sign } from "node:crypto";
|
|
38485
39011
|
import { createServer as createServer3 } from "node:net";
|
|
38486
|
-
import { existsSync as
|
|
38487
|
-
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as
|
|
39012
|
+
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";
|
|
39013
|
+
import { basename as basename2, dirname as dirname9, isAbsolute as isAbsolute4, join as join11, relative, resolve as resolve8 } from "node:path";
|
|
38488
39014
|
|
|
38489
39015
|
// src/local-typed-migrations.ts
|
|
38490
39016
|
var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
@@ -38531,17 +39057,17 @@ function typedMigrationSql(source) {
|
|
|
38531
39057
|
}
|
|
38532
39058
|
|
|
38533
39059
|
// src/local-job-services.ts
|
|
38534
|
-
import { createHash as
|
|
38535
|
-
import { existsSync as
|
|
39060
|
+
import { createHash as createHash6, randomBytes as randomBytes3, randomUUID as randomUUID8 } from "node:crypto";
|
|
39061
|
+
import { existsSync as existsSync10, lstatSync as lstatSync7, readFileSync as readFileSync11 } from "node:fs";
|
|
38536
39062
|
import { isIP } from "node:net";
|
|
38537
|
-
import { dirname as dirname8, join as
|
|
39063
|
+
import { dirname as dirname8, join as join10 } from "node:path";
|
|
38538
39064
|
function fields3(value, names) {
|
|
38539
39065
|
return !!value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === names.length && names.every((name2) => Object.hasOwn(value, name2));
|
|
38540
39066
|
}
|
|
38541
39067
|
function digest2(value) {
|
|
38542
39068
|
return typeof value === "string" && value.length === 64 && /^[a-f0-9]{64}$/.test(value);
|
|
38543
39069
|
}
|
|
38544
|
-
function
|
|
39070
|
+
function uuid5(value) {
|
|
38545
39071
|
return 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}$/i.test(value) && value !== "00000000-0000-0000-0000-000000000000";
|
|
38546
39072
|
}
|
|
38547
39073
|
function integer2(value, minimum, maximum) {
|
|
@@ -38562,7 +39088,7 @@ function image(value) {
|
|
|
38562
39088
|
function validateLocalJobArtifacts(value) {
|
|
38563
39089
|
if (!Array.isArray(value) || !integer2(value.length, 1, 100)) throw new Error("Local jobs require bounded reviewed artifact pins and policies");
|
|
38564
39090
|
const result = value.map((artifact) => {
|
|
38565
|
-
if (!fields3(artifact, ["deploymentId", "artifactVersion", "imageReference", "sourceCommit", "jobs"]) || !
|
|
39091
|
+
if (!fields3(artifact, ["deploymentId", "artifactVersion", "imageReference", "sourceCommit", "jobs"]) || !uuid5(artifact.deploymentId) || !digest2(artifact.artifactVersion) || !image(artifact.imageReference) || typeof artifact.sourceCommit !== "string" || ![40, 64].includes(artifact.sourceCommit.length) || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(artifact.sourceCommit) || !Array.isArray(artifact.jobs) || !integer2(artifact.jobs.length, 1, 100)) throw new Error("Local jobs require bounded reviewed artifact pins and policies");
|
|
38566
39092
|
const jobs = artifact.jobs.map((policy) => {
|
|
38567
39093
|
if (!fields3(policy, ["name", "retries", "timeoutSeconds", "concurrency", "backoff"]) || typeof policy.name !== "string" || !integer2(policy.name.length, 1, 100) || /[\r\n]/.test(policy.name) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(policy.name) || !integer2(policy.retries, 0, 100) || !integer2(policy.timeoutSeconds, 1, 86400) || !integer2(policy.concurrency, 1, 100) || !["fixed", "exponential"].includes(policy.backoff)) throw new Error("Local jobs require bounded reviewed artifact pins and policies");
|
|
38568
39094
|
return { name: policy.name, retries: policy.retries, timeoutSeconds: policy.timeoutSeconds, concurrency: policy.concurrency, backoff: policy.backoff };
|
|
@@ -38574,7 +39100,7 @@ function validateLocalJobArtifacts(value) {
|
|
|
38574
39100
|
return result.sort((first, second) => first.artifactVersion < second.artifactVersion ? -1 : first.artifactVersion > second.artifactVersion ? 1 : 0);
|
|
38575
39101
|
}
|
|
38576
39102
|
function validLocalJobState(value, otherIds) {
|
|
38577
|
-
if (!fields3(value, ["id", "password", "schemaDigests", "initialized", "artifacts"]) || !
|
|
39103
|
+
if (!fields3(value, ["id", "password", "schemaDigests", "initialized", "artifacts"]) || !uuid5(value.id) || otherIds.some((identifier3) => identifier3.toLowerCase() === value.id.toLowerCase()) || !digest2(value.password) || !fields3(value.schemaDigests, ["base", "producer"]) || !digest2(value.schemaDigests.base) || !digest2(value.schemaDigests.producer) || typeof value.initialized !== "boolean") return false;
|
|
38578
39104
|
try {
|
|
38579
39105
|
validateLocalJobArtifacts(value.artifacts);
|
|
38580
39106
|
return true;
|
|
@@ -38585,12 +39111,12 @@ function validLocalJobState(value, otherIds) {
|
|
|
38585
39111
|
function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
|
|
38586
39112
|
const requested = validateLocalJobArtifacts(artifacts);
|
|
38587
39113
|
const readSchema = (name2) => {
|
|
38588
|
-
const filename2 =
|
|
39114
|
+
const filename2 = join10(dirname8(hcrPath), "sql", name2), info = existsSync10(filename2) ? lstatSync7(filename2) : void 0;
|
|
38589
39115
|
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
|
|
39116
|
+
return readFileSync11(filename2, "utf8");
|
|
38591
39117
|
};
|
|
38592
39118
|
const base = readSchema("jobs-v1.sql"), producer = readSchema("jobs-producer-v1.sql");
|
|
38593
|
-
const schemaDigests = { base:
|
|
39119
|
+
const schemaDigests = { base: createHash6("sha256").update(base).digest("hex"), producer: createHash6("sha256").update(producer).digest("hex") };
|
|
38594
39120
|
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
39121
|
if (!retained?.initialized && !applyMigrations) throw new Error("Review both HCR job SQL assets and pass --apply-migrations for explicit native job schema approval");
|
|
38596
39122
|
const retainedArtifacts = retained ? validateLocalJobArtifacts(retained.artifacts) : [];
|
|
@@ -38599,20 +39125,20 @@ function prepareLocalJobService(hcrPath, retained, artifacts, applyMigrations) {
|
|
|
38599
39125
|
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
39126
|
if (!previous) retainedArtifacts.push(artifact);
|
|
38601
39127
|
}
|
|
38602
|
-
const state = { ...retained ?? { id:
|
|
39128
|
+
const state = { ...retained ?? { id: randomUUID8(), password: randomBytes3(32).toString("hex"), initialized: false }, schemaDigests, artifacts: validateLocalJobArtifacts(retainedArtifacts) };
|
|
38603
39129
|
return { state, base, producer };
|
|
38604
39130
|
}
|
|
38605
39131
|
|
|
38606
39132
|
// src/local-services.ts
|
|
38607
39133
|
function writePrivate(filename2, value) {
|
|
38608
39134
|
if (isLink(filename2)) throw new Error("Local service files must not be symbolic links");
|
|
38609
|
-
const temporary = filename2 + "." +
|
|
38610
|
-
|
|
39135
|
+
const temporary = filename2 + "." + randomUUID9() + ".tmp";
|
|
39136
|
+
writeFileSync10(temporary, value, { flag: "wx", mode: 384 });
|
|
38611
39137
|
renameLocalFile(temporary, filename2);
|
|
38612
39138
|
}
|
|
38613
39139
|
function isLink(filename2) {
|
|
38614
39140
|
try {
|
|
38615
|
-
return
|
|
39141
|
+
return lstatSync8(filename2).isSymbolicLink();
|
|
38616
39142
|
} catch (error2) {
|
|
38617
39143
|
if (error2.code === "ENOENT") return false;
|
|
38618
39144
|
throw error2;
|
|
@@ -38627,23 +39153,23 @@ function assertLocalStatePath(root, filename2) {
|
|
|
38627
39153
|
}
|
|
38628
39154
|
}
|
|
38629
39155
|
function stateValid(value) {
|
|
38630
|
-
const
|
|
39156
|
+
const uuid7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
38631
39157
|
if (value?.jobs !== void 0 && !validLocalJobState(value.jobs, [value.databaseId, value.storageId, ...Object.values(value.storageBindings ?? {}), ...value.events ? [value.events.id] : []].filter((identifier3) => typeof identifier3 === "string"))) return false;
|
|
38632
|
-
if (value?.events !== void 0 && (!value.events || typeof value.events !== "object" || Array.isArray(value.events) || typeof value.events.id !== "string" || value.events.id.length !== 36 || !
|
|
38633
|
-
return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier3) => typeof identifier3 === "string" &&
|
|
39158
|
+
if (value?.events !== void 0 && (!value.events || typeof value.events !== "object" || Array.isArray(value.events) || typeof value.events.id !== "string" || value.events.id.length !== 36 || !uuid7.test(value.events.id) || value.events.id === "00000000-0000-0000-0000-000000000000" || [value.databaseId, value.storageId, ...Object.values(value.storageBindings ?? {})].some((identifier3) => typeof identifier3 === "string" && identifier3.toLowerCase() === value.events.id.toLowerCase()) || typeof value.events.password !== "string" || value.events.password.length !== 64 || !/^[a-f0-9]{64}$/.test(value.events.password) || typeof value.events.schemaDigest !== "string" || value.events.schemaDigest.length !== 64 || !/^[a-f0-9]{64}$/.test(value.events.schemaDigest) || typeof value.events.initialized !== "boolean")) return false;
|
|
39159
|
+
return value?.version === 1 && value.scope && [value.scope.organizationId, value.scope.applicationId, value.scope.environmentId, value.databaseId, value.storageId].every((identifier3) => typeof identifier3 === "string" && uuid7.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
39160
|
}
|
|
38635
39161
|
function acquireLocalLease(root, relativePath2 = ".backify/dev/development.lock") {
|
|
38636
|
-
const filename2 =
|
|
39162
|
+
const filename2 = join11(root, relativePath2);
|
|
38637
39163
|
assertLocalStatePath(root, filename2);
|
|
38638
39164
|
mkdirSync4(resolve8(filename2, ".."), { recursive: true, mode: 448 });
|
|
38639
|
-
const owner = JSON.stringify({ version: 1, pid: process.pid, id:
|
|
39165
|
+
const owner = JSON.stringify({ version: 1, pid: process.pid, id: randomUUID9() });
|
|
38640
39166
|
try {
|
|
38641
|
-
|
|
39167
|
+
writeFileSync10(filename2, owner, { flag: "wx", mode: 384 });
|
|
38642
39168
|
} catch {
|
|
38643
39169
|
throw new Error("Local development already owns this repository, or a stale lifecycle lock requires explicit recovery");
|
|
38644
39170
|
}
|
|
38645
39171
|
return () => {
|
|
38646
|
-
if (
|
|
39172
|
+
if (existsSync11(filename2) && readFileSync12(filename2, "utf8") === owner) unlinkSync4(filename2);
|
|
38647
39173
|
};
|
|
38648
39174
|
}
|
|
38649
39175
|
async function allocateLocalPort(requested) {
|
|
@@ -38686,42 +39212,42 @@ function command(executable, args2, options = {}) {
|
|
|
38686
39212
|
});
|
|
38687
39213
|
}
|
|
38688
39214
|
function postgresExecutable(name2, bin) {
|
|
38689
|
-
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ?
|
|
38690
|
-
return directory2 ?
|
|
39215
|
+
const directory2 = bin ?? process.env.BACKIFY_LOCAL_POSTGRES_BIN ?? (process.platform === "win32" ? join11(process.env.ProgramFiles ?? "C:/Program Files", "PostgreSQL", "17", "bin") : void 0);
|
|
39216
|
+
return directory2 ? join11(directory2, name2 + (process.platform === "win32" ? ".exe" : "")) : name2;
|
|
38691
39217
|
}
|
|
38692
39218
|
function localMigrationFiles(root, directory2) {
|
|
38693
|
-
const typed =
|
|
39219
|
+
const typed = join11(root, "backify.migrations.json");
|
|
38694
39220
|
if (directory2 === void 0) {
|
|
38695
|
-
if (!
|
|
39221
|
+
if (!existsSync11(typed) && !lstatIfPresent(typed)) return [];
|
|
38696
39222
|
assertLocalStatePath(root, typed);
|
|
38697
|
-
const info =
|
|
39223
|
+
const info = lstatSync8(typed);
|
|
38698
39224
|
if (!info.isFile() || info.size > 1024 * 1024) throw new Error("Typed migration manifest must be a file at most 1 MiB");
|
|
38699
|
-
return typedMigrationSql(
|
|
39225
|
+
return typedMigrationSql(readFileSync12(typed, "utf8")).map((migration) => ({ ...migration, digest: createHash7("sha256").update(migration.sql).digest("hex") }));
|
|
38700
39226
|
}
|
|
38701
|
-
if (
|
|
39227
|
+
if (existsSync11(typed) || lstatIfPresent(typed)) throw new Error("Use either declared SQL migrations or the typed manifest, not both");
|
|
38702
39228
|
if (typeof directory2 !== "string") throw new Error("Local migrations require a repository-relative directory");
|
|
38703
39229
|
const folder = resolve8(root, directory2);
|
|
38704
39230
|
assertLocalStatePath(root, folder);
|
|
38705
|
-
if (!
|
|
39231
|
+
if (!existsSync11(folder)) throw new Error("Declared migration directory does not exist");
|
|
38706
39232
|
const entries2 = readdirSync5(folder);
|
|
38707
39233
|
const filenames = entries2.filter((entry) => entry.endsWith(".sql")).sort();
|
|
38708
39234
|
if (filenames.length > 100 || entries2.some((entry) => !entry.endsWith(".sql"))) throw new Error("Migrations require at most 100 flat .sql files");
|
|
38709
39235
|
let total = 0;
|
|
38710
39236
|
return filenames.map((name2) => {
|
|
38711
39237
|
if (!/^[A-Za-z0-9_.-]{1,150}\.sql$/.test(name2)) throw new Error("Invalid migration filename");
|
|
38712
|
-
const filename2 =
|
|
39238
|
+
const filename2 = join11(folder, name2);
|
|
38713
39239
|
assertLocalStatePath(root, filename2);
|
|
38714
|
-
const info =
|
|
39240
|
+
const info = lstatSync8(filename2);
|
|
38715
39241
|
if (!info.isFile() || info.size > 1024 * 1024 || (total += info.size) > 4 * 1024 * 1024) throw new Error("Migration SQL exceeds supported limits");
|
|
38716
|
-
const sql =
|
|
39242
|
+
const sql = readFileSync12(filename2, "utf8");
|
|
38717
39243
|
if (!sql.trim()) throw new Error("Migration SQL must not be empty");
|
|
38718
39244
|
validateLocalMigrationSql(sql);
|
|
38719
|
-
return { name: name2, digest:
|
|
39245
|
+
return { name: name2, digest: createHash7("sha256").update(sql).digest("hex"), sql };
|
|
38720
39246
|
});
|
|
38721
39247
|
}
|
|
38722
39248
|
function lstatIfPresent(filename2) {
|
|
38723
39249
|
try {
|
|
38724
|
-
return
|
|
39250
|
+
return lstatSync8(filename2);
|
|
38725
39251
|
} catch (error2) {
|
|
38726
39252
|
if (error2 instanceof Error && "code" in error2 && error2.code === "ENOENT") return void 0;
|
|
38727
39253
|
throw error2;
|
|
@@ -38798,19 +39324,19 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38798
39324
|
const reviewedScope = options.jobIdentityScope;
|
|
38799
39325
|
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
39326
|
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 =
|
|
39327
|
+
const hcrPath = resolve8(options.hcrPath ?? process.env.BACKIFY_LOCAL_HCR_PATH ?? installed?.path ?? join11(root, "apps/hcr/bin/Debug/net9.0/Backify.Hcr.dll"));
|
|
39328
|
+
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");
|
|
39329
|
+
const directory2 = join11(root, ".backify", "dev", "services");
|
|
38804
39330
|
assertLocalStatePath(root, directory2);
|
|
38805
39331
|
mkdirSync4(directory2, { recursive: true, mode: 448 });
|
|
38806
39332
|
assertLocalStatePath(root, directory2);
|
|
38807
|
-
const statePath =
|
|
39333
|
+
const statePath = join11(directory2, "host.json");
|
|
38808
39334
|
assertLocalStatePath(root, statePath);
|
|
38809
39335
|
let existing;
|
|
38810
|
-
if (
|
|
38811
|
-
if (
|
|
39336
|
+
if (existsSync11(statePath)) {
|
|
39337
|
+
if (lstatSync8(statePath).size > 16384) throw new Error("Local ownership state exceeds supported limits");
|
|
38812
39338
|
try {
|
|
38813
|
-
existing = JSON.parse(
|
|
39339
|
+
existing = JSON.parse(readFileSync12(statePath, "utf8"));
|
|
38814
39340
|
} catch {
|
|
38815
39341
|
throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
|
|
38816
39342
|
}
|
|
@@ -38818,31 +39344,31 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38818
39344
|
}
|
|
38819
39345
|
const state = existing ?? {
|
|
38820
39346
|
version: 1,
|
|
38821
|
-
scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId:
|
|
38822
|
-
databaseId:
|
|
38823
|
-
storageId:
|
|
39347
|
+
scope: reviewedScope ? structuredClone(reviewedScope) : { organizationId: randomUUID9(), applicationId: randomUUID9(), environmentId: randomUUID9() },
|
|
39348
|
+
databaseId: randomUUID9(),
|
|
39349
|
+
storageId: randomUUID9(),
|
|
38824
39350
|
configurationVersion: 0,
|
|
38825
|
-
adminPassword:
|
|
38826
|
-
databasePassword:
|
|
39351
|
+
adminPassword: randomBytes4(32).toString("hex"),
|
|
39352
|
+
databasePassword: randomBytes4(32).toString("hex")
|
|
38827
39353
|
};
|
|
38828
39354
|
if (!stateValid(state)) throw new Error("Invalid local service ownership state; preserve the data and repair explicitly");
|
|
38829
39355
|
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
39356
|
let eventSchema;
|
|
38831
39357
|
if (events) {
|
|
38832
|
-
const filename2 =
|
|
38833
|
-
if (!
|
|
38834
|
-
eventSchema =
|
|
38835
|
-
const digest4 =
|
|
39358
|
+
const filename2 = join11(dirname9(hcrPath), "sql", "events-v1.sql");
|
|
39359
|
+
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.");
|
|
39360
|
+
eventSchema = readFileSync12(filename2, "utf8");
|
|
39361
|
+
const digest4 = createHash7("sha256").update(eventSchema).digest("hex");
|
|
38836
39362
|
if (state.events && state.events.schemaDigest !== digest4) throw new Error("Native event schema changed; preserve its database and plan an explicit migration.");
|
|
38837
39363
|
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:
|
|
39364
|
+
state.events ??= { id: randomUUID9(), password: randomBytes4(32).toString("hex"), schemaDigest: digest4, initialized: false };
|
|
38839
39365
|
}
|
|
38840
39366
|
const jobSchema = jobs ? prepareLocalJobService(hcrPath, state.jobs, options.jobArtifacts, options.applyMigrations) : void 0;
|
|
38841
39367
|
if (jobSchema) state.jobs = jobSchema.state;
|
|
38842
39368
|
const storageNames = manifest.capabilities.storage?.buckets === void 0 ? ["default"] : manifest.capabilities.storage.buckets.map((bucket) => bucket.name);
|
|
38843
39369
|
state.storageBindings ??= { default: state.storageId };
|
|
38844
39370
|
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] ??=
|
|
39371
|
+
for (const name2 of storageNames) state.storageBindings[name2] ??= randomUUID9();
|
|
38846
39372
|
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
39373
|
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
39374
|
const migrations = database ? localMigrationFiles(root, manifest.capabilities.database?.migrations) : [];
|
|
@@ -38850,7 +39376,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38850
39376
|
const databasePort = database || events || jobs ? await allocateLocalPort(options.databasePort) : void 0;
|
|
38851
39377
|
if (databasePort !== void 0) state.retainedDatabasePort = databasePort;
|
|
38852
39378
|
if (databasePort === hcrPort) throw new Error("HCR and PostgreSQL require separate ports");
|
|
38853
|
-
const cluster =
|
|
39379
|
+
const cluster = join11(directory2, "postgres");
|
|
38854
39380
|
assertLocalStatePath(root, cluster);
|
|
38855
39381
|
const release2 = acquireLocalLease(root, ".backify/dev/services/lifecycle.lock");
|
|
38856
39382
|
let postgresStarted = false;
|
|
@@ -38866,7 +39392,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38866
39392
|
}
|
|
38867
39393
|
};
|
|
38868
39394
|
const runtimeUrl = "http://127.0.0.1:" + hcrPort;
|
|
38869
|
-
const tokenPath =
|
|
39395
|
+
const tokenPath = join11(directory2, "workload-token");
|
|
38870
39396
|
const stop = () => stopping ??= (async () => {
|
|
38871
39397
|
if (timer) clearInterval(timer);
|
|
38872
39398
|
if (snapshotTimer) clearInterval(snapshotTimer);
|
|
@@ -38885,9 +39411,9 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38885
39411
|
}
|
|
38886
39412
|
notify("hcr", "stopped");
|
|
38887
39413
|
try {
|
|
38888
|
-
if (postgresStarted &&
|
|
39414
|
+
if (postgresStarted && existsSync11(join11(cluster, "postmaster.pid"))) await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-m", "fast", "-w", "stop"]);
|
|
38889
39415
|
if (postgresStarted) notify("postgres", "stopped");
|
|
38890
|
-
if (
|
|
39416
|
+
if (existsSync11(tokenPath)) unlinkSync4(tokenPath);
|
|
38891
39417
|
} finally {
|
|
38892
39418
|
release2();
|
|
38893
39419
|
}
|
|
@@ -38897,28 +39423,28 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38897
39423
|
writePrivate(statePath, JSON.stringify(state));
|
|
38898
39424
|
if (database || events || jobs) {
|
|
38899
39425
|
notify("postgres", "starting");
|
|
38900
|
-
if (!
|
|
38901
|
-
const passwordPath =
|
|
39426
|
+
if (!existsSync11(join11(cluster, "PG_VERSION"))) {
|
|
39427
|
+
const passwordPath = join11(directory2, "init-password");
|
|
38902
39428
|
writePrivate(passwordPath, state.adminPassword);
|
|
38903
39429
|
try {
|
|
38904
39430
|
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
39431
|
} finally {
|
|
38906
|
-
if (
|
|
39432
|
+
if (existsSync11(passwordPath)) unlinkSync4(passwordPath);
|
|
38907
39433
|
}
|
|
38908
39434
|
}
|
|
38909
|
-
if (
|
|
39435
|
+
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
39436
|
postgresStarted = true;
|
|
38911
|
-
await command(postgresExecutable("pg_ctl", options.postgresBin), ["-D", cluster, "-l",
|
|
39437
|
+
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
39438
|
notify("postgres", "ready");
|
|
38913
39439
|
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
39440
|
if (database) {
|
|
38915
39441
|
if ((await sql("SELECT count(*) FROM pg_roles WHERE rolname='backify_local'")).trim() === "0") {
|
|
38916
|
-
const filename2 =
|
|
39442
|
+
const filename2 = join11(directory2, "role-" + randomUUID9() + ".sql");
|
|
38917
39443
|
writePrivate(filename2, "CREATE ROLE backify_local LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + state.databasePassword + "';");
|
|
38918
39444
|
try {
|
|
38919
39445
|
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
39446
|
} finally {
|
|
38921
|
-
if (
|
|
39447
|
+
if (existsSync11(filename2)) unlinkSync4(filename2);
|
|
38922
39448
|
}
|
|
38923
39449
|
}
|
|
38924
39450
|
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 +39459,12 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38933
39459
|
notify("migrations", "starting");
|
|
38934
39460
|
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
39461
|
for (const migration of pending) {
|
|
38936
|
-
const filename2 =
|
|
39462
|
+
const filename2 = join11(directory2, "apply-" + randomUUID9() + ".sql");
|
|
38937
39463
|
writePrivate(filename2, "BEGIN;\n" + migration.sql + "\n;\nINSERT INTO public.__backify_migrations(name,digest) VALUES ('" + migration.name + "','" + migration.digest + "');\nCOMMIT;\n");
|
|
38938
39464
|
try {
|
|
38939
39465
|
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
39466
|
} finally {
|
|
38941
|
-
if (
|
|
39467
|
+
if (existsSync11(filename2)) unlinkSync4(filename2);
|
|
38942
39468
|
}
|
|
38943
39469
|
applied.push(migration.name);
|
|
38944
39470
|
}
|
|
@@ -38949,20 +39475,20 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38949
39475
|
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
39476
|
if (!eventState.initialized) {
|
|
38951
39477
|
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 =
|
|
39478
|
+
const roleFile = join11(directory2, "event-role-" + randomUUID9() + ".sql");
|
|
38953
39479
|
writePrivate(roleFile, "CREATE ROLE backify_events LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '" + eventState.password + "';");
|
|
38954
39480
|
try {
|
|
38955
39481
|
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
39482
|
} finally {
|
|
38957
|
-
if (
|
|
39483
|
+
if (existsSync11(roleFile)) unlinkSync4(roleFile);
|
|
38958
39484
|
}
|
|
38959
39485
|
await sql("CREATE DATABASE backify_events OWNER backify_events");
|
|
38960
|
-
const schemaFile =
|
|
39486
|
+
const schemaFile = join11(directory2, "event-schema-" + randomUUID9() + ".sql");
|
|
38961
39487
|
writePrivate(schemaFile, eventSchema);
|
|
38962
39488
|
try {
|
|
38963
39489
|
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
39490
|
} finally {
|
|
38965
|
-
if (
|
|
39491
|
+
if (existsSync11(schemaFile)) unlinkSync4(schemaFile);
|
|
38966
39492
|
}
|
|
38967
39493
|
eventState.initialized = true;
|
|
38968
39494
|
writePrivate(statePath, JSON.stringify(state));
|
|
@@ -38976,21 +39502,21 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
38976
39502
|
const adminSql = (query, databaseName = "postgres") => jobCommand("backify_admin", state.adminPassword, databaseName, ["-c", query]);
|
|
38977
39503
|
if (!jobState.initialized) {
|
|
38978
39504
|
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 =
|
|
39505
|
+
const roleFile = join11(directory2, "job-role-" + randomUUID9() + ".sql");
|
|
38980
39506
|
writePrivate(roleFile, "CREATE ROLE backify_jobs LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '" + jobState.password + "';");
|
|
38981
39507
|
try {
|
|
38982
39508
|
await jobCommand("backify_admin", state.adminPassword, "postgres", ["-f", roleFile]);
|
|
38983
39509
|
} finally {
|
|
38984
|
-
if (
|
|
39510
|
+
if (existsSync11(roleFile)) unlinkSync4(roleFile);
|
|
38985
39511
|
}
|
|
38986
39512
|
await adminSql("CREATE DATABASE backify_jobs OWNER backify_admin");
|
|
38987
39513
|
for (const schema of [jobSchema.base, jobSchema.producer]) {
|
|
38988
|
-
const filename2 =
|
|
39514
|
+
const filename2 = join11(directory2, "job-schema-" + randomUUID9() + ".sql");
|
|
38989
39515
|
writePrivate(filename2, schema);
|
|
38990
39516
|
try {
|
|
38991
39517
|
await jobCommand("backify_admin", state.adminPassword, "backify_jobs", ["-f", filename2]);
|
|
38992
39518
|
} finally {
|
|
38993
|
-
if (
|
|
39519
|
+
if (existsSync11(filename2)) unlinkSync4(filename2);
|
|
38994
39520
|
}
|
|
38995
39521
|
}
|
|
38996
39522
|
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 +39545,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39019
39545
|
...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
39546
|
...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
39547
|
];
|
|
39022
|
-
const snapshotPath =
|
|
39548
|
+
const snapshotPath = join11(directory2, "snapshot.json");
|
|
39023
39549
|
const writeSnapshot = () => writePrivate(snapshotPath, JSON.stringify({ schemaVersion: 1, configurationVersion: state.configurationVersion, expiresAt: new Date(Date.now() + 7 * 864e5).toISOString(), bindings }));
|
|
39024
39550
|
const renewConfiguration = () => {
|
|
39025
39551
|
if (stopping) throw new Error("Stopped local services cannot renew configuration");
|
|
@@ -39029,15 +39555,15 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39029
39555
|
writeSnapshot();
|
|
39030
39556
|
};
|
|
39031
39557
|
writeSnapshot();
|
|
39032
|
-
const settingsPath =
|
|
39558
|
+
const settingsPath = join11(directory2, "appsettings.json");
|
|
39033
39559
|
writePrivate(settingsPath, JSON.stringify({ Hcr: {
|
|
39034
39560
|
Authentication: { PublicKeyPem: publicKey.export({ type: "spki", format: "pem" }), Issuer: "backify-local", Audience: "backify-local-hcr" },
|
|
39035
39561
|
SnapshotPath: snapshotPath,
|
|
39036
|
-
SnapshotJournalPath:
|
|
39562
|
+
SnapshotJournalPath: join11(directory2, "journal.json"),
|
|
39037
39563
|
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
39564
|
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
39565
|
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:
|
|
39566
|
+
Storage: { Bindings: Object.fromEntries(Object.entries(state.storageBindings).map(([name2, identifier3]) => [identifier3, { Scope: state.scope, ResourceReference: name2, RootPath: join11(directory2, "objects", identifier3) }])) }
|
|
39041
39567
|
} }));
|
|
39042
39568
|
issueToken();
|
|
39043
39569
|
notify("hcr", "starting");
|
|
@@ -39051,7 +39577,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39051
39577
|
while (true) {
|
|
39052
39578
|
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
39579
|
try {
|
|
39054
|
-
const response = await fetch(runtimeUrl + "/v1/health", { headers: { authorization: "Bearer " +
|
|
39580
|
+
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
39581
|
if (response.ok) {
|
|
39056
39582
|
const status = await response.json();
|
|
39057
39583
|
if (status.status === "ready" && status.configurationVersion === state.configurationVersion) break;
|
|
@@ -39060,8 +39586,8 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39060
39586
|
}
|
|
39061
39587
|
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
|
|
39062
39588
|
}
|
|
39063
|
-
if (events) await createHcrEventsProvider({ runtimeUrl, token: () =>
|
|
39064
|
-
if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () =>
|
|
39589
|
+
if (events) await createHcrEventsProvider({ runtimeUrl, token: () => readFileSync12(tokenPath, "utf8") }).inspect();
|
|
39590
|
+
if (jobs) await createHcrJobsProvider({ runtimeUrl, token: () => readFileSync12(tokenPath, "utf8") }).inspect();
|
|
39065
39591
|
timer = setInterval(() => {
|
|
39066
39592
|
try {
|
|
39067
39593
|
issueToken();
|
|
@@ -39077,7 +39603,7 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39077
39603
|
}
|
|
39078
39604
|
}, 36e5);
|
|
39079
39605
|
notify("hcr", "ready");
|
|
39080
|
-
const configurationFingerprint =
|
|
39606
|
+
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
39607
|
return { identityScope: { ...state.scope }, runtimeUrl, tokenPath, database, storage, events, jobs, databasePort, migrations: applied, configurationFingerprint, renewConfiguration, stop };
|
|
39082
39608
|
} catch (error2) {
|
|
39083
39609
|
await stop();
|
|
@@ -39086,15 +39612,15 @@ async function startLocalServices(root, manifest, options = {}) {
|
|
|
39086
39612
|
}
|
|
39087
39613
|
|
|
39088
39614
|
// src/local-job-auth.ts
|
|
39089
|
-
import { createHash as
|
|
39090
|
-
import { lstatSync as
|
|
39615
|
+
import { createHash as createHash8 } from "node:crypto";
|
|
39616
|
+
import { lstatSync as lstatSync9, readFileSync as readFileSync13 } from "node:fs";
|
|
39091
39617
|
import { isAbsolute as isAbsolute5, resolve as resolve9 } from "node:path";
|
|
39092
39618
|
function prepareLocalJobAuth(root, filename2) {
|
|
39093
39619
|
const read = (path, maximum) => {
|
|
39094
39620
|
assertLocalStatePath(root, path);
|
|
39095
|
-
const metadata =
|
|
39621
|
+
const metadata = lstatSync9(path);
|
|
39096
39622
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
39097
|
-
const bytes =
|
|
39623
|
+
const bytes = readFileSync13(path);
|
|
39098
39624
|
if (bytes.length > maximum) throw new Error();
|
|
39099
39625
|
return bytes;
|
|
39100
39626
|
};
|
|
@@ -39108,7 +39634,7 @@ function prepareLocalJobAuth(root, filename2) {
|
|
|
39108
39634
|
if (trustFile === stateFile) throw new Error();
|
|
39109
39635
|
const bytes = read(trustFile, 131072), trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
39110
39636
|
read(stateFile, 2048);
|
|
39111
|
-
if (
|
|
39637
|
+
if (createHash8("sha256").update(bytes).digest("hex") !== input.trustDigest || trust.revision !== input.revision) throw new Error();
|
|
39112
39638
|
createPersistentApplicationAuthProvider(trust, { expectedScope: input.scope, stateFile });
|
|
39113
39639
|
return { trustFile, stateFile, scope: structuredClone(input.scope), revision: input.revision, trustDigest: input.trustDigest };
|
|
39114
39640
|
} catch {
|
|
@@ -39117,20 +39643,20 @@ function prepareLocalJobAuth(root, filename2) {
|
|
|
39117
39643
|
}
|
|
39118
39644
|
|
|
39119
39645
|
// src/local-job-trust-renewal.ts
|
|
39120
|
-
import { createHash as
|
|
39121
|
-
import { lstatSync as
|
|
39646
|
+
import { createHash as createHash10 } from "node:crypto";
|
|
39647
|
+
import { lstatSync as lstatSync11, readFileSync as readFileSync15 } from "node:fs";
|
|
39122
39648
|
import { isAbsolute as isAbsolute7, relative as relative2, resolve as resolve11 } from "node:path";
|
|
39123
39649
|
|
|
39124
39650
|
// src/workload-trust-sync.ts
|
|
39125
|
-
import { lstatSync as
|
|
39651
|
+
import { lstatSync as lstatSync10, readFileSync as readFileSync14 } from "node:fs";
|
|
39126
39652
|
import { isAbsolute as isAbsolute6, resolve as resolve10 } from "node:path";
|
|
39127
|
-
import { createHash as
|
|
39653
|
+
import { createHash as createHash9 } from "node:crypto";
|
|
39128
39654
|
function prepareWorkloadTrustSynchronization(filename2) {
|
|
39129
39655
|
try {
|
|
39130
39656
|
if (!isAbsolute6(filename2)) throw new Error();
|
|
39131
|
-
const metadata =
|
|
39657
|
+
const metadata = lstatSync10(filename2);
|
|
39132
39658
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 65536) throw new Error();
|
|
39133
|
-
const bytes =
|
|
39659
|
+
const bytes = readFileSync14(filename2);
|
|
39134
39660
|
if (bytes.length > 65536) throw new Error();
|
|
39135
39661
|
const value = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
39136
39662
|
const allowed = ["controlPlaneUrl", "agentId", "expectedScope", "managementIssuer", "managementAudience", "managementPublicKeyPem", "credentialFile", "trustFile", "stateFile", "intervalSeconds"];
|
|
@@ -39141,15 +39667,15 @@ function prepareWorkloadTrustSynchronization(filename2) {
|
|
|
39141
39667
|
const intervalSeconds = value.intervalSeconds ?? 30;
|
|
39142
39668
|
if (!Number.isSafeInteger(intervalSeconds) || intervalSeconds < 10 || intervalSeconds > 300) throw new Error();
|
|
39143
39669
|
const credential = () => {
|
|
39144
|
-
const metadata2 =
|
|
39670
|
+
const metadata2 = lstatSync10(credentialFile);
|
|
39145
39671
|
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 =
|
|
39672
|
+
const bytes2 = readFileSync14(credentialFile);
|
|
39147
39673
|
if (bytes2.length > 256) throw new Error("Management credential unavailable");
|
|
39148
39674
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes2).trim();
|
|
39149
39675
|
};
|
|
39150
39676
|
const options = { controlPlaneUrl: value.controlPlaneUrl, agentId: value.agentId, expectedScope: value.expectedScope, managementIssuer: value.managementIssuer, managementAudience: value.managementAudience, managementPublicKeyPem: value.managementPublicKeyPem, credential, trustFile, stateFile };
|
|
39151
39677
|
const plan = planApplicationAuthSynchronization(options);
|
|
39152
|
-
return { options, plan, intervalSeconds, credentialFile, configurationDigest:
|
|
39678
|
+
return { options, plan, intervalSeconds, credentialFile, configurationDigest: createHash9("sha256").update(bytes).digest("hex") };
|
|
39153
39679
|
} catch {
|
|
39154
39680
|
throw new Error("Invalid operator trust-sync configuration");
|
|
39155
39681
|
}
|
|
@@ -39208,15 +39734,15 @@ function prepareLocalJobTrustRenewal(root, filename2, mount) {
|
|
|
39208
39734
|
const same = (first, second) => process.platform === "win32" ? first.toLowerCase() === second.toLowerCase() : first === second;
|
|
39209
39735
|
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
39736
|
assertLocalStatePath(root, configured.credentialFile);
|
|
39211
|
-
const metadata =
|
|
39737
|
+
const metadata = lstatSync11(configured.credentialFile);
|
|
39212
39738
|
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
39739
|
return { configurationFile, configurationDigest: configured.configurationDigest, credentialFile: configured.credentialFile, intervalSeconds: configured.intervalSeconds, options };
|
|
39214
39740
|
} catch {
|
|
39215
39741
|
throw new Error("Invalid reviewed native worker trust renewal; preserve trust and state and review explicitly");
|
|
39216
39742
|
}
|
|
39217
39743
|
}
|
|
39218
|
-
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash:
|
|
39219
|
-
const { createHash: createHash17, lstatSync:
|
|
39744
|
+
function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies = { createHash: createHash10, lstatSync: lstatSync11, readFileSync: readFileSync15, isAbsolute: isAbsolute7, relative: relative2, resolve: resolve11, createPersistentApplicationAuthProvider, synchronizeApplicationAuthTrustWithDigest }) {
|
|
39745
|
+
const { createHash: createHash17, lstatSync: lstatSync21, readFileSync: readFileSync30, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2, synchronizeApplicationAuthTrustWithDigest: synchronizeApplicationAuthTrustWithDigest2 } = dependencies;
|
|
39220
39746
|
const key = (filename2) => process.platform === "win32" ? resolve25(filename2).toLowerCase() : resolve25(filename2);
|
|
39221
39747
|
const groups = [];
|
|
39222
39748
|
for (const mount of mounts) {
|
|
@@ -39236,11 +39762,11 @@ function createLocalJobTrustRenewal(root, mounts, settings = {}, dependencies =
|
|
|
39236
39762
|
const read = (filename2, maximum, privateFile2 = false) => {
|
|
39237
39763
|
for (let current = resolve25(filename2); current !== root; current = resolve25(current, "..")) {
|
|
39238
39764
|
const part = relative11(root, current);
|
|
39239
|
-
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) ||
|
|
39765
|
+
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error();
|
|
39240
39766
|
}
|
|
39241
|
-
const metadata =
|
|
39767
|
+
const metadata = lstatSync21(filename2);
|
|
39242
39768
|
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 =
|
|
39769
|
+
const bytes = readFileSync30(filename2);
|
|
39244
39770
|
if (bytes.length > maximum) throw new Error();
|
|
39245
39771
|
return bytes;
|
|
39246
39772
|
};
|
|
@@ -39321,14 +39847,14 @@ function prepareLocalJobWorker(root, directory2, artifacts, manifest, authFile,
|
|
|
39321
39847
|
if (trustSyncFile !== void 0 && authFile === void 0) throw new Error("Native worker trust renewal requires explicit reviewed auth mounts");
|
|
39322
39848
|
const authTrust = authFile === void 0 ? void 0 : prepareLocalJobAuth(root, authFile);
|
|
39323
39849
|
if (authTrust && trustSyncFile !== void 0) authTrust.renewal = prepareLocalJobTrustRenewal(root, trustSyncFile, authTrust);
|
|
39324
|
-
const workerFile =
|
|
39850
|
+
const workerFile = join12(resolve12(root, directory2), "workload.mjs"), metadataFile = join12(resolve12(root, directory2), "artifact.json");
|
|
39325
39851
|
for (const filename2 of [workerFile, metadataFile]) assertLocalStatePath(root, filename2);
|
|
39326
|
-
if (!
|
|
39327
|
-
const metadata = JSON.parse(
|
|
39328
|
-
const bundle =
|
|
39329
|
-
const actual =
|
|
39852
|
+
if (!lstatSync12(workerFile).isFile() || lstatSync12(workerFile).size > 16777216 || !lstatSync12(metadataFile).isFile() || lstatSync12(metadataFile).size > 65536) throw new Error("Invalid bounded native worker artifact");
|
|
39853
|
+
const metadata = JSON.parse(readFileSync16(metadataFile, "utf8"));
|
|
39854
|
+
const bundle = readFileSync16(workerFile);
|
|
39855
|
+
const actual = createHash11("sha256").update(bundle).digest("hex");
|
|
39330
39856
|
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 !==
|
|
39857
|
+
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
39858
|
const artifact = validateLocalJobArtifacts(artifacts).find((item) => item.artifactVersion === actual);
|
|
39333
39859
|
if (!artifact) throw new Error("Native worker bundle is not an explicitly reviewed job artifact");
|
|
39334
39860
|
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 +39864,29 @@ function readLocalJobArtifacts(root, filename2) {
|
|
|
39338
39864
|
if (!filename2 || isAbsolute8(filename2)) throw new Error("Job artifact admission requires a repository-relative reviewed JSON file");
|
|
39339
39865
|
const path = resolve12(root, filename2);
|
|
39340
39866
|
assertLocalStatePath(root, path);
|
|
39341
|
-
if (!
|
|
39342
|
-
return validateLocalJobArtifacts(JSON.parse(
|
|
39867
|
+
if (!lstatSync12(path).isFile() || lstatSync12(path).size > 16384) throw new Error("Reviewed job artifact admission exceeds supported bounds");
|
|
39868
|
+
return validateLocalJobArtifacts(JSON.parse(readFileSync16(path, "utf8")));
|
|
39343
39869
|
}
|
|
39344
|
-
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash:
|
|
39345
|
-
const { spawn: spawn6, createHash: createHash17, lstatSync:
|
|
39870
|
+
function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createHash: createHash11, lstatSync: lstatSync12, readFileSync: readFileSync16, isAbsolute: isAbsolute8, relative: relative3, resolve: resolve12, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider }) {
|
|
39871
|
+
const { spawn: spawn6, createHash: createHash17, lstatSync: lstatSync21, readFileSync: readFileSync30, isAbsolute: isAbsolute17, relative: relative11, resolve: resolve25, validateWorkloadJobSchedules: validateWorkloadJobSchedules2, createPersistentApplicationAuthProvider: createPersistentApplicationAuthProvider2 } = dependencies;
|
|
39346
39872
|
const assertReady = () => {
|
|
39347
39873
|
for (let current = resolve25(options.workerFile); current !== options.root; current = resolve25(current, "..")) {
|
|
39348
39874
|
const part = relative11(options.root, current);
|
|
39349
|
-
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) ||
|
|
39875
|
+
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error("Native worker paths or pins changed");
|
|
39350
39876
|
}
|
|
39351
|
-
if (!
|
|
39877
|
+
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
39878
|
if (options.authTrust) {
|
|
39353
39879
|
try {
|
|
39354
39880
|
const mount = options.authTrust;
|
|
39355
39881
|
for (const path of [mount.trustFile, mount.stateFile]) {
|
|
39356
39882
|
for (let current = resolve25(path); current !== options.root; current = resolve25(current, "..")) {
|
|
39357
39883
|
const part = relative11(options.root, current);
|
|
39358
|
-
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) ||
|
|
39884
|
+
if (part === ".." || part.startsWith("../") || part.startsWith("..\\") || isAbsolute17(part) || lstatSync21(current).isSymbolicLink()) throw new Error();
|
|
39359
39885
|
}
|
|
39360
|
-
const metadata =
|
|
39886
|
+
const metadata = lstatSync21(path);
|
|
39361
39887
|
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.size > (path === mount.trustFile ? 131072 : 2048)) throw new Error();
|
|
39362
39888
|
}
|
|
39363
|
-
const bytes =
|
|
39889
|
+
const bytes = readFileSync30(mount.trustFile);
|
|
39364
39890
|
if (bytes.length > 131072 || createHash17("sha256").update(bytes).digest("hex") !== mount.trustDigest) throw new Error();
|
|
39365
39891
|
const trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
39366
39892
|
if (trust.revision !== mount.revision) throw new Error();
|
|
@@ -39474,9 +40000,9 @@ function createLocalJobExecutor(options, dependencies = { spawn: spawn2, createH
|
|
|
39474
40000
|
}
|
|
39475
40001
|
|
|
39476
40002
|
// src/local-native-jobs.ts
|
|
39477
|
-
import { createHash as
|
|
40003
|
+
import { createHash as createHash12 } from "node:crypto";
|
|
39478
40004
|
function createLocalNativeJobs(local, native, executor, artifact, scope, onFailure = () => {
|
|
39479
|
-
}, hash2 =
|
|
40005
|
+
}, hash2 = createHash12, catalog = { workloadJobSchedules, validateWorkloadJobSchedules, HcrJobsRequestError }, historical = []) {
|
|
39480
40006
|
const workers = [{ artifact, executor }, ...historical];
|
|
39481
40007
|
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
40008
|
const lanes = workers.flatMap((worker) => worker.artifact.jobs.map((policy) => ({ ...worker, policy })));
|
|
@@ -39615,7 +40141,7 @@ import { jobs } from "@backifydev/sdk";
|
|
|
39615
40141
|
import { createHcrDatabaseProvider, createHcrStorageProvider, createHcrEventsProvider, createHcrJobsProvider, HcrJobsRequestError, workloadJobSchedules, validateWorkloadJobSchedules, createPersistentApplicationAuthProvider } from "@backifydev/sdk/server";
|
|
39616
40142
|
import { createServer } from "node:http";
|
|
39617
40143
|
import { existsSync, lstatSync, readFileSync, writeFileSync, renameSync } from "node:fs";
|
|
39618
|
-
import { timingSafeEqual, createHash } from "node:crypto";
|
|
40144
|
+
import { timingSafeEqual, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
39619
40145
|
import { spawn } from "node:child_process";
|
|
39620
40146
|
import { isAbsolute, relative, resolve } from "node:path";
|
|
39621
40147
|
const statePath = process.env.BACKIFY_LOCAL_STATE;
|
|
@@ -39679,11 +40205,26 @@ async function inspectEndpoint(url) {
|
|
|
39679
40205
|
return { url, status: "responding", httpStatus: response.status };
|
|
39680
40206
|
} catch { return { url, status: "unreachable" }; }
|
|
39681
40207
|
}
|
|
40208
|
+
const createLocalEmailAuth = __BACKIFY_LOCAL_EMAIL_AUTH__;
|
|
40209
|
+
const emailOrigin = process.env.BACKIFY_LOCAL_FRONTEND_URL || process.env.BACKIFY_LOCAL_BACKEND_URL;
|
|
40210
|
+
const localEmailAuth = runtime.localIdentity && emailOrigin ? createLocalEmailAuth({ identity: runtime.localIdentity, origin: emailOrigin }, { createHash, randomBytes, randomUUID }) : undefined;
|
|
39682
40211
|
const server = createServer(async (request, response) => {
|
|
39683
40212
|
response.setHeader("cache-control", "no-store"); response.setHeader("x-content-type-options", "nosniff");
|
|
39684
40213
|
const send = (status, value) => { response.writeHead(status, { "content-type": "application/json" }); response.end(JSON.stringify(value)); };
|
|
39685
40214
|
if (!/^((127\.0\.0\.1)|(localhost)):\d+$/.test(request.headers.host ?? "")) return send(403, { error: "Invalid host" });
|
|
39686
40215
|
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); }
|
|
40216
|
+
if (request.url?.startsWith("/.backify/auth/")) {
|
|
40217
|
+
if (!localEmailAuth) return send(503, { error: "local_identity_unavailable" });
|
|
40218
|
+
try {
|
|
40219
|
+
let body = "";
|
|
40220
|
+
for await (const chunk of request) { body += chunk.toString(); if (Buffer.byteLength(body) > 8192) return send(413, { error: "request_too_large" }); }
|
|
40221
|
+
const headers = new Headers();
|
|
40222
|
+
for (const [name, value] of Object.entries(request.headers)) if (typeof value === "string" && name !== "host") headers.set(name, value);
|
|
40223
|
+
const result = await localEmailAuth.handle(new Request(emailOrigin + request.url, { method: request.method, headers, ...(body ? { body } : {}) }));
|
|
40224
|
+
response.writeHead(result.status, Object.fromEntries(result.headers));
|
|
40225
|
+
return response.end(Buffer.from(await result.arrayBuffer()));
|
|
40226
|
+
} catch { return send(400, { error: "invalid_local_auth_request" }); }
|
|
40227
|
+
}
|
|
39687
40228
|
const provided = request.headers.authorization?.replace(/^Bearer /, "") ?? "";
|
|
39688
40229
|
const bytes = /^[a-f0-9]{64}$/.test(provided) ? Buffer.from(provided, "hex") : Buffer.alloc(0);
|
|
39689
40230
|
if (bytes.length !== token.length || !timingSafeEqual(bytes, token)) return send(401, { error: "Local session required" });
|
|
@@ -39691,6 +40232,7 @@ const server = createServer(async (request, response) => {
|
|
|
39691
40232
|
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
40233
|
if (request.method === "GET" && request.url === "/v1/logs") return send(200, runtime.inspect().logs);
|
|
39693
40234
|
if (request.method === "GET" && request.url === "/v1/events") return send(200, await inspectEvents());
|
|
40235
|
+
if (request.method === "GET" && request.url === "/v1/identity/inbox") return localEmailAuth ? send(200, { messages: localEmailAuth.inbox() }) : send(503, { error: "local_identity_unavailable" });
|
|
39694
40236
|
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
40237
|
if (request.method === "GET" && request.url === "/v1/database/tables") return send(200, await inspector.tables());
|
|
39696
40238
|
if (request.method === "GET" && request.url === "/v1/storage/buckets") return send(200, inspector.buckets());
|
|
@@ -39729,14 +40271,14 @@ process.on("SIGTERM", stop); process.on("SIGINT", stop); process.once("disconnec
|
|
|
39729
40271
|
catch { console.error("Native worker trust renewal delivery refused; pin guards remain enforced."); }
|
|
39730
40272
|
}
|
|
39731
40273
|
});
|
|
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());
|
|
40274
|
+
`.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
40275
|
}
|
|
39734
40276
|
|
|
39735
40277
|
// src/local-frontend.ts
|
|
39736
40278
|
import { spawn as spawn3 } from "node:child_process";
|
|
39737
|
-
import { readFileSync as
|
|
40279
|
+
import { readFileSync as readFileSync18, realpathSync as realpathSync3, existsSync as existsSync12, statSync } from "node:fs";
|
|
39738
40280
|
import { createRequire as createRequire3 } from "node:module";
|
|
39739
|
-
import { dirname as dirname10, isAbsolute as isAbsolute10, join as
|
|
40281
|
+
import { dirname as dirname10, isAbsolute as isAbsolute10, join as join14, relative as relative5, resolve as resolve14 } from "node:path";
|
|
39740
40282
|
import { pathToFileURL } from "node:url";
|
|
39741
40283
|
|
|
39742
40284
|
// src/local-frontend-guard.ts
|
|
@@ -39754,6 +40296,7 @@ const guard = {
|
|
|
39754
40296
|
config.root = settings.directory;
|
|
39755
40297
|
config.server = {
|
|
39756
40298
|
...config.server, host: "127.0.0.1", port: settings.port, strictPort: true,
|
|
40299
|
+
...(settings.authUrl ? { proxy: { ...config.server?.proxy, "/.backify/auth": { target: settings.authUrl, changeOrigin: true } } } : {}),
|
|
39757
40300
|
fs: { ...config.server?.fs, strict: true, deny: [...new Set([...(config.server?.fs?.deny ?? []), ...settings.denied])] }
|
|
39758
40301
|
};
|
|
39759
40302
|
}
|
|
@@ -39803,9 +40346,9 @@ await server.listen();
|
|
|
39803
40346
|
`;
|
|
39804
40347
|
|
|
39805
40348
|
// 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
|
|
40349
|
+
import { createServer as createServer4, request as proxyRequest } from "node:http";
|
|
40350
|
+
import { lstatSync as lstatSync13, readFileSync as readFileSync17, realpathSync as realpathSync2, watch } from "node:fs";
|
|
40351
|
+
import { extname as extname2, isAbsolute as isAbsolute9, join as join13, relative as relative4, resolve as resolve13, sep as sep4 } from "node:path";
|
|
39809
40352
|
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
40353
|
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
40354
|
function publicFile(directory2, pathname) {
|
|
@@ -39815,12 +40358,12 @@ function publicFile(directory2, pathname) {
|
|
|
39815
40358
|
const filename2 = resolve13(directory2, ...parts), part = relative4(directory2, filename2);
|
|
39816
40359
|
if (part === ".." || part.startsWith(".." + sep4) || isAbsolute9(part) || !contentTypes[extname2(filename2).toLowerCase()]) throw new Error("refused");
|
|
39817
40360
|
let current = directory2;
|
|
39818
|
-
if (
|
|
40361
|
+
if (lstatSync13(current).isSymbolicLink() || realpathSync2(current) !== directory2) throw new Error("refused");
|
|
39819
40362
|
for (const segment of parts) {
|
|
39820
|
-
current =
|
|
39821
|
-
if (
|
|
40363
|
+
current = join13(current, segment);
|
|
40364
|
+
if (lstatSync13(current).isSymbolicLink()) throw new Error("refused");
|
|
39822
40365
|
}
|
|
39823
|
-
const stat =
|
|
40366
|
+
const stat = lstatSync13(filename2);
|
|
39824
40367
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size > 5242880) throw new Error("refused");
|
|
39825
40368
|
return filename2;
|
|
39826
40369
|
}
|
|
@@ -39828,7 +40371,7 @@ function prepareLocalStaticFrontend(directory2) {
|
|
|
39828
40371
|
publicFile(directory2, "/index.html");
|
|
39829
40372
|
return { adapter: "static", directory: directory2 };
|
|
39830
40373
|
}
|
|
39831
|
-
async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
40374
|
+
async function startLocalStaticFrontend(directory2, port, backendUrl, authUrl) {
|
|
39832
40375
|
const assignedPort = await allocateLocalPort(port), url2 = "http://127.0.0.1:" + assignedPort;
|
|
39833
40376
|
let revision = 0;
|
|
39834
40377
|
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 +40384,18 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
|
39841
40384
|
response.end(request.method === "HEAD" ? void 0 : body);
|
|
39842
40385
|
};
|
|
39843
40386
|
if (request.headers.host !== "127.0.0.1:" + assignedPort || request.headers.origin && request.headers.origin !== url2) return send(403, "text/plain", "Development request refused");
|
|
40387
|
+
if (authUrl && request.url?.startsWith("/.backify/auth/")) {
|
|
40388
|
+
const upstream = proxyRequest(new URL(request.url, authUrl), { method: request.method, headers: { ...request.headers, host: new URL(authUrl).host } }, (incoming) => {
|
|
40389
|
+
response.writeHead(incoming.statusCode ?? 502, incoming.headers);
|
|
40390
|
+
incoming.pipe(response);
|
|
40391
|
+
});
|
|
40392
|
+
upstream.on("error", () => {
|
|
40393
|
+
if (!response.headersSent) send(502, "text/plain", "Local authentication unavailable");
|
|
40394
|
+
else response.destroy();
|
|
40395
|
+
});
|
|
40396
|
+
request.pipe(upstream);
|
|
40397
|
+
return;
|
|
40398
|
+
}
|
|
39844
40399
|
if (!["GET", "HEAD"].includes(request.method ?? "")) return send(405, "text/plain", "Method not allowed");
|
|
39845
40400
|
try {
|
|
39846
40401
|
const pathname = decodeURIComponent((request.url ?? "/").split("?")[0]);
|
|
@@ -39848,7 +40403,7 @@ async function startLocalStaticFrontend(directory2, port, backendUrl) {
|
|
|
39848
40403
|
if (pathname === "/__backify/revision") return send(200, "text/plain", String(revision));
|
|
39849
40404
|
if (pathname === "/__backify/config.json") return send(200, "application/json", JSON.stringify({ backendUrl: backendUrl ?? null }));
|
|
39850
40405
|
const filename2 = publicFile(directory2, pathname);
|
|
39851
|
-
const content =
|
|
40406
|
+
const content = readFileSync17(filename2);
|
|
39852
40407
|
if (content.length > 5242880) throw new Error("refused");
|
|
39853
40408
|
const extension = extname2(filename2).toLowerCase();
|
|
39854
40409
|
const body = extension === ".html" ? content.toString("utf8") + '\n<script src="/__backify/reload.js?revision=' + revision + '"></script>\n' : content;
|
|
@@ -39898,15 +40453,15 @@ function prepareLocalFrontend(root, options, privateFiles = []) {
|
|
|
39898
40453
|
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
40454
|
return prepareLocalStaticFrontend(directory2);
|
|
39900
40455
|
}
|
|
39901
|
-
if (!
|
|
39902
|
-
const require3 = createRequire3(
|
|
40456
|
+
if (!existsSync12(join14(directory2, "package.json"))) throw new Error("Frontend requires an existing package.json and installed Vite");
|
|
40457
|
+
const require3 = createRequire3(join14(directory2, "package.json"));
|
|
39903
40458
|
let packagePath;
|
|
39904
40459
|
try {
|
|
39905
40460
|
packagePath = require3.resolve("vite/package.json");
|
|
39906
40461
|
} catch {
|
|
39907
40462
|
throw new Error("Frontend requires locally installed Vite; Backify does not install dependencies automatically");
|
|
39908
40463
|
}
|
|
39909
|
-
const metadata = JSON.parse(
|
|
40464
|
+
const metadata = JSON.parse(readFileSync18(packagePath, "utf8"));
|
|
39910
40465
|
if (metadata.name !== "vite" || typeof metadata.bin?.vite !== "string") throw new Error("Installed Vite has no supported CLI entrypoint");
|
|
39911
40466
|
const executable = realpathSync3(resolve14(dirname10(packagePath), metadata.bin.vite));
|
|
39912
40467
|
const executablePart = relative5(realpathSync3(dirname10(packagePath)), executable);
|
|
@@ -39932,15 +40487,15 @@ async function stopFrontend(child) {
|
|
|
39932
40487
|
else child.kill("SIGTERM");
|
|
39933
40488
|
});
|
|
39934
40489
|
}
|
|
39935
|
-
async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic) {
|
|
39936
|
-
if (prepared.adapter === "static") return startLocalStaticFrontend(prepared.directory, port, backendUrl);
|
|
40490
|
+
async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic, authUrl) {
|
|
40491
|
+
if (prepared.adapter === "static") return startLocalStaticFrontend(prepared.directory, port, backendUrl, authUrl);
|
|
39937
40492
|
const assignedPort = await allocateLocalPort(port);
|
|
39938
40493
|
const url2 = "http://127.0.0.1:" + assignedPort;
|
|
39939
40494
|
const environment = { ...process.env };
|
|
39940
40495
|
for (const name2 of Object.keys(environment)) if (name2.startsWith("BACKIFY_")) delete environment[name2];
|
|
39941
40496
|
if (backendUrl) environment.VITE_BACKIFY_BACKEND_URL = backendUrl;
|
|
39942
40497
|
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("\\", "/")) };
|
|
40498
|
+
const settings = { authUrl, moduleUrl: pathToFileURL(prepared.modulePath).href, directory: prepared.directory, port: assignedPort, denied, privateFiles: prepared.privateFiles.map((filename2) => filename2.replaceAll("\\", "/")) };
|
|
39944
40499
|
const launcher = "const settings=" + JSON.stringify(settings) + ";\n" + protectedFrontendSource;
|
|
39945
40500
|
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
40501
|
if (onDiagnostic) {
|
|
@@ -39974,107 +40529,9 @@ async function startLocalFrontend(prepared, port, backendUrl, onDiagnostic) {
|
|
|
39974
40529
|
}
|
|
39975
40530
|
|
|
39976
40531
|
// src/local-identity.ts
|
|
39977
|
-
import { readFileSync as
|
|
40532
|
+
import { readFileSync as readFileSync19, statSync as statSync2 } from "node:fs";
|
|
39978
40533
|
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";
|
|
40534
|
+
import { randomUUID as randomUUID10 } from "node:crypto";
|
|
40078
40535
|
function prepareLocalIdentity(root, filename2) {
|
|
40079
40536
|
if (filename2 === void 0) return void 0;
|
|
40080
40537
|
const path = resolve15(root, filename2);
|
|
@@ -40082,19 +40539,19 @@ function prepareLocalIdentity(root, filename2) {
|
|
|
40082
40539
|
if (!statSync2(path).isFile() || statSync2(path).size > 16384) throw new Error("Local identity profiles require a file at most 16 KiB");
|
|
40083
40540
|
let input;
|
|
40084
40541
|
try {
|
|
40085
|
-
input = JSON.parse(
|
|
40542
|
+
input = JSON.parse(readFileSync19(path, "utf8"));
|
|
40086
40543
|
} catch {
|
|
40087
40544
|
throw new Error("Invalid local identity profile JSON");
|
|
40088
40545
|
}
|
|
40089
40546
|
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
40547
|
const value = input;
|
|
40091
40548
|
if (value.version !== 1) throw new Error("Invalid local identity profile version");
|
|
40092
|
-
const identity = createLocalIdentityProvider({ scope: { organizationId:
|
|
40549
|
+
const identity = createLocalIdentityProvider({ scope: { organizationId: randomUUID10(), applicationId: randomUUID10(), environmentId: randomUUID10() }, organizationName: value.organizationName, users: value.users, requestOrigins: ["http://127.0.0.1:3000"] });
|
|
40093
40550
|
return { organizationName: value.organizationName, users: identity.profiles() };
|
|
40094
40551
|
}
|
|
40095
40552
|
function localIdentityCommand(args2) {
|
|
40096
40553
|
const kind = args2[0];
|
|
40097
|
-
if (!["users", "issue", "clear"].includes(kind)) throw new Error("Use backify identity users|issue|clear --local [--json]");
|
|
40554
|
+
if (!["users", "inbox", "issue", "clear"].includes(kind)) throw new Error("Use backify identity users|inbox|issue|clear --local [--json]");
|
|
40098
40555
|
const flags = /* @__PURE__ */ new Set();
|
|
40099
40556
|
let userId;
|
|
40100
40557
|
for (let index = 1; index < args2.length; index++) {
|
|
@@ -40115,7 +40572,7 @@ function localIdentityCommand(args2) {
|
|
|
40115
40572
|
}
|
|
40116
40573
|
|
|
40117
40574
|
// src/local-job-history.ts
|
|
40118
|
-
import { lstatSync as
|
|
40575
|
+
import { lstatSync as lstatSync14, readFileSync as readFileSync20 } from "node:fs";
|
|
40119
40576
|
import { isAbsolute as isAbsolute11, resolve as resolve16 } from "node:path";
|
|
40120
40577
|
function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
40121
40578
|
if (filename2 === void 0) return [];
|
|
@@ -40123,9 +40580,9 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
40123
40580
|
if (typeof filename3 !== "string" || !filename3 || isAbsolute11(filename3)) throw new Error();
|
|
40124
40581
|
const path = resolve16(root, filename3);
|
|
40125
40582
|
assertLocalStatePath(root, path);
|
|
40126
|
-
const metadata =
|
|
40583
|
+
const metadata = lstatSync14(path);
|
|
40127
40584
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > maximum) throw new Error();
|
|
40128
|
-
const bytes =
|
|
40585
|
+
const bytes = readFileSync20(path);
|
|
40129
40586
|
if (bytes.length > maximum) throw new Error();
|
|
40130
40587
|
return new TextDecoder("utf8", { fatal: true }).decode(bytes);
|
|
40131
40588
|
};
|
|
@@ -40171,14 +40628,14 @@ function prepareLocalJobHistory(root, filename2, artifacts, manifest, current) {
|
|
|
40171
40628
|
}
|
|
40172
40629
|
|
|
40173
40630
|
// 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
|
|
40631
|
+
import { createCipheriv, createDecipheriv, randomBytes as randomBytes5, randomUUID as randomUUID11 } from "node:crypto";
|
|
40632
|
+
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";
|
|
40633
|
+
import { dirname as dirname11, isAbsolute as isAbsolute12, join as join15, relative as relative6, resolve as resolve17 } from "node:path";
|
|
40177
40634
|
var maximumBytes2 = 1048576;
|
|
40178
40635
|
var secretName = /^[A-Z][A-Z0-9_]{0,127}$/;
|
|
40179
40636
|
var failure = () => new Error("Local secret vault unavailable or invalid; review the vault and external key privately");
|
|
40180
40637
|
function vaultPath(root) {
|
|
40181
|
-
return
|
|
40638
|
+
return join15(realpathSync4(root), ".backify", "dev", "secrets.enc.json");
|
|
40182
40639
|
}
|
|
40183
40640
|
function inside(root, filename2) {
|
|
40184
40641
|
const part = relative6(root, filename2);
|
|
@@ -40186,12 +40643,12 @@ function inside(root, filename2) {
|
|
|
40186
40643
|
}
|
|
40187
40644
|
function privateFile(filename2, limit) {
|
|
40188
40645
|
for (let current = resolve17(filename2); ; current = dirname11(current)) {
|
|
40189
|
-
if (
|
|
40646
|
+
if (lstatSync15(current).isSymbolicLink()) throw failure();
|
|
40190
40647
|
if (dirname11(current) === current) break;
|
|
40191
40648
|
}
|
|
40192
|
-
const stat =
|
|
40649
|
+
const stat = lstatSync15(filename2);
|
|
40193
40650
|
if (!stat.isFile() || stat.size > limit || stat.nlink !== 1 || process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
|
|
40194
|
-
return
|
|
40651
|
+
return readFileSync21(filename2);
|
|
40195
40652
|
}
|
|
40196
40653
|
function externalKey(root, filename2) {
|
|
40197
40654
|
const keyFile = resolve17(filename2);
|
|
@@ -40223,22 +40680,22 @@ function encrypt(root, application, key, secrets) {
|
|
|
40223
40680
|
function writePrivate2(filename2, value) {
|
|
40224
40681
|
const descriptor2 = openSync3(filename2, "wx", 384);
|
|
40225
40682
|
try {
|
|
40226
|
-
|
|
40683
|
+
writeFileSync11(descriptor2, value);
|
|
40227
40684
|
fsyncSync3(descriptor2);
|
|
40228
40685
|
} finally {
|
|
40229
40686
|
closeSync3(descriptor2);
|
|
40230
40687
|
}
|
|
40231
40688
|
}
|
|
40232
40689
|
function ensureIgnored(root) {
|
|
40233
|
-
const filename2 =
|
|
40690
|
+
const filename2 = join15(root, ".gitignore");
|
|
40234
40691
|
assertLocalStatePath(root, filename2);
|
|
40235
|
-
const current =
|
|
40236
|
-
if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/"))
|
|
40692
|
+
const current = existsSync13(filename2) ? readFileSync21(filename2, "utf8") : "";
|
|
40693
|
+
if (!current.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync11(filename2, current + (current && !current.endsWith("\n") ? "\n" : "") + ".backify/\n");
|
|
40237
40694
|
}
|
|
40238
40695
|
function readLocalSecrets(root, application, keyFile) {
|
|
40239
40696
|
const filename2 = vaultPath(root);
|
|
40240
40697
|
assertLocalStatePath(root, filename2);
|
|
40241
|
-
if (!
|
|
40698
|
+
if (!existsSync13(filename2) && keyFile === void 0) return {};
|
|
40242
40699
|
if (!keyFile) throw new Error("Encrypted local secrets require --local-secrets-key <external-key-file>");
|
|
40243
40700
|
let key, plaintext;
|
|
40244
40701
|
try {
|
|
@@ -40268,10 +40725,10 @@ function readLocalSecrets(root, application, keyFile) {
|
|
|
40268
40725
|
function initializeLocalSecrets(root, application, keyFile) {
|
|
40269
40726
|
const filename2 = vaultPath(root), external = resolve17(keyFile);
|
|
40270
40727
|
assertLocalStatePath(root, filename2);
|
|
40271
|
-
if (
|
|
40728
|
+
if (existsSync13(filename2) || existsSync13(external)) throw new Error("Local secret initialization never overwrites an existing vault or key");
|
|
40272
40729
|
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
40730
|
for (let current = dirname11(external); ; current = dirname11(current)) {
|
|
40274
|
-
const stat =
|
|
40731
|
+
const stat = lstatSync15(current);
|
|
40275
40732
|
if (stat.isSymbolicLink()) throw failure();
|
|
40276
40733
|
if (current === dirname11(external) && process.platform !== "win32" && (stat.mode & 63) !== 0) throw failure();
|
|
40277
40734
|
if (dirname11(current) === current) break;
|
|
@@ -40280,7 +40737,7 @@ function initializeLocalSecrets(root, application, keyFile) {
|
|
|
40280
40737
|
const release2 = acquireLocalLease(root, ".backify/dev/secrets.lock");
|
|
40281
40738
|
const key = randomBytes5(32);
|
|
40282
40739
|
try {
|
|
40283
|
-
if (
|
|
40740
|
+
if (existsSync13(filename2)) throw failure();
|
|
40284
40741
|
mkdirSync5(dirname11(filename2), { recursive: true, mode: 448 });
|
|
40285
40742
|
writePrivate2(external, key.toString("hex"));
|
|
40286
40743
|
writePrivate2(filename2, encrypt(root, application, key, {}));
|
|
@@ -40300,7 +40757,7 @@ function setLocalSecret(root, application, keyFile, name2, value) {
|
|
|
40300
40757
|
const secrets = readLocalSecrets(root, application, keyFile);
|
|
40301
40758
|
secrets[name2] = value;
|
|
40302
40759
|
key = externalKey(root, keyFile);
|
|
40303
|
-
const temporary = filename2 + "." +
|
|
40760
|
+
const temporary = filename2 + "." + randomUUID11() + ".tmp";
|
|
40304
40761
|
assertLocalStatePath(root, temporary);
|
|
40305
40762
|
writePrivate2(temporary, encrypt(root, application, key, secrets));
|
|
40306
40763
|
renameLocalFile(temporary, filename2);
|
|
@@ -40337,11 +40794,11 @@ async function localSecretsCommand(args2, root, application, input = process.std
|
|
|
40337
40794
|
|
|
40338
40795
|
// src/local-development.ts
|
|
40339
40796
|
function localManifest(root = process.cwd()) {
|
|
40340
|
-
const filename2 =
|
|
40341
|
-
if (!
|
|
40342
|
-
const manifest = parseApplicationManifest(
|
|
40797
|
+
const filename2 = join16(root, "backify.yaml");
|
|
40798
|
+
if (!existsSync14(filename2)) throw new Error("Create backify.yaml with version, application, runtime and explicit capabilities before running backify dev");
|
|
40799
|
+
const manifest = parseApplicationManifest(readFileSync22(filename2, "utf8"));
|
|
40343
40800
|
const entry = resolve18(root, manifest.runtime.entrypoint);
|
|
40344
|
-
if (!
|
|
40801
|
+
if (!existsSync14(entry) || !inside2(root, realpathSync5(entry))) throw new Error("Runtime entrypoint must exist inside this repository");
|
|
40345
40802
|
const discovered = analyzeSources(repositorySources(root));
|
|
40346
40803
|
const diagnostics = manifestDiagnostics(manifest, Object.keys(discovered.capabilities), discovered.capabilities.auth?.configuration);
|
|
40347
40804
|
if (diagnostics.length) throw new Error(diagnostics.map((diagnostic) => diagnostic.message).join("; "));
|
|
@@ -40352,12 +40809,12 @@ function inside2(root, path) {
|
|
|
40352
40809
|
return part !== ".." && !part.startsWith(".." + (process.platform === "win32" ? "\\" : "/")) && !isAbsolute13(part);
|
|
40353
40810
|
}
|
|
40354
40811
|
function sessionPath(root) {
|
|
40355
|
-
return
|
|
40812
|
+
return join16(root, ".backify", "dev", "session.json");
|
|
40356
40813
|
}
|
|
40357
40814
|
async function localRequest(path, input, root = process.cwd()) {
|
|
40358
40815
|
if (!/^\/v1\/[a-z/-]+$/.test(path)) throw new Error("Invalid local command path");
|
|
40359
|
-
if (!
|
|
40360
|
-
const session = JSON.parse(
|
|
40816
|
+
if (!existsSync14(sessionPath(root))) throw new Error("Start backify dev before using local commands");
|
|
40817
|
+
const session = JSON.parse(readFileSync22(sessionPath(root), "utf8"));
|
|
40361
40818
|
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
40819
|
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
40820
|
if (!response.ok) {
|
|
@@ -40408,17 +40865,17 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40408
40865
|
const identityProfiles = prepareLocalIdentity(root, options.identityUsers);
|
|
40409
40866
|
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
40867
|
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/"))
|
|
40868
|
+
const ignorePath = join16(root, ".gitignore");
|
|
40869
|
+
if (existsSync14(ignorePath) && lstatSync16(ignorePath).isSymbolicLink()) throw new Error("Local development cannot update a symlinked .gitignore");
|
|
40870
|
+
const ignore = existsSync14(ignorePath) ? readFileSync22(ignorePath, "utf8") : "";
|
|
40871
|
+
if (!ignore.split(/\r?\n/).some((line) => line.trim() === ".backify/")) writeFileSync12(ignorePath, ignore + (ignore.endsWith("\n") || !ignore ? "" : "\n") + ".backify/\n");
|
|
40415
40872
|
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 =
|
|
40873
|
+
const directory2 = join16(root, ".backify", "dev");
|
|
40417
40874
|
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,
|
|
40875
|
+
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
40876
|
mkdirSync6(directory2, { recursive: true });
|
|
40420
40877
|
if (!inside2(root, realpathSync5(directory2))) throw new Error("Local state directory must remain inside this repository");
|
|
40421
|
-
if (
|
|
40878
|
+
if (existsSync14(sessionPath(root))) {
|
|
40422
40879
|
try {
|
|
40423
40880
|
await localRequest("/v1/status", void 0, root);
|
|
40424
40881
|
throw new Error("Backify dev is already running for this repository");
|
|
@@ -40432,14 +40889,15 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40432
40889
|
if (jobWorker && mode !== "full") throw new Error("Native jobs require full-fidelity local mode");
|
|
40433
40890
|
const backendPort = options.backendPort === void 0 ? void 0 : await allocateLocalPort(options.backendPort);
|
|
40434
40891
|
const backendUrl = backendPort === void 0 ? void 0 : "http://127.0.0.1:" + backendPort;
|
|
40435
|
-
|
|
40892
|
+
let dashboardPort = await allocateLocalPort(options.port);
|
|
40893
|
+
const explicitPorts = [dashboardPort, backendPort, options.frontendPort, options.hcrPort, options.databasePort].filter((port) => port !== void 0 && port !== 0);
|
|
40436
40894
|
if (new Set(explicitPorts).size !== explicitPorts.length) throw new Error("Local service ports must be distinct");
|
|
40437
40895
|
const releaseLease = acquireLocalLease(root);
|
|
40438
40896
|
let services;
|
|
40439
40897
|
let frontend;
|
|
40440
40898
|
try {
|
|
40441
40899
|
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);
|
|
40900
|
+
if (preparedFrontend) frontend = await startLocalFrontend(preparedFrontend, options.frontendPort, backendUrl, options.onDiagnostic, identityProfiles ? "http://127.0.0.1:" + dashboardPort : void 0);
|
|
40443
40901
|
} catch (error2) {
|
|
40444
40902
|
try {
|
|
40445
40903
|
await services?.stop();
|
|
@@ -40449,14 +40907,14 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40449
40907
|
throw error2;
|
|
40450
40908
|
}
|
|
40451
40909
|
const token = randomBytes6(32).toString("hex");
|
|
40452
|
-
const identityScope = services?.identityScope ?? { organizationId:
|
|
40910
|
+
const identityScope = services?.identityScope ?? { organizationId: randomUUID12(), applicationId: randomUUID12(), environmentId: randomUUID12() };
|
|
40453
40911
|
const workerEnvironment = (worker) => {
|
|
40454
40912
|
if (!worker.authTrust) return worker;
|
|
40455
40913
|
const { renewal, ...authTrust } = worker.authTrust;
|
|
40456
40914
|
return { ...worker, authTrust };
|
|
40457
40915
|
};
|
|
40458
40916
|
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 =
|
|
40917
|
+
const outfile = join16(directory2, "worker.mjs");
|
|
40460
40918
|
let child;
|
|
40461
40919
|
const trustRenewal = createLocalJobTrustRenewal(root, authMounts, { onFailure: () => console.error("Native worker trust renewal unavailable; existing validity and pin guards remain enforced."), onUpdate: () => {
|
|
40462
40920
|
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 +40923,6 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40465
40923
|
} });
|
|
40466
40924
|
let buildContext;
|
|
40467
40925
|
let stopping = false;
|
|
40468
|
-
let dashboardPort = options.port ?? 0;
|
|
40469
40926
|
let dashboardOpened = false;
|
|
40470
40927
|
let restarting = Promise.resolve();
|
|
40471
40928
|
let resolveStartup = () => {
|
|
@@ -40494,8 +40951,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40494
40951
|
}
|
|
40495
40952
|
await stopChild(child);
|
|
40496
40953
|
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:
|
|
40954
|
+
const version2 = createHash13("sha256").update(readFileSync22(outfile)).update(services?.configurationFingerprint ?? "lightweight").digest("hex");
|
|
40955
|
+
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
40956
|
if (options.onDiagnostic) {
|
|
40500
40957
|
worker.stdout?.on("data", (chunk) => options.onDiagnostic(chunk.toString()));
|
|
40501
40958
|
worker.stderr?.on("data", (chunk) => options.onDiagnostic(chunk.toString()));
|
|
@@ -40521,7 +40978,7 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40521
40978
|
workerReady = true;
|
|
40522
40979
|
const session = { version: 1, port: message.port, token, pid: worker.pid };
|
|
40523
40980
|
const temp = sessionPath(root) + ".tmp";
|
|
40524
|
-
|
|
40981
|
+
writeFileSync12(temp, JSON.stringify(session), { mode: 384 });
|
|
40525
40982
|
renameLocalFile(temp, sessionPath(root));
|
|
40526
40983
|
const url2 = "http://127.0.0.1:" + message.port;
|
|
40527
40984
|
options.onReady?.(url2, { frontendUrl: frontend?.url, backendUrl });
|
|
@@ -40541,9 +40998,9 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40541
40998
|
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
40999
|
if (updated.runtime.entrypoint !== manifest.runtime.entrypoint) throw new Error("Runtime entrypoint changed; restart backify dev");
|
|
40543
41000
|
} catch (error2) {
|
|
40544
|
-
return { errors: [{ text: error2 instanceof Error ? error2.message : "Manifest validation failed" }], watchFiles: [
|
|
41001
|
+
return { errors: [{ text: error2 instanceof Error ? error2.message : "Manifest validation failed" }], watchFiles: [join16(root, "backify.yaml")] };
|
|
40545
41002
|
}
|
|
40546
|
-
return { contents:
|
|
41003
|
+
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
41004
|
});
|
|
40548
41005
|
build3.onEnd((result) => {
|
|
40549
41006
|
if (options.onDiagnostic) {
|
|
@@ -40602,8 +41059,8 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40602
41059
|
}
|
|
40603
41060
|
}
|
|
40604
41061
|
}
|
|
40605
|
-
if (
|
|
40606
|
-
const session = JSON.parse(
|
|
41062
|
+
if (existsSync14(sessionPath(root))) {
|
|
41063
|
+
const session = JSON.parse(readFileSync22(sessionPath(root), "utf8"));
|
|
40607
41064
|
if (session.token === token) unlinkSync5(sessionPath(root));
|
|
40608
41065
|
}
|
|
40609
41066
|
};
|
|
@@ -40617,11 +41074,11 @@ async function startLocalDevelopment(options = {}) {
|
|
|
40617
41074
|
}
|
|
40618
41075
|
async function runLocalTests(root = process.cwd()) {
|
|
40619
41076
|
const manifest = localManifest(root);
|
|
40620
|
-
const project = JSON.parse(
|
|
41077
|
+
const project = JSON.parse(readFileSync22(join16(root, "package.json"), "utf8"));
|
|
40621
41078
|
if (!project.scripts?.test) throw new Error("Add a test script to package.json so AI agents can run backify test");
|
|
40622
41079
|
const result = await new Promise((resolveResult, reject) => {
|
|
40623
|
-
const npmPath = process.platform === "win32" ? process.env.npm_execpath ??
|
|
40624
|
-
if (npmPath && !
|
|
41080
|
+
const npmPath = process.platform === "win32" ? process.env.npm_execpath ?? join16(dirname12(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : void 0;
|
|
41081
|
+
if (npmPath && !existsSync14(npmPath)) {
|
|
40625
41082
|
reject(new Error("Cannot locate npm-cli.js; run backify test through npx or npm"));
|
|
40626
41083
|
return;
|
|
40627
41084
|
}
|
|
@@ -40648,7 +41105,7 @@ function digest3(contents) {
|
|
|
40648
41105
|
}
|
|
40649
41106
|
function packageDirectory(filename2) {
|
|
40650
41107
|
for (let current = dirname13(filename2); ; current = dirname13(current)) {
|
|
40651
|
-
if (
|
|
41108
|
+
if (existsSync15(join17(current, "package.json"))) return current;
|
|
40652
41109
|
if (dirname13(current) === current) throw new Error("Cannot locate an installed dependency package");
|
|
40653
41110
|
}
|
|
40654
41111
|
}
|
|
@@ -40760,11 +41217,11 @@ async function prepareWorkload(options) {
|
|
|
40760
41217
|
context3.onResolve({ filter: /./ }, async (input) => {
|
|
40761
41218
|
if (input.pluginData?.backifyResolved) return;
|
|
40762
41219
|
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" ?
|
|
41220
|
+
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
41221
|
if (!resolved.external && !resolved.errors.length && resolved.path) {
|
|
40765
41222
|
const directory2 = realpathSync6(packageDirectory(resolved.path));
|
|
40766
41223
|
const target = relative8(directory2, realpathSync6(resolved.path)).replaceAll("\\", "/");
|
|
40767
|
-
if (JSON.parse(
|
|
41224
|
+
if (JSON.parse(readFileSync23(join17(directory2, "package.json"), "utf8")).name === "@backifydev/sdk") {
|
|
40768
41225
|
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
41226
|
}
|
|
40770
41227
|
if (!isAbsolute14(input.path) && !input.path.startsWith(".")) trustedPackages.add(directory2);
|
|
@@ -40828,28 +41285,28 @@ async function packageWorkload(options) {
|
|
|
40828
41285
|
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
41286
|
const output = resolve19(root, options.output ?? ".backify/artifacts/" + options.kind + "-" + plan.artifactVersion.slice(0, 16));
|
|
40830
41287
|
assertLocalStatePath(root, output);
|
|
40831
|
-
if (
|
|
41288
|
+
if (existsSync15(output)) {
|
|
40832
41289
|
if (JSON.stringify(readdirSync6(output).sort()) !== JSON.stringify(Object.keys(files).sort()) || Object.entries(files).some(([name2, value]) => {
|
|
40833
|
-
assertLocalStatePath(root,
|
|
40834
|
-
return !
|
|
41290
|
+
assertLocalStatePath(root, join17(output, name2));
|
|
41291
|
+
return !readFileSync23(join17(output, name2)).equals(Buffer.from(value));
|
|
40835
41292
|
})) throw new Error("Refusing to overwrite an existing workload artifact directory");
|
|
40836
41293
|
} else {
|
|
40837
41294
|
mkdirSync7(output, { recursive: true });
|
|
40838
|
-
for (const [name2, value] of Object.entries(files))
|
|
41295
|
+
for (const [name2, value] of Object.entries(files)) writeFileSync13(join17(output, name2), value, { flag: "wx", mode: 384 });
|
|
40839
41296
|
}
|
|
40840
41297
|
return { ...plan, outputDirectory: relative8(root, output).replaceAll("\\", "/") };
|
|
40841
41298
|
}
|
|
40842
41299
|
|
|
40843
41300
|
// src/workload-provenance.ts
|
|
40844
41301
|
import { execFileSync } from "node:child_process";
|
|
40845
|
-
import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as
|
|
41302
|
+
import { mkdirSync as mkdirSync8, mkdtempSync as mkdtempSync2, readdirSync as readdirSync7, rmSync as rmSync2, writeFileSync as writeFileSync14 } from "node:fs";
|
|
40846
41303
|
import { tmpdir } from "node:os";
|
|
40847
|
-
import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as
|
|
41304
|
+
import { basename as basename3, dirname as dirname15, isAbsolute as isAbsolute15, join as join19, relative as relative9, resolve as resolve21 } from "node:path";
|
|
40848
41305
|
|
|
40849
41306
|
// src/workload-provenance-oci.ts
|
|
40850
41307
|
import { createHash as createHash15 } from "node:crypto";
|
|
40851
|
-
import { createReadStream, lstatSync as
|
|
40852
|
-
import { dirname as dirname14, join as
|
|
41308
|
+
import { createReadStream, lstatSync as lstatSync17, readFileSync as readFileSync24 } from "node:fs";
|
|
41309
|
+
import { dirname as dirname14, join as join18, parse as parse3, resolve as resolve20 } from "node:path";
|
|
40853
41310
|
import { Transform, Writable } from "node:stream";
|
|
40854
41311
|
import { pipeline } from "node:stream/promises";
|
|
40855
41312
|
import { createGunzip } from "node:zlib";
|
|
@@ -40866,12 +41323,12 @@ function provenanceRef(value) {
|
|
|
40866
41323
|
function provenanceFile(filename2, maximum) {
|
|
40867
41324
|
const absolute = resolve20(filename2);
|
|
40868
41325
|
for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
|
|
40869
|
-
if (
|
|
41326
|
+
if (lstatSync17(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
|
|
40870
41327
|
if (ancestor === parse3(absolute).root) break;
|
|
40871
41328
|
}
|
|
40872
|
-
const stat =
|
|
41329
|
+
const stat = lstatSync17(absolute);
|
|
40873
41330
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size < 1 || stat.size > maximum) throw new Error("Invalid provenance file");
|
|
40874
|
-
const bytes =
|
|
41331
|
+
const bytes = readFileSync24(absolute);
|
|
40875
41332
|
if (bytes.length !== stat.size) throw new Error("Provenance file changed during read");
|
|
40876
41333
|
return bytes;
|
|
40877
41334
|
}
|
|
@@ -40880,7 +41337,7 @@ function descriptor(value) {
|
|
|
40880
41337
|
return value;
|
|
40881
41338
|
}
|
|
40882
41339
|
function blobPath(root, value) {
|
|
40883
|
-
return
|
|
41340
|
+
return join18(root, "blobs", "sha256", descriptor(value).digest.slice(7));
|
|
40884
41341
|
}
|
|
40885
41342
|
function jsonBlob(root, value) {
|
|
40886
41343
|
const bytes = provenanceFile(blobPath(root, value), 1024 * 1024);
|
|
@@ -40889,8 +41346,8 @@ function jsonBlob(root, value) {
|
|
|
40889
41346
|
}
|
|
40890
41347
|
async function inspectProvenanceImage(root, architecture, requestedDigest) {
|
|
40891
41348
|
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(
|
|
41349
|
+
if (JSON.parse(provenanceFile(join18(root, "oci-layout"), 1024).toString()).imageLayoutVersion !== "1.0.0") throw new Error("OCI layout required");
|
|
41350
|
+
const indexBytes = provenanceFile(join18(root, "index.json"), 1024 * 1024);
|
|
40894
41351
|
let current = JSON.parse(indexBytes.toString());
|
|
40895
41352
|
let selected;
|
|
40896
41353
|
let manifestDigest = provenanceHash(indexBytes);
|
|
@@ -40949,10 +41406,10 @@ async function inspectProvenanceImage(root, architecture, requestedDigest) {
|
|
|
40949
41406
|
function provenanceFileMetadata(filename2, expectedSize) {
|
|
40950
41407
|
const absolute = resolve20(filename2);
|
|
40951
41408
|
for (let ancestor = absolute; ; ancestor = dirname14(ancestor)) {
|
|
40952
|
-
if (
|
|
41409
|
+
if (lstatSync17(ancestor).isSymbolicLink()) throw new Error("Provenance paths must not contain links");
|
|
40953
41410
|
if (ancestor === parse3(absolute).root) break;
|
|
40954
41411
|
}
|
|
40955
|
-
const stat =
|
|
41412
|
+
const stat = lstatSync17(absolute);
|
|
40956
41413
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size !== expectedSize) throw new Error("Invalid OCI layer file");
|
|
40957
41414
|
}
|
|
40958
41415
|
function verifyBaseLineage(base, image2) {
|
|
@@ -41019,17 +41476,17 @@ async function captureWorkloadProvenance(options) {
|
|
|
41019
41476
|
if (!sha.test(commit) || !sha.test(tree)) throw new Error("Full Git commit and tree required");
|
|
41020
41477
|
const origin = git2(root, ["remote", "get-url", "origin"]);
|
|
41021
41478
|
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(
|
|
41479
|
+
const lockBytes = provenanceFile(join19(root, "package-lock.json"), 16 * 1024 * 1024);
|
|
41023
41480
|
const dependencies = dependencyMaterials(JSON.parse(lockBytes.toString("utf8")));
|
|
41024
41481
|
const context3 = resolve21(root, options.context);
|
|
41025
41482
|
if (canonical(readdirSync7(context3).sort()) !== canonical(contextNames)) throw new Error("Exact allowlisted workload context required");
|
|
41026
41483
|
const contextDigests = {};
|
|
41027
|
-
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(
|
|
41028
|
-
const plan = boundedJson(
|
|
41484
|
+
for (const name2 of contextNames) contextDigests[name2] = provenanceHash(provenanceFile(join19(context3, name2), name2 === "workload.mjs" ? 16 * 1024 * 1024 : 65536));
|
|
41485
|
+
const plan = boundedJson(join19(context3, "artifact.json"));
|
|
41029
41486
|
const baseDigest = provenanceRef(options.baseImage);
|
|
41030
41487
|
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
41488
|
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(
|
|
41489
|
+
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
41490
|
const base = await inspectProvenanceImage(resolve21(root, options.baseLayout), options.architecture, baseDigest);
|
|
41034
41491
|
const image2 = await inspectProvenanceImage(resolve21(root, options.imageLayout), options.architecture);
|
|
41035
41492
|
verifyBaseLineage(base, image2);
|
|
@@ -41105,16 +41562,16 @@ function verifyWorkloadProvenance(options, now = /* @__PURE__ */ new Date()) {
|
|
|
41105
41562
|
evidence.push({ bytes: baseSubject, bundle: provenanceFile(options.baseBundle, 4 * 1024 * 1024), identity: { ...policy, ...supplier } });
|
|
41106
41563
|
}
|
|
41107
41564
|
const scratchRoot = resolve21(tmpdir());
|
|
41108
|
-
const scratch = mkdtempSync2(
|
|
41565
|
+
const scratch = mkdtempSync2(join19(scratchRoot, "backify-provenance-"));
|
|
41109
41566
|
if (dirname15(scratch) !== scratchRoot || !basename3(scratch).startsWith("backify-provenance-")) throw new Error("Unsafe provenance evidence directory");
|
|
41110
41567
|
try {
|
|
41111
|
-
mkdirSync8(
|
|
41112
|
-
const trustedRoot =
|
|
41113
|
-
|
|
41568
|
+
mkdirSync8(join19(scratch, "evidence"), { mode: 448 });
|
|
41569
|
+
const trustedRoot = join19(scratch, "evidence", "trusted-root.jsonl");
|
|
41570
|
+
writeFileSync14(trustedRoot, rootBytes, { flag: "wx", mode: 384 });
|
|
41114
41571
|
for (const [index, { bytes, bundle: bundleBytes, identity }] of evidence.entries()) {
|
|
41115
|
-
const report =
|
|
41116
|
-
|
|
41117
|
-
|
|
41572
|
+
const report = join19(scratch, "evidence", "report-" + index + ".json"), bundle = join19(scratch, "evidence", "bundle-" + index + ".jsonl");
|
|
41573
|
+
writeFileSync14(report, bytes, { flag: "wx", mode: 384 });
|
|
41574
|
+
writeFileSync14(bundle, bundleBytes, { flag: "wx", mode: 384 });
|
|
41118
41575
|
try {
|
|
41119
41576
|
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
41577
|
if (!Array.isArray(JSON.parse(result)) || !JSON.parse(result).length) throw new Error();
|
|
@@ -41145,12 +41602,12 @@ async function workloadProvenanceCommand(args2) {
|
|
|
41145
41602
|
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
41603
|
}
|
|
41147
41604
|
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
|
-
|
|
41605
|
+
writeFileSync14(resolve21(required2("--output")), JSON.stringify(result, null, 2) + "\n", { flag: "wx", mode: 384 });
|
|
41149
41606
|
return { schemaVersion: 1, status: "captured-unsigned", deploymentReady: false, reportDigest: provenanceHash(JSON.stringify(result, null, 2) + "\n") };
|
|
41150
41607
|
}
|
|
41151
41608
|
|
|
41152
41609
|
// src/workload-trust-state.ts
|
|
41153
|
-
import { lstatSync as
|
|
41610
|
+
import { lstatSync as lstatSync18, readFileSync as readFileSync25 } from "node:fs";
|
|
41154
41611
|
import { isAbsolute as isAbsolute16, resolve as resolve22 } from "node:path";
|
|
41155
41612
|
function parseWorkloadTrustState(args2) {
|
|
41156
41613
|
const action = args2[0];
|
|
@@ -41176,9 +41633,9 @@ function workloadTrustState(options) {
|
|
|
41176
41633
|
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
41634
|
let trust;
|
|
41178
41635
|
try {
|
|
41179
|
-
const metadata =
|
|
41636
|
+
const metadata = lstatSync18(options.trustFile);
|
|
41180
41637
|
if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink !== 1 || metadata.size > 131072) throw new Error();
|
|
41181
|
-
const bytes =
|
|
41638
|
+
const bytes = readFileSync25(options.trustFile);
|
|
41182
41639
|
if (bytes.length > 131072) throw new Error();
|
|
41183
41640
|
trust = JSON.parse(new TextDecoder("utf8", { fatal: true }).decode(bytes));
|
|
41184
41641
|
} catch {
|
|
@@ -41194,8 +41651,8 @@ function workloadTrustState(options) {
|
|
|
41194
41651
|
}
|
|
41195
41652
|
|
|
41196
41653
|
// src/scaffold.ts
|
|
41197
|
-
import { existsSync as
|
|
41198
|
-
import { dirname as dirname16, join as
|
|
41654
|
+
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";
|
|
41655
|
+
import { dirname as dirname16, join as join20, relative as relative10, resolve as resolve23 } from "node:path";
|
|
41199
41656
|
|
|
41200
41657
|
// src/task-template.ts
|
|
41201
41658
|
function json2(value) {
|
|
@@ -41603,20 +42060,20 @@ provider-readiness claim, cloud deployment or browser authentication is implied.
|
|
|
41603
42060
|
function scaffoldFullStack(options) {
|
|
41604
42061
|
const files = fullStackTemplate(options.appId, options.name, options.template);
|
|
41605
42062
|
const root = resolve23(options.root ?? process.cwd());
|
|
41606
|
-
if (!
|
|
42063
|
+
if (!existsSync16(root) || !lstatSync19(root).isDirectory() || lstatSync19(root).isSymbolicLink()) throw new Error("Scaffold destination must be an existing non-linked directory");
|
|
41607
42064
|
const allowed = /* @__PURE__ */ new Set([...Object.keys(files).map((filename2) => filename2.split("/")[0]), ".git", "node_modules", "package-lock.json", ".backify"]);
|
|
41608
42065
|
if (readdirSync8(root).some((filename2) => !allowed.has(filename2))) throw new Error("Scaffolding requires an empty folder or an unchanged generated starter");
|
|
41609
42066
|
const canonicalRoot = realpathSync7(root);
|
|
41610
42067
|
const pending = [];
|
|
41611
42068
|
for (const [filename2, content] of Object.entries(files)) {
|
|
41612
|
-
const destination =
|
|
42069
|
+
const destination = join20(root, filename2);
|
|
41613
42070
|
let current = destination;
|
|
41614
42071
|
while (current !== root) {
|
|
41615
42072
|
try {
|
|
41616
|
-
const stat =
|
|
42073
|
+
const stat = lstatSync19(current);
|
|
41617
42074
|
if (stat.isSymbolicLink() || current !== destination && !stat.isDirectory()) throw new Error("Scaffolding refuses linked or invalid output paths: " + filename2);
|
|
41618
42075
|
if (relative10(canonicalRoot, realpathSync7(current)).startsWith("..")) throw new Error("Scaffold output must remain inside its directory");
|
|
41619
|
-
if (current === destination && (!stat.isFile() ||
|
|
42076
|
+
if (current === destination && (!stat.isFile() || readFileSync26(current, "utf8") !== content)) throw new Error("Scaffolding refuses to overwrite existing content: " + filename2);
|
|
41620
42077
|
} catch (error2) {
|
|
41621
42078
|
if (!(error2 instanceof Error) || !("code" in error2) || error2.code !== "ENOENT") throw error2;
|
|
41622
42079
|
if (current === destination) pending.push(filename2);
|
|
@@ -41625,9 +42082,9 @@ function scaffoldFullStack(options) {
|
|
|
41625
42082
|
}
|
|
41626
42083
|
}
|
|
41627
42084
|
for (const filename2 of pending) {
|
|
41628
|
-
const destination =
|
|
42085
|
+
const destination = join20(root, filename2);
|
|
41629
42086
|
mkdirSync9(dirname16(destination), { recursive: true });
|
|
41630
|
-
|
|
42087
|
+
writeFileSync15(destination, files[filename2], { flag: "wx" });
|
|
41631
42088
|
}
|
|
41632
42089
|
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
42090
|
}
|
|
@@ -41671,16 +42128,16 @@ function localInspectionCommand(args2) {
|
|
|
41671
42128
|
}
|
|
41672
42129
|
|
|
41673
42130
|
// src/index.ts
|
|
41674
|
-
import { readFileSync as
|
|
42131
|
+
import { readFileSync as readFileSync29, existsSync as existsSync18, rmSync as rmSync3 } from "node:fs";
|
|
41675
42132
|
import { homedir as homedir3 } from "node:os";
|
|
41676
|
-
import { join as
|
|
42133
|
+
import { join as join23 } from "node:path";
|
|
41677
42134
|
import { spawn as spawn5 } from "node:child_process";
|
|
41678
42135
|
var [command2, ...args] = process.argv.slice(2);
|
|
41679
|
-
var configPath =
|
|
41680
|
-
var userConfig = command2 !== "mcp" &&
|
|
42136
|
+
var configPath = join23(homedir3(), ".backify.json");
|
|
42137
|
+
var userConfig = command2 !== "mcp" && existsSync18(configPath) ? JSON.parse(readFileSync29(configPath, "utf8")) : {};
|
|
41681
42138
|
async function call(path, init) {
|
|
41682
42139
|
let appId = option("--app");
|
|
41683
|
-
if (!appId &&
|
|
42140
|
+
if (!appId && existsSync18(join23(process.cwd(), "backify.json"))) appId = projectApplication();
|
|
41684
42141
|
const session = appId ? userConfig.sessions?.[sessionKey(appId)] : void 0;
|
|
41685
42142
|
const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
|
|
41686
42143
|
return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
|
|
@@ -41744,9 +42201,47 @@ async function main() {
|
|
|
41744
42201
|
console.error(args.includes("--dry-run") ? "Preview only; no files changed." : result.transport === "stdio" ? "Restart your coding tool. Sign in with backify login --organization <organization-id> --organization-access." : "Restart your coding tool, connect Backify and approve organization access in your browser. The deployed MCP and portal must support OAuth.");
|
|
41745
42202
|
break;
|
|
41746
42203
|
}
|
|
42204
|
+
case "domains": {
|
|
42205
|
+
if (args[0] !== "connect" || args.includes("--help")) {
|
|
42206
|
+
console.log(domainConnectHelp);
|
|
42207
|
+
if (args[0] !== "connect" && !args.includes("--help")) process.exitCode = 2;
|
|
42208
|
+
break;
|
|
42209
|
+
}
|
|
42210
|
+
const options = domainConnectArguments(args.slice(1)), controller = new AbortController(), stop = () => controller.abort();
|
|
42211
|
+
process.once("SIGINT", stop);
|
|
42212
|
+
process.once("SIGTERM", stop);
|
|
42213
|
+
try {
|
|
42214
|
+
const result = await connectDomain(call, { ...options, applicationId: applicationGuid(option("--app") ?? projectApplication()), portalUrl: process.env.BACKIFY_PORTAL_URL ?? userConfig.portalUrl ?? "https://portal.backify.dev", openBrowser, progress: (message) => console.error(message), signal: controller.signal });
|
|
42215
|
+
console.log(JSON.stringify(result, null, 2));
|
|
42216
|
+
if (!result.confirmed) process.exitCode = 2;
|
|
42217
|
+
} finally {
|
|
42218
|
+
process.removeListener("SIGINT", stop);
|
|
42219
|
+
process.removeListener("SIGTERM", stop);
|
|
42220
|
+
}
|
|
42221
|
+
break;
|
|
42222
|
+
}
|
|
41747
42223
|
case "integrations": {
|
|
41748
|
-
|
|
41749
|
-
|
|
42224
|
+
if (args[0] === "connect") {
|
|
42225
|
+
if (args.includes("--help")) {
|
|
42226
|
+
console.log(integrationConnectHelp);
|
|
42227
|
+
break;
|
|
42228
|
+
}
|
|
42229
|
+
const options = integrationConnectArguments(args.slice(1));
|
|
42230
|
+
const controller = new AbortController(), stop = () => controller.abort();
|
|
42231
|
+
process.once("SIGINT", stop);
|
|
42232
|
+
process.once("SIGTERM", stop);
|
|
42233
|
+
try {
|
|
42234
|
+
const result = await connectIntegration(call, { ...options, applicationId: applicationGuid(option("--app") ?? projectApplication()), portalUrl: process.env.BACKIFY_PORTAL_URL ?? userConfig.portalUrl ?? "https://portal.backify.dev", openBrowser, progress: (message) => console.error(message), signal: controller.signal });
|
|
42235
|
+
console.log(JSON.stringify(result, null, 2));
|
|
42236
|
+
if (result.state !== "ready" && !("userConnectionFlowRequired" in result && result.userConnectionFlowRequired)) process.exitCode = 2;
|
|
42237
|
+
} finally {
|
|
42238
|
+
process.removeListener("SIGINT", stop);
|
|
42239
|
+
process.removeListener("SIGTERM", stop);
|
|
42240
|
+
}
|
|
42241
|
+
break;
|
|
42242
|
+
}
|
|
42243
|
+
const path = integrationDiscoveryPath(args[0], { applicationId: applicationGuid(option("--app") ?? projectApplication()), connectionId: option("--connection"), operationId: option("--operation"), query: option("--query"), offset: Number(option("--offset") ?? 0), adoptionId: option("--adoption"), revisionId: option("--revision") });
|
|
42244
|
+
const value = await call(path, args[0] === "prepare" ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(integrationPreparation({ definitionId: option("--definition"), revisionId: option("--revision"), environmentId: option("--environment"), mode: option("--mode"), operations: option("--operations") })) } : void 0);
|
|
41750
42245
|
if (args[0] === "types") console.log(value.source);
|
|
41751
42246
|
else console.log(JSON.stringify(value, null, 2));
|
|
41752
42247
|
break;
|
|
@@ -41843,7 +42338,7 @@ async function main() {
|
|
|
41843
42338
|
const name2 = option("--name");
|
|
41844
42339
|
if (!name2) throw new Error("Specify --name <job>");
|
|
41845
42340
|
const payload = option("--payload");
|
|
41846
|
-
console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(
|
|
42341
|
+
console.log(JSON.stringify(await localRequest("/v1/jobs/run", { name: name2, payload: payload ? JSON.parse(readFileSync29(payload, "utf8")) : null }), null, 2));
|
|
41847
42342
|
} else if (["retry", "cancel"].includes(args[0])) {
|
|
41848
42343
|
const id = option("--id");
|
|
41849
42344
|
if (!id) throw new Error("Specify --id <run>");
|
|
@@ -41866,7 +42361,7 @@ async function main() {
|
|
|
41866
42361
|
const environmentId = option("--environment");
|
|
41867
42362
|
const packagePath = option("--package");
|
|
41868
42363
|
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(
|
|
42364
|
+
await deployFunctions(call, appId, applicationGuid(environmentId), new Uint8Array(readFileSync29(packagePath)), { progress: (message) => console.log(message) });
|
|
41870
42365
|
console.log("Functions deployed.");
|
|
41871
42366
|
} else throw new Error("Use backify functions package or backify functions deploy");
|
|
41872
42367
|
break;
|
|
@@ -41885,6 +42380,11 @@ async function main() {
|
|
|
41885
42380
|
synchronize(process.cwd(), option("--agent"), option("--instruction-file"));
|
|
41886
42381
|
console.log("Backify instructions synchronized to version " + INSTRUCTION_VERSION);
|
|
41887
42382
|
break;
|
|
42383
|
+
case "upgrade": {
|
|
42384
|
+
if (args.some((value) => value !== "--json")) throw new Error("Use backify upgrade [--json]. Only stable compatible SDK releases are selected automatically.");
|
|
42385
|
+
console.log(JSON.stringify(upgradeSdk(), null, 2));
|
|
42386
|
+
break;
|
|
42387
|
+
}
|
|
41888
42388
|
case "doctor": {
|
|
41889
42389
|
if (args.includes("--environment")) {
|
|
41890
42390
|
const result2 = await diagnoseEnvironment(process.cwd(), { network: args.includes("--network"), capability: option("--capability") });
|
|
@@ -41902,7 +42402,7 @@ async function main() {
|
|
|
41902
42402
|
userConfig.token = args[0];
|
|
41903
42403
|
userConfig.organizationId = args[1] ?? userConfig.organizationId;
|
|
41904
42404
|
saveUserConfig(configPath, userConfig);
|
|
41905
|
-
} else await browserLogin(args.includes("--organization-access") ? void 0 : option("--app") ?? (
|
|
42405
|
+
} else await browserLogin(args.includes("--organization-access") ? void 0 : option("--app") ?? (existsSync18(join23(process.cwd(), "backify.json")) ? projectApplication() : void 0), option("--organization"));
|
|
41906
42406
|
console.log("Logged in to Backify");
|
|
41907
42407
|
break;
|
|
41908
42408
|
case "logout":
|
|
@@ -41941,7 +42441,7 @@ async function main() {
|
|
|
41941
42441
|
userConfig.sessions[key] ??= session;
|
|
41942
42442
|
saveUserConfig(configPath, userConfig);
|
|
41943
42443
|
if (args.includes("--clone")) await cloneProject(client, appId);
|
|
41944
|
-
else if (
|
|
42444
|
+
else if (existsSync18(join23(process.cwd(), ".git"))) {
|
|
41945
42445
|
const update = await pullProject(client, appId);
|
|
41946
42446
|
console.log(JSON.stringify(update, null, 2));
|
|
41947
42447
|
if (update.status === "blocked") throw new Error(update.reason);
|
|
@@ -42004,7 +42504,7 @@ async function main() {
|
|
|
42004
42504
|
} else if (args[0] === "install") {
|
|
42005
42505
|
const version2 = option("--version"), sha256 = option("--sha256");
|
|
42006
42506
|
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") ?
|
|
42507
|
+
const bytes = option("--archive") ? readFileSync29(option("--archive")) : await downloadLocalRuntime(version2);
|
|
42008
42508
|
console.log(JSON.stringify(installLocalRuntime(bytes, { version: version2, sha256 }), null, 2));
|
|
42009
42509
|
} else throw new Error("Use backify runtime install or backify runtime doctor");
|
|
42010
42510
|
break;
|
|
@@ -42019,7 +42519,7 @@ async function main() {
|
|
|
42019
42519
|
case "request": {
|
|
42020
42520
|
const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
|
|
42021
42521
|
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(
|
|
42522
|
+
const configuration = configurationFile ? JSON.parse(readFileSync29(configurationFile, "utf8")) : void 0;
|
|
42023
42523
|
console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
|
|
42024
42524
|
break;
|
|
42025
42525
|
}
|
|
@@ -42037,7 +42537,7 @@ async function main() {
|
|
|
42037
42537
|
else if (args[0] === "test") {
|
|
42038
42538
|
const name2 = option("--name"), payload = option("--payload");
|
|
42039
42539
|
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(
|
|
42540
|
+
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
42541
|
} else throw new Error("Use backify events environments|inspect|test");
|
|
42042
42542
|
break;
|
|
42043
42543
|
}
|
|
@@ -42048,7 +42548,7 @@ async function main() {
|
|
|
42048
42548
|
console.log(await call("/apps/" + applicationGuid(args[0]) + "/deployments/preview", { method: "POST", body: JSON.stringify({ sourceRevision: args[1] ?? "latest" }) }));
|
|
42049
42549
|
break;
|
|
42050
42550
|
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");
|
|
42551
|
+
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 | domains connect [hostname] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types | workload plan|package|artifact-plan|trust-state|trust-sync|provenance capture|verify | apps | deploy");
|
|
42052
42552
|
}
|
|
42053
42553
|
}
|
|
42054
42554
|
main().catch((error2) => {
|